TypscriptLanguageExtension.ts 17 KB

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