TypscriptLanguageExtension.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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. * Resource extension that supports the web view typescript extension
  25. */
  26. export default class TypescriptLanguageExtension implements Editor.HostExtensions.ResourceServicesEventListener, Editor.HostExtensions.ProjectServicesEventListener {
  27. name: string = "HostTypeScriptLanguageExtension";
  28. description: string = "This service supports the typscript webview extension.";
  29. /**
  30. * Indicates if this project contains typescript files.
  31. * @type {Boolean}
  32. */
  33. private isTypescriptProject = false;
  34. private serviceRegistry: Editor.HostExtensions.HostServiceLocator = null;
  35. /**
  36. * Determines if the file name/path provided is something we care about
  37. * @param {string} path
  38. * @return {boolean}
  39. */
  40. private isValidFiletype(path: string): boolean {
  41. if (this.isTypescriptProject) {
  42. const ext = Atomic.getExtension(path);
  43. if (ext == ".ts") {
  44. return true;
  45. }
  46. }
  47. return false;
  48. }
  49. /**
  50. * Seed the language service with all of the relevant files in the project. This updates the tsconifg.atomic file in
  51. * the root of the resources directory.
  52. */
  53. private loadProjectFiles() {
  54. let projectFiles: Array<string> = [];
  55. //scan all the files in the project for any typescript files so we can determine if this is a typescript project
  56. Atomic.fileSystem.scanDir(ToolCore.toolSystem.project.resourcePath, "*.ts", Atomic.SCAN_FILES, true).forEach(filename => {
  57. projectFiles.push(Atomic.addTrailingSlash(ToolCore.toolSystem.project.resourcePath) + filename);
  58. this.isTypescriptProject = true;
  59. });
  60. // only build out a tsconfig.atomic if we actually have typescript files in the project
  61. if (this.isTypescriptProject) {
  62. // First we need to load in a copy of the lib.core.d.ts that is necessary for the hosted typescript compiler
  63. projectFiles.push(Atomic.addTrailingSlash(Atomic.addTrailingSlash(ToolCore.toolEnvironment.toolDataDir) + "TypeScriptSupport") + "lib.core.d.ts");
  64. // 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
  65. let found = false;
  66. projectFiles.forEach((file) => {
  67. if (file.indexOf("Atomic.d.ts") != -1) {
  68. found = true;
  69. }
  70. });
  71. if (!found) {
  72. // Load up the Atomic.d.ts from the tool core
  73. console.log("Need to load up hosted Atomic.d.ts!");
  74. }
  75. let files = projectFiles.map((f: string) => {
  76. if (f.indexOf(ToolCore.toolSystem.project.resourcePath) != -1) {
  77. // if we are in the resources directory, just pass back the path from resources down
  78. return f.replace(Atomic.addTrailingSlash(ToolCore.toolSystem.project.projectPath), "");
  79. } else {
  80. // otherwise return the full path
  81. return f;
  82. }
  83. });
  84. let tsConfig = {
  85. files: files
  86. };
  87. let filename = Atomic.addTrailingSlash(ToolCore.toolSystem.project.resourcePath) + "tsconfig.atomic";
  88. let script = new Atomic.File(filename, Atomic.FILE_WRITE);
  89. try {
  90. script.writeString(JSON.stringify(tsConfig));
  91. script.flush();
  92. } finally {
  93. script.close();
  94. }
  95. }
  96. }
  97. /**
  98. * Inject this language service into the registry
  99. * @return {[type]} True if successful
  100. */
  101. initialize(serviceLocator: Editor.HostExtensions.HostServiceLocator) {
  102. // We care about both resource events as well as project events
  103. serviceLocator.resourceServices.register(this);
  104. serviceLocator.projectServices.register(this);
  105. serviceLocator.uiServices.register(this);
  106. this.serviceRegistry = serviceLocator;
  107. }
  108. /**
  109. * Handle the delete. This should delete the corresponding javascript file
  110. * @param {Editor.EditorEvents.DeleteResourceEvent} ev
  111. */
  112. delete(ev: Editor.EditorEvents.DeleteResourceEvent) {
  113. if (this.isValidFiletype(ev.path)) {
  114. console.log(`${this.name}: received a delete resource event`);
  115. // Delete the corresponding js file
  116. let jsFile = ev.path.replace(/\.ts$/, ".js");
  117. let jsFileAsset = ToolCore.assetDatabase.getAssetByPath(jsFile);
  118. if (jsFileAsset) {
  119. console.log(`${this.name}: deleting corresponding .js file`);
  120. ToolCore.assetDatabase.deleteAsset(jsFileAsset);
  121. let eventData: EditorEvents.DeleteResourceEvent = {
  122. path: jsFile
  123. };
  124. this.serviceRegistry.sendEvent(EditorEvents.DeleteResourceNotification, eventData);
  125. // rebuild the tsconfig.atomic
  126. this.loadProjectFiles();
  127. }
  128. }
  129. }
  130. /**
  131. * Handle the rename. Should rename the corresponding .js file
  132. * @param {Editor.EditorEvents.RenameResourceEvent} ev
  133. */
  134. rename(ev: Editor.EditorEvents.RenameResourceEvent) {
  135. if (this.isValidFiletype(ev.path)) {
  136. console.log(`${this.name}: received a rename resource event`);
  137. // Rename the corresponding js file
  138. let jsFile = ev.path.replace(/\.ts$/, ".js");
  139. let jsFileNew = ev.newPath.replace(/\.ts$/, ".js"); // rename doesn't want extension
  140. let jsFileAsset = ToolCore.assetDatabase.getAssetByPath(jsFile);
  141. if (jsFileAsset) {
  142. console.log(`${this.name}: renaming corresponding .js file`);
  143. jsFileAsset.rename(ev.newName);
  144. let eventData: EditorEvents.RenameResourceEvent = {
  145. path: jsFile,
  146. newPath: jsFileNew,
  147. newName: ev.newName,
  148. asset: jsFileAsset
  149. };
  150. this.serviceRegistry.sendEvent(EditorEvents.RenameResourceNotification, eventData);
  151. // rebuild the tsconfig.atomic
  152. this.loadProjectFiles();
  153. }
  154. }
  155. }
  156. /**
  157. * Handles the save event and detects if a typescript file has been added to a non-typescript project
  158. * @param {Editor.EditorEvents.SaveResourceEvent} ev
  159. * @return {[type]}
  160. */
  161. save(ev: Editor.EditorEvents.SaveResourceEvent) {
  162. // let's check to see if we have created a typescript file
  163. if (!this.isTypescriptProject) {
  164. if (Atomic.getExtension(ev.path) == ".ts") {
  165. this.isTypescriptProject = true;
  166. this.loadProjectFiles();
  167. }
  168. }
  169. }
  170. /*** ProjectService implementation ****/
  171. /**
  172. * Called when the project is being loaded to allow the typscript language service to reset and
  173. * possibly compile
  174. */
  175. projectLoaded(ev: Editor.EditorEvents.LoadProjectEvent) {
  176. // got a load, we need to reset the language service
  177. console.log(`${this.name}: received a project loaded event for project at ${ev.path}`);
  178. this.loadProjectFiles();
  179. this.rebuildMenu();
  180. }
  181. /**
  182. * Rebuilds the plugin menu. This is needed to toggle the CompileOnSave true or false
  183. */
  184. rebuildMenu() {
  185. if (this.isTypescriptProject) {
  186. this.serviceRegistry.uiServices.removePluginMenuItemSource("TypeScript");
  187. const isCompileOnSave = this.serviceRegistry.projectServices.getUserPreference(this.name, "CompileOnSave", false);
  188. let subMenu = {};
  189. if (isCompileOnSave) {
  190. subMenu["Compile on Save: On"] = [`${this.name}.compileonsave`];
  191. } else {
  192. subMenu["Compile on Save: Off"] = [`${this.name}.compileonsave`];
  193. }
  194. subMenu["Compile Project"] = [`${this.name}.compileproject`];
  195. this.serviceRegistry.uiServices.createPluginMenuItemSource("TypeScript", subMenu);
  196. }
  197. }
  198. /*** UIService implementation ***/
  199. /**
  200. * Called when a plugin menu item is clicked
  201. * @param {string} refId
  202. * @return {boolean}
  203. */
  204. menuItemClicked(refId: string): boolean {
  205. let [extension, action] = refId.split(".");
  206. if (extension == this.name) {
  207. switch (action) {
  208. case "compileonsave":
  209. // Toggle
  210. const isCompileOnSave = this.serviceRegistry.projectServices.getUserPreference(this.name, "CompileOnSave", false);
  211. this.serviceRegistry.projectServices.setUserPreference(this.name, "CompileOnSave", !isCompileOnSave);
  212. this.rebuildMenu();
  213. return true;
  214. case "compileproject":
  215. const editor = this.serviceRegistry.uiServices.getCurrentResourceEditor();
  216. if (editor && editor.typeName == "JSResourceEditor") {
  217. const jsEditor = <Editor.JSResourceEditor>editor;
  218. jsEditor.webView.webClient.executeJavaScript(`TypeScript_DoFullCompile();`);
  219. }
  220. return true;
  221. }
  222. }
  223. }
  224. /**
  225. * Handle messages that are submitted via Atomic.Query from within a web view editor.
  226. * @param message The message type that was submitted to be used to determine what the data contains if present
  227. * @param data any additional data that needs to be submitted with the message
  228. */
  229. handleWebMessage(messageType: string, data: any) {
  230. switch (messageType) {
  231. case "TypeScript.DisplayCompileResults":
  232. this.displayCompileResults(data.annotations);
  233. break;
  234. }
  235. }
  236. /**
  237. * Display the results of the compilation step
  238. * @param {any[]} annotations
  239. */
  240. displayCompileResults(annotations: any[]) {
  241. let messageArray = annotations.map((result) => {
  242. return `${result.text} at line ${result.row} col ${result.column} in ${result.file}`;
  243. });
  244. if (messageArray.length == 0) {
  245. messageArray.push("Success");
  246. }
  247. this.serviceRegistry.uiServices.showModalError("TypeScript Compilation Results", messageArray.join("\n"));
  248. }
  249. }