TypscriptLanguageExtension.ts 15 KB

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