TypscriptLanguageExtension.ts 19 KB

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