TypscriptLanguageExtension.ts 19 KB

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