TypscriptLanguageExtension.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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. * Build an in-memory config file to be sent down to the web view client. This will scan the resources directory
  51. * and generate a file list
  52. */
  53. private buildTsConfig(): any {
  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. projectFiles.push(Atomic.addTrailingSlash(Atomic.addTrailingSlash(ToolCore.toolEnvironment.toolDataDir) + "TypeScriptSupport") + "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. return tsConfig;
  88. } else {
  89. return {
  90. files: []
  91. };
  92. }
  93. }
  94. /**
  95. * Inject this language service into the registry
  96. * @return {[type]} True if successful
  97. */
  98. initialize(serviceLocator: Editor.HostExtensions.HostServiceLocator) {
  99. // We care about both resource events as well as project events
  100. serviceLocator.resourceServices.register(this);
  101. serviceLocator.projectServices.register(this);
  102. serviceLocator.uiServices.register(this);
  103. this.serviceRegistry = serviceLocator;
  104. }
  105. /**
  106. * Handle the delete. This should delete the corresponding javascript file
  107. * @param {Editor.EditorEvents.DeleteResourceEvent} ev
  108. */
  109. delete(ev: Editor.EditorEvents.DeleteResourceEvent) {
  110. if (this.isValidFiletype(ev.path)) {
  111. // console.log(`${this.name}: received a delete resource event`);
  112. // Delete the corresponding js file
  113. let jsFile = ev.path.replace(/\.ts$/, ".js");
  114. let jsFileAsset = ToolCore.assetDatabase.getAssetByPath(jsFile);
  115. if (jsFileAsset) {
  116. console.log(`${this.name}: deleting corresponding .js file`);
  117. ToolCore.assetDatabase.deleteAsset(jsFileAsset);
  118. let eventData: EditorEvents.DeleteResourceEvent = {
  119. path: jsFile
  120. };
  121. this.setTsConfigOnWebView(this.buildTsConfig());
  122. this.serviceRegistry.sendEvent(EditorEvents.DeleteResourceNotification, eventData);
  123. }
  124. }
  125. }
  126. /**
  127. * Handle the rename. Should rename the corresponding .js file
  128. * @param {Editor.EditorEvents.RenameResourceEvent} ev
  129. */
  130. rename(ev: Editor.EditorEvents.RenameResourceEvent) {
  131. if (this.isValidFiletype(ev.path)) {
  132. // console.log(`${this.name}: received a rename resource event`);
  133. // Rename the corresponding js file
  134. let jsFile = ev.path.replace(/\.ts$/, ".js");
  135. let jsFileNew = ev.newPath.replace(/\.ts$/, ".js"); // rename doesn't want extension
  136. let jsFileAsset = ToolCore.assetDatabase.getAssetByPath(jsFile);
  137. if (jsFileAsset) {
  138. console.log(`${this.name}: renaming corresponding .js file`);
  139. jsFileAsset.rename(ev.newName);
  140. let eventData: EditorEvents.RenameResourceEvent = {
  141. path: jsFile,
  142. newPath: jsFileNew,
  143. newName: ev.newName,
  144. asset: jsFileAsset
  145. };
  146. this.setTsConfigOnWebView(this.buildTsConfig());
  147. this.serviceRegistry.sendEvent(EditorEvents.RenameResourceNotification, eventData);
  148. }
  149. }
  150. }
  151. /**
  152. * Handles the save event and detects if a typescript file has been added to a non-typescript project
  153. * @param {Editor.EditorEvents.SaveResourceEvent} ev
  154. * @return {[type]}
  155. */
  156. save(ev: Editor.EditorEvents.SaveResourceEvent) {
  157. // let's check to see if we have created a typescript file
  158. if (!this.isTypescriptProject) {
  159. if (Atomic.getExtension(ev.path) == ".ts") {
  160. this.isTypescriptProject = true;
  161. this.setTsConfigOnWebView(this.buildTsConfig());
  162. }
  163. }
  164. }
  165. /*** ProjectService implementation ****/
  166. /**
  167. * Called when the project is being loaded to allow the typscript language service to reset and
  168. * possibly compile
  169. */
  170. projectLoaded(ev: Editor.EditorEvents.LoadProjectEvent) {
  171. // got a load, we need to reset the language service
  172. console.log(`${this.name}: received a project loaded event for project at ${ev.path}`);
  173. this.setTsConfigOnWebView(this.buildTsConfig());
  174. this.rebuildMenu();
  175. }
  176. /**
  177. * Rebuilds the plugin menu. This is needed to toggle the CompileOnSave true or false
  178. */
  179. rebuildMenu() {
  180. if (this.isTypescriptProject) {
  181. this.serviceRegistry.uiServices.removePluginMenuItemSource("TypeScript");
  182. const isCompileOnSave = this.serviceRegistry.projectServices.getUserPreference(this.name, "CompileOnSave", false);
  183. let subMenu = {};
  184. if (isCompileOnSave) {
  185. subMenu["Compile on Save: On"] = [`${this.name}.compileonsave`];
  186. } else {
  187. subMenu["Compile on Save: Off"] = [`${this.name}.compileonsave`];
  188. }
  189. subMenu["Compile Project"] = [`${this.name}.compileproject`];
  190. this.serviceRegistry.uiServices.createPluginMenuItemSource("TypeScript", subMenu);
  191. }
  192. }
  193. /*** UIService implementation ***/
  194. /**
  195. * Called when a plugin menu item is clicked
  196. * @param {string} refId
  197. * @return {boolean}
  198. */
  199. menuItemClicked(refId: string): boolean {
  200. let [extension, action] = refId.split(".");
  201. if (extension == this.name) {
  202. switch (action) {
  203. case "compileonsave":
  204. // Toggle
  205. const isCompileOnSave = this.serviceRegistry.projectServices.getUserPreference(this.name, "CompileOnSave", false);
  206. this.serviceRegistry.projectServices.setUserPreference(this.name, "CompileOnSave", !isCompileOnSave);
  207. this.rebuildMenu();
  208. return true;
  209. case "compileproject":
  210. this.doFullCompile();
  211. return true;
  212. }
  213. }
  214. }
  215. /**
  216. * Handle messages that are submitted via Atomic.Query from within a web view editor.
  217. * @param message The message type that was submitted to be used to determine what the data contains if present
  218. * @param data any additional data that needs to be submitted with the message
  219. */
  220. handleWebMessage(messageType: string, data: any) {
  221. switch (messageType) {
  222. case "TypeScript.DisplayCompileResults":
  223. this.displayCompileResults(data.annotations);
  224. break;
  225. }
  226. }
  227. setTsConfigOnWebView(tsConfig: any) {
  228. WebView.WebBrowserHost.setGlobalStringProperty("TypeScriptLanguageExtension", "tsConfig", JSON.stringify(tsConfig));
  229. }
  230. /**
  231. * Perform a full compile of the TypeScript
  232. */
  233. doFullCompile() {
  234. const editor = this.serviceRegistry.uiServices.getCurrentResourceEditor();
  235. if (editor && editor.typeName == "JSResourceEditor") {
  236. const jsEditor = <Editor.JSResourceEditor>editor;
  237. jsEditor.webView.webClient.executeJavaScript(`TypeScript_DoFullCompile();`);
  238. } else {
  239. this.serviceRegistry.uiServices.showModalError("TypeScript Compilation", "Please open a TypeScript file in the editor before attempting to do a full compile.");
  240. }
  241. // Ideally, we would want to either launch up a background web view, or shell out to node or something and not
  242. // need to have an editor open. Still researching this
  243. /*
  244. const url = `atomic://${ToolCore.toolEnvironment.toolDataDir}CodeEditor/Editor.html`;
  245. const webClient = new WebView.WebClient();
  246. this.webClient = webClient;
  247. //this.webClient.loadURL(url);
  248. const webTexture = new WebView.WebTexture2D();
  249. webClient.webRenderHandler = webTexture;
  250. // doesn't work because atomicquery doesn't seem to be exposed to WebView.WebClient instances
  251. webClient.subscribeToEvent(EditorEvents.WebMessage, (data) => {
  252. switch (data.message) {
  253. case "editorLoadComplete":
  254. webClient.unsubscribeFromEvent(EditorEvents.WebMessage);
  255. webClient.executeJavaScript(`TypeScript_DoFullCompile();`);
  256. break;
  257. }
  258. });
  259. webClient.createBrowser(url, 1, 1);
  260. */
  261. }
  262. /**
  263. * Display the results of the compilation step
  264. * @param {any[]} annotations
  265. */
  266. displayCompileResults(annotations: any[]) {
  267. // get the name of the resources directory without preceding path
  268. let resourceDir = ToolCore.toolSystem.project.resourcePath.replace(Atomic.addTrailingSlash(ToolCore.toolSystem.project.projectPath), "");
  269. console.log(resourceDir);
  270. let messageArray = annotations.filter(result => {
  271. // If we are compiling the lib.d.ts or some other built-in library and it was successful, then
  272. // we really don't need to display that result since it's just noise. Only display it if it fails
  273. if (result.type == "success") {
  274. return result.file.indexOf(resourceDir) == 0;
  275. }
  276. return true;
  277. }).map(result => {
  278. let message = `<color #888888>${result.file}: </color>`;
  279. if (result.type == "success") {
  280. message += `<color #00ff00>${result.text}</color>`;
  281. } else {
  282. message += `<color #e3e02b>${result.text} at line ${result.row} col ${result.column}</color>`;
  283. }
  284. return message;
  285. });
  286. if (messageArray.length == 0) {
  287. messageArray.push("Success");
  288. }
  289. this.serviceRegistry.uiServices.showModalError("TypeScript Compilation Results", messageArray.join("\n"));
  290. }
  291. }