TypscriptLanguageExtension.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. //
  2. // Copyright (c) 2014-2016 THUNDERBEAST GAMES LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. import * as EditorEvents from "../../editor/EditorEvents";
  23. /**
  24. * Default compiler options to use for compilation. If there
  25. * is a compiler option block in a tsconfig.json located in the project,
  26. * then the one in the project will overwrite these
  27. * @type {ts.CompilerOptions}
  28. */
  29. const defaultCompilerOptions = {
  30. noEmitOnError: true,
  31. noImplicitAny: false,
  32. target: "es5",
  33. module: "commonjs",
  34. declaration: false,
  35. inlineSourceMap: false,
  36. removeComments: false,
  37. noLib: false,
  38. forceConsistentCasingInFileNames: true,
  39. allowJs: true,
  40. lib: ["es5"]
  41. };
  42. /**
  43. * Resource extension that supports the web view typescript extension
  44. */
  45. export default class TypescriptLanguageExtension implements Editor.HostExtensions.ResourceServicesEventListener, Editor.HostExtensions.ProjectServicesEventListener {
  46. name: string = "HostTypeScriptLanguageExtension";
  47. description: string = "This service supports the typscript webview extension.";
  48. /**
  49. * Indicates if this project contains typescript files.
  50. * @type {Boolean}
  51. */
  52. private isTypescriptProject = false;
  53. private serviceRegistry: Editor.HostExtensions.HostServiceLocator = null;
  54. private menuCreated = false;
  55. /** Reference to the compileOnSaveMenuItem */
  56. private compileOnSaveMenuItem: Atomic.UIMenuItem;
  57. /**
  58. * Determines if the file name/path provided is something we care about
  59. * @param {string} path
  60. * @return {boolean}
  61. */
  62. private isValidFiletype(path: string): boolean {
  63. const ext = Atomic.getExtension(path);
  64. if (ext == ".ts" || ext == ".js") {
  65. return true;
  66. }
  67. }
  68. /**
  69. * Build an in-memory config file to be sent down to the web view client. This will scan the resources directory
  70. * and generate a file list
  71. */
  72. private buildTsConfig(): any {
  73. // only build out a tsconfig.atomic if we actually have typescript files in the project
  74. let projectFiles: Array<string> = [];
  75. const slashedProjectPath = Atomic.addTrailingSlash(ToolCore.toolSystem.project.projectPath);
  76. //scan all the files in the project for any typescript files and add them to the project
  77. Atomic.fileSystem.scanDir(ToolCore.toolSystem.project.resourcePath, "*.ts", Atomic.SCAN_FILES, true).forEach(filename => {
  78. // Don't grab d.ts files yet. We'll do that in a separate pass
  79. if (filename.search(/d.ts$/i) == -1) {
  80. projectFiles.push(Atomic.addTrailingSlash(ToolCore.toolSystem.project.resourcePath) + filename);
  81. if (!this.isTypescriptProject) {
  82. this.isTypescriptProject = true;
  83. }
  84. }
  85. });
  86. //Scan for any d.ts files in the root
  87. Atomic.fileSystem.scanDir(ToolCore.toolSystem.project.projectPath, "*.d.ts", Atomic.SCAN_FILES, true).forEach(filename => {
  88. projectFiles.push(Atomic.addTrailingSlash(ToolCore.toolSystem.project.projectPath) + filename);
  89. if (!this.isTypescriptProject) {
  90. this.isTypescriptProject = true;
  91. }
  92. });
  93. let compilerOptions = defaultCompilerOptions;
  94. Atomic.fileSystem.scanDir(ToolCore.toolSystem.project.resourcePath, "*.js", Atomic.SCAN_FILES, true).forEach(filename => {
  95. let fn = Atomic.addTrailingSlash(ToolCore.toolSystem.project.resourcePath) + filename;
  96. projectFiles.push(Atomic.addTrailingSlash(ToolCore.toolSystem.project.resourcePath) + filename);
  97. });
  98. // First we need to load in a copy of the lib.es6.d.ts that is necessary for the hosted typescript compiler
  99. projectFiles.push(Atomic.addTrailingSlash(Atomic.addTrailingSlash(ToolCore.toolEnvironment.toolDataDir) + "TypeScriptSupport") + "lib.es5.d.ts");
  100. const tsconfigFn = Atomic.addTrailingSlash(ToolCore.toolSystem.project.projectPath) + "tsconfig.json";
  101. // Let's look for a tsconfig.json file in the project root and add any additional files
  102. if (Atomic.fileSystem.fileExists(tsconfigFn)) {
  103. // load up the tsconfig file and parse out the files block and compare it to what we have
  104. // in resources
  105. const file = new Atomic.File(tsconfigFn, Atomic.FILE_READ);
  106. try {
  107. const savedTsConfig = JSON.parse(file.readText());
  108. if (savedTsConfig["files"]) {
  109. savedTsConfig["files"].forEach((file: string) => {
  110. let newFile = Atomic.addTrailingSlash(ToolCore.toolSystem.project.projectPath) + file;
  111. let exists = false;
  112. if (Atomic.fileSystem.fileExists(newFile)) {
  113. exists = true;
  114. file = newFile;
  115. } else if (Atomic.fileSystem.exists(file)) {
  116. exists = true;
  117. }
  118. if (exists && projectFiles.indexOf(file) == -1) {
  119. projectFiles.push(file);
  120. }
  121. });
  122. }
  123. // override the default options if the tsconfig contains them
  124. if (savedTsConfig["compilerOptions"]) {
  125. compilerOptions = savedTsConfig["compilerOptions"];
  126. }
  127. } finally {
  128. file.close();
  129. }
  130. };
  131. // Then see if we have a copy of Atomic.d.ts in the project directory. If we don't then we should load it up from the tool environment
  132. let found = false;
  133. projectFiles.forEach((file) => {
  134. if (file.toLowerCase().indexOf("atomic.d.ts") != -1) {
  135. found = true;
  136. }
  137. });
  138. if (!found) {
  139. // Load up the Atomic.d.ts from the tool core
  140. projectFiles.push(Atomic.addTrailingSlash(Atomic.addTrailingSlash(ToolCore.toolEnvironment.toolDataDir) + "TypeScriptSupport") + "Atomic.d.ts");
  141. }
  142. // set the base url
  143. compilerOptions["baseUrl"] = ToolCore.toolSystem.project.resourcePath;
  144. let tsConfig = {
  145. compilerOptions: compilerOptions,
  146. files: projectFiles
  147. };
  148. return tsConfig;
  149. }
  150. /**
  151. * Configures the project to be a Typescript Project
  152. * @return {[type]}
  153. */
  154. private configureTypescriptProjectMenu() {
  155. if (this.isTypescriptProject && !this.menuCreated) {
  156. const isCompileOnSave = this.serviceRegistry.projectServices.getUserPreference(this.name, "CompileOnSave", false);
  157. // Build the menu - First build up an empty menu then manually add the items so we can have reference to them
  158. const menu = this.serviceRegistry.uiServices.createPluginMenuItemSource("TypeScript", {});
  159. this.compileOnSaveMenuItem = new Atomic.UIMenuItem(`Compile on Save: ${isCompileOnSave ? "On" : "Off"}`, `${this.name}.compileonsave`);
  160. menu.addItem(this.compileOnSaveMenuItem);
  161. menu.addItem(new Atomic.UIMenuItem("Compile Project", `${this.name}.compileproject`));
  162. menu.addItem(new Atomic.UIMenuItem("Generate External Editor Project", `${this.name}.generateexternalproject`));
  163. this.menuCreated = true;
  164. }
  165. }
  166. /**
  167. * Inject this language service into the registry
  168. * @return {[type]} True if successful
  169. */
  170. initialize(serviceLocator: Editor.HostExtensions.HostServiceLocator) {
  171. // We care about both resource events as well as project events
  172. serviceLocator.resourceServices.register(this);
  173. serviceLocator.projectServices.register(this);
  174. serviceLocator.uiServices.register(this);
  175. this.serviceRegistry = serviceLocator;
  176. }
  177. /**
  178. * Handle when a new file is loaded and we have not yet configured the editor for TS.
  179. * This could be when someone adds a TS file to a vanilla project
  180. * @param {Editor.EditorEvents.EditResourceEvent} ev
  181. */
  182. edit(ev: Editor.EditorEvents.EditResourceEvent) {
  183. if (this.isValidFiletype(ev.path)) {
  184. // update ts config in case we have a new resource
  185. let tsConfig = this.buildTsConfig();
  186. this.setTsConfigOnWebView(tsConfig);
  187. if (this.isTypescriptProject) {
  188. this.configureTypescriptProjectMenu();
  189. }
  190. }
  191. }
  192. /**
  193. * Handle the delete. This should delete the corresponding javascript file
  194. * @param {Editor.EditorEvents.DeleteResourceEvent} ev
  195. */
  196. delete(ev: Editor.EditorEvents.DeleteResourceEvent) {
  197. if (this.isValidFiletype(ev.path)) {
  198. // console.log(`${this.name}: received a delete resource event`);
  199. // Delete the corresponding js file
  200. let jsFile = ev.path.replace(/\.ts$/, ".js");
  201. let jsFileAsset = ToolCore.assetDatabase.getAssetByPath(jsFile);
  202. if (jsFileAsset) {
  203. console.log(`${this.name}: deleting corresponding .js file`);
  204. ToolCore.assetDatabase.deleteAsset(jsFileAsset);
  205. let eventData: EditorEvents.DeleteResourceEvent = {
  206. path: jsFile
  207. };
  208. this.setTsConfigOnWebView(this.buildTsConfig());
  209. this.serviceRegistry.sendEvent(EditorEvents.DeleteResourceNotification, eventData);
  210. }
  211. }
  212. }
  213. /**
  214. * Handle the rename. Should rename the corresponding .js file
  215. * @param {Editor.EditorEvents.RenameResourceEvent} ev
  216. */
  217. rename(ev: Editor.EditorEvents.RenameResourceEvent) {
  218. if (this.isValidFiletype(ev.path)) {
  219. // console.log(`${this.name}: received a rename resource event`);
  220. // Rename the corresponding js file
  221. let jsFile = ev.path.replace(/\.ts$/, ".js");
  222. let jsFileNew = ev.newPath.replace(/\.ts$/, ".js"); // rename doesn't want extension
  223. let jsFileAsset = ToolCore.assetDatabase.getAssetByPath(jsFile);
  224. if (jsFileAsset) {
  225. console.log(`${this.name}: renaming corresponding .js file`);
  226. jsFileAsset.rename(ev.newName);
  227. let eventData: EditorEvents.RenameResourceEvent = {
  228. path: jsFile,
  229. newPath: jsFileNew,
  230. newName: ev.newName,
  231. asset: jsFileAsset
  232. };
  233. this.setTsConfigOnWebView(this.buildTsConfig());
  234. this.serviceRegistry.sendEvent(EditorEvents.RenameResourceNotification, eventData);
  235. }
  236. }
  237. }
  238. /**
  239. * Handles the save event and detects if a typescript file has been added to a non-typescript project
  240. * @param {Editor.EditorEvents.SaveResourceEvent} ev
  241. * @return {[type]}
  242. */
  243. save(ev: Editor.EditorEvents.SaveResourceEvent) {
  244. // let's check to see if we have created a typescript file
  245. if (!this.isTypescriptProject) {
  246. if (Atomic.getExtension(ev.path) == ".ts") {
  247. this.isTypescriptProject = true;
  248. this.setTsConfigOnWebView(this.buildTsConfig());
  249. }
  250. }
  251. }
  252. /*** ProjectService implementation ****/
  253. /**
  254. * Called when the project is being loaded to allow the typscript language service to reset and
  255. * possibly compile
  256. */
  257. projectLoaded(ev: Editor.EditorEvents.LoadProjectEvent) {
  258. // got a load, we need to reset the language service
  259. this.isTypescriptProject = false;
  260. //scan all the files in the project for any typescript files so we can determine if this is a typescript project
  261. if (Atomic.fileSystem.scanDir(ToolCore.toolSystem.project.resourcePath, "*.ts", Atomic.SCAN_FILES, true).length > 0) {
  262. this.isTypescriptProject = true;
  263. this.configureTypescriptProjectMenu();
  264. };
  265. }
  266. /**
  267. * Called when the project is unloaded
  268. */
  269. projectUnloaded() {
  270. // Clean up
  271. this.serviceRegistry.uiServices.removePluginMenuItemSource("TypeScript");
  272. this.compileOnSaveMenuItem = null;
  273. this.menuCreated = false;
  274. this.isTypescriptProject = false;
  275. }
  276. /*** UIService implementation ***/
  277. /**
  278. * Called when a plugin menu item is clicked
  279. * @param {string} refId
  280. * @return {boolean}
  281. */
  282. menuItemClicked(refId: string): boolean {
  283. let [extension, action] = refId.split(".");
  284. if (extension == this.name) {
  285. switch (action) {
  286. case "compileonsave":
  287. let isCompileOnSave = this.serviceRegistry.projectServices.getUserPreference(this.name, "CompileOnSave", false);
  288. // Toggle
  289. isCompileOnSave = !isCompileOnSave;
  290. this.serviceRegistry.projectServices.setUserPreference(this.name, "CompileOnSave", isCompileOnSave);
  291. this.compileOnSaveMenuItem.string = `Compile on Save: ${isCompileOnSave ? "On" : "Off"}`;
  292. return true;
  293. case "compileproject":
  294. this.doFullCompile();
  295. return true;
  296. case "generateexternalproject":
  297. this.generateExternalProject();
  298. return true;
  299. }
  300. }
  301. }
  302. /**
  303. * Handle messages that are submitted via Atomic.Query from within a web view editor.
  304. * @param message The message type that was submitted to be used to determine what the data contains if present
  305. * @param data any additional data that needs to be submitted with the message
  306. */
  307. handleWebMessage(messageType: string, data: any) {
  308. switch (messageType) {
  309. case "TypeScript.DisplayCompileResults":
  310. this.displayCompileResults(data);
  311. break;
  312. }
  313. }
  314. setTsConfigOnWebView(tsConfig: any) {
  315. WebView.WebBrowserHost.setGlobalStringProperty("TypeScriptLanguageExtension", "tsConfig", JSON.stringify(tsConfig));
  316. }
  317. generateExternalProject () {
  318. const projectDir = ToolCore.toolSystem.project.projectPath;
  319. // Create the typings folder in project root
  320. const projectDirTypings = Atomic.addTrailingSlash(projectDir + "typings/ambient/atomicgameengine");
  321. Atomic.getFileSystem().createDir(projectDirTypings);
  322. // Copy the Atomic.d.ts definition file to the typings folder
  323. const toolDataDir = ToolCore.toolEnvironment.toolDataDir;
  324. const typescriptSupportDir = Atomic.addTrailingSlash(toolDataDir + "TypeScriptSupport");
  325. Atomic.getFileSystem().copy(typescriptSupportDir + "Atomic.d.ts", projectDirTypings + "Atomic.d.ts");
  326. // Generate a tsconfig.json file
  327. const tsconfigFile = new Atomic.File(projectDir + "tsconfig.json", Atomic.FILE_WRITE);
  328. let tsconfig = {
  329. compilerOptions: defaultCompilerOptions
  330. };
  331. // Don't use fully qualified path in the persistent tsconfig file, just use a relative path from the tsconfig
  332. tsconfig.compilerOptions["baseUrl"] = "./Resources";
  333. tsconfigFile.writeString(JSON.stringify(tsconfig, null, 4));
  334. tsconfigFile.close();
  335. // Build out the vscode tasks.json
  336. const tasks = {
  337. "command": "tsc",
  338. "isShellCommand": true,
  339. "args": ["-p", "."],
  340. "showOutput": "always",
  341. "problemMatcher": "$tsc"
  342. };
  343. const tasksDir = Atomic.addTrailingSlash(projectDir + ".vscode");
  344. Atomic.fileSystem.createDir(tasksDir);
  345. const tasksFile = new Atomic.File(tasksDir + "tasks.json", Atomic.FILE_WRITE);
  346. tasksFile.writeString(JSON.stringify(tasks, null, 4));
  347. tasksFile.close();
  348. }
  349. /**
  350. * Perform a full compile of the TypeScript
  351. */
  352. doFullCompile() {
  353. const editor = this.serviceRegistry.uiServices.getCurrentResourceEditor();
  354. if (editor && editor.typeName == "JSResourceEditor" && this.isValidFiletype(editor.fullPath)) {
  355. const jsEditor = <Editor.JSResourceEditor>editor;
  356. jsEditor.webView.webClient.executeJavaScript(`TypeScript_DoFullCompile('${JSON.stringify(this.buildTsConfig())}');`);
  357. } else {
  358. this.serviceRegistry.uiServices.showModalError("TypeScript Compilation", "Please open a TypeScript file in the editor before attempting to do a full compile.");
  359. }
  360. // Ideally, we would want to either launch up a background web view, or shell out to node or something and not
  361. // need to have an editor open. Still researching this
  362. /*
  363. const url = `atomic://${ToolCore.toolEnvironment.toolDataDir}CodeEditor/Editor.html`;
  364. const webClient = new WebView.WebClient();
  365. this.webClient = webClient;
  366. //this.webClient.loadURL(url);
  367. const webTexture = new WebView.WebTexture2D();
  368. webClient.webRenderHandler = webTexture;
  369. // doesn't work because atomicquery doesn't seem to be exposed to WebView.WebClient instances
  370. webClient.subscribeToEvent(EditorEvents.WebMessage, (data) => {
  371. switch (data.message) {
  372. case "editorLoadComplete":
  373. webClient.unsubscribeFromEvent(EditorEvents.WebMessage);
  374. webClient.executeJavaScript(`TypeScript_DoFullCompile();`);
  375. break;
  376. }
  377. });
  378. webClient.createBrowser(url, 1, 1);
  379. */
  380. }
  381. /**
  382. * Display the results of the compilation step
  383. * @param {any[]} annotations
  384. */
  385. displayCompileResults(results: {
  386. annotations: any[],
  387. compilerOptions: any,
  388. duration: number
  389. }) {
  390. // get the name of the resources directory without preceding path
  391. let resourceDir = ToolCore.toolSystem.project.resourcePath.replace(Atomic.addTrailingSlash(ToolCore.toolSystem.project.projectPath), "");
  392. let messageArray = results.annotations.filter(result => {
  393. // If we are compiling the lib.d.ts or some other built-in library and it was successful, then
  394. // we really don't need to display that result since it's just noise. Only display it if it fails
  395. if (result.type == "success") {
  396. return result.file.indexOf(ToolCore.toolSystem.project.projectPath) == 0;
  397. }
  398. return true;
  399. }).map(result => {
  400. // Clean up the path for display
  401. let file = result.file.replace(ToolCore.toolSystem.project.projectPath, "");
  402. let message = `<color #888888>${file}: </color>`;
  403. if (result.type == "success") {
  404. message += `<color #00ff00>${result.text}</color>`;
  405. } else {
  406. message += `<color #e3e02b>${result.text} at line ${result.row} col ${result.column}</color>`;
  407. }
  408. return message;
  409. }).join("\n");
  410. if (messageArray.length == 0) {
  411. messageArray = "Success";
  412. }
  413. let message = [
  414. "Compiler Options: ",
  415. JSON.stringify(results.compilerOptions, null, 2),
  416. "",
  417. messageArray,
  418. "",
  419. `Compilation Completed in ${results.duration}ms`
  420. ].join("\n");
  421. this.serviceRegistry.uiServices.showModalError("TypeScript Compilation Results", message);
  422. }
  423. }