TypscriptLanguageExtension.ts 14 KB

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