Preferences.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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. class Preferences {
  23. private static Ctor = (() => {
  24. new Preferences();
  25. })();
  26. private fileSystem: Atomic.FileSystem;
  27. private static instance: Preferences;
  28. private _prefs: PreferencesFormat;
  29. private _cachedProjectPreferences: Object = null;
  30. constructor() {
  31. this.fileSystem = Atomic.getFileSystem();
  32. Preferences.instance = this;
  33. }
  34. registerRecentProject(path: string): void {
  35. var index = this._prefs.recentProjects.indexOf(path);
  36. if (index >= 0) {
  37. this._prefs.recentProjects.splice(index, 1);
  38. }
  39. this._prefs.recentProjects.unshift(path);
  40. this.updateRecentProjects(true);
  41. }
  42. updateRecentProjects(write: boolean = false): void {
  43. for (var i = 0; i < this._prefs.recentProjects.length; i++) {
  44. var path = this._prefs.recentProjects[i];
  45. if (!this.fileSystem.exists(path)) {
  46. this._prefs.recentProjects.splice(i, 1);
  47. write = true;
  48. }
  49. }
  50. if (write)
  51. this.write();
  52. }
  53. deleteRecentProjects(): void {
  54. this._prefs.recentProjects.length = 0;
  55. this.write();
  56. }
  57. addColorHistory(path: string): void {
  58. var index = this._prefs.colorHistory.indexOf(path); // search array for entry
  59. if (index >= 0) { // if its in there,
  60. this._prefs.colorHistory.splice(index, 1); // REMOVE it.
  61. }
  62. this._prefs.colorHistory.unshift(path); // now add it to beginning of array
  63. this.updateColorHistory(true); // update and write out
  64. }
  65. updateColorHistory(write: boolean = false): void {
  66. var len = this._prefs.colorHistory.length; // we only need indexes 0-7 now
  67. var over = 8;
  68. if ( len >= over ) // have MOaR than we need
  69. this._prefs.colorHistory.splice( over, len - over ); // remove the excess
  70. if (write)
  71. this.write();
  72. }
  73. getPreferencesFullPath(): string {
  74. var filePath = this.fileSystem.getAppPreferencesDir("AtomicEditor", "Preferences");
  75. filePath += "prefs.json";
  76. return filePath;
  77. }
  78. read(): void {
  79. var filePath = this.getPreferencesFullPath();
  80. var jsonFile;
  81. //check if file doesn't exist, create default json
  82. if (!this.fileSystem.fileExists(filePath)) {
  83. this.useDefaultConfig();
  84. this.write();
  85. return;
  86. }
  87. //Read file
  88. jsonFile = new Atomic.File(filePath, Atomic.FileMode.FILE_READ);
  89. var prefs = null;
  90. try {
  91. if (jsonFile.isOpen())
  92. prefs = <PreferencesFormat>JSON.parse(jsonFile.readText());
  93. } catch (e) {
  94. prefs = null;
  95. }
  96. if (prefs) {
  97. const defaultPrefs = new PreferencesFormat();
  98. const shouldWrite = defaultPrefs.applyMissingDefaults(prefs);
  99. this._prefs = prefs;
  100. if (shouldWrite) {
  101. this.write();
  102. }
  103. } else {
  104. console.log("Editor preference file missing or invalid, regenerating default configuration");
  105. this.useDefaultConfig();
  106. this.write();
  107. }
  108. }
  109. write(): boolean {
  110. var filePath = this.getPreferencesFullPath();
  111. var jsonFile = new Atomic.File(filePath, Atomic.FileMode.FILE_WRITE);
  112. if (!jsonFile.isOpen()) return false;
  113. jsonFile.writeString(JSON.stringify(this._prefs, null, 2));
  114. }
  115. saveEditorWindowData(windowData: WindowData) {
  116. this._prefs.editorWindow = windowData;
  117. this.write();
  118. }
  119. savePlayerWindowData(windowData: WindowData) {
  120. this._prefs.playerWindow = windowData;
  121. this.write();
  122. }
  123. useDefaultConfig(): void {
  124. this._prefs = new PreferencesFormat();
  125. }
  126. get cachedProjectPreferences(): any {
  127. return this._cachedProjectPreferences;
  128. }
  129. get cachedApplicationPreferences(): PreferencesFormat {
  130. return this._prefs;
  131. }
  132. get editorWindow(): WindowData {
  133. return this._prefs.editorWindow;
  134. }
  135. get playerWindow(): WindowData {
  136. return this._prefs.playerWindow;
  137. }
  138. get recentProjects(): string[] {
  139. return this._prefs.recentProjects;
  140. }
  141. get colorHistory(): string[] {
  142. return this._prefs.colorHistory;
  143. }
  144. get uiData(): UserInterfaceData {
  145. return this._prefs.uiData;
  146. }
  147. get editorBuildData(): EditorBuildData {
  148. return this._prefs.editorBuildData;
  149. }
  150. get editorFeatures(): EditorFeatures {
  151. return this._prefs.editorFeatures;
  152. }
  153. static getInstance(): Preferences {
  154. return Preferences.instance;
  155. }
  156. /**
  157. * Load up the user preferences for the project
  158. */
  159. loadUserPrefs() {
  160. const prefsFileLoc = ToolCore.toolSystem.project.userPrefsFullPath;
  161. if (Atomic.fileSystem.fileExists(prefsFileLoc)) {
  162. let prefsFile = new Atomic.File(prefsFileLoc, Atomic.FileMode.FILE_READ);
  163. try {
  164. let prefs = JSON.parse(prefsFile.readText());
  165. this._cachedProjectPreferences = prefs;
  166. } finally {
  167. prefsFile.close();
  168. }
  169. }
  170. }
  171. /**
  172. * Return a preference value or the provided default from the user settings file located in the project
  173. * @param {string} settingsGroup name of the group these settings should fall under
  174. * @param {string} preferenceName name of the preference to retrieve
  175. * @param {number | boolean | string} defaultValue value to return if pref doesn't exist
  176. * @return {number|boolean|string}
  177. */
  178. getUserPreference(settingsGroup: string, preferenceName: string, defaultValue?: number): number;
  179. getUserPreference(settingsGroup: string, preferenceName: string, defaultValue?: string): string;
  180. getUserPreference(settingsGroup: string, preferenceName: string, defaultValue?: boolean): boolean;
  181. getUserPreference(settingsGroup: string, preferenceName: string, defaultValue?: any): any {
  182. // Cache the settings so we don't keep going out to the file
  183. if (this._cachedProjectPreferences == null) {
  184. this.loadUserPrefs();
  185. }
  186. if (this._cachedProjectPreferences && this._cachedProjectPreferences[settingsGroup]) {
  187. return this._cachedProjectPreferences[settingsGroup][preferenceName] || defaultValue;
  188. }
  189. // if all else fails
  190. return defaultValue;
  191. }
  192. /**
  193. * Sets a preference value in a preferences file that is provided
  194. * @param {string} preferencesFilePath path to the prefs file to update
  195. * @param {string} settingsGroup name of the group the preference lives under
  196. * @param {string} preferenceName name of the preference to set
  197. * @param {number | boolean | string} value value to set
  198. */
  199. setGenericPreference(preferencesFilePath: string, settingsGroup: string, preferenceName: string, value: number | boolean | string): Object {
  200. let prefs = {};
  201. if (Atomic.fileSystem.fileExists(preferencesFilePath)) {
  202. let prefsFile = new Atomic.File(preferencesFilePath, Atomic.FileMode.FILE_READ);
  203. try {
  204. prefs = JSON.parse(prefsFile.readText());
  205. } finally {
  206. prefsFile.close();
  207. }
  208. }
  209. prefs[settingsGroup] = prefs[settingsGroup] || {};
  210. prefs[settingsGroup][preferenceName] = value;
  211. let saveFile = new Atomic.File(preferencesFilePath, Atomic.FileMode.FILE_WRITE);
  212. try {
  213. saveFile.writeString(JSON.stringify(prefs, null, " "));
  214. } finally {
  215. saveFile.flush();
  216. saveFile.close();
  217. }
  218. // Cache the update
  219. return prefs;
  220. }
  221. /**
  222. * Sets a user preference value in the user settings file located in the project
  223. * @param {string} settingsGroup name of the group the preference lives under
  224. * @param {string} preferenceName name of the preference to set
  225. * @param {number | boolean | string} value value to set
  226. */
  227. setUserPreference(settingsGroup: string, preferenceName: string, value: number | boolean | string) {
  228. const prefsFileLoc = ToolCore.toolSystem.project.userPrefsFullPath;
  229. const prefs = this.setGenericPreference(prefsFileLoc, settingsGroup, preferenceName, value);
  230. // Cache the update
  231. this._cachedProjectPreferences = prefs;
  232. }
  233. /**
  234. * Sets an editor preference value in the global user settings file
  235. * @param {string} settingsGroup name of the group the preference lives under
  236. * @param {string} preferenceName name of the preference to set
  237. * @param {number | boolean | string} value value to set
  238. */
  239. setApplicationPreference(settingsGroup: string, preferenceName: string, value: number | boolean | string) {
  240. const prefsFileLoc = this.getPreferencesFullPath();
  241. const prefs = this.setGenericPreference(prefsFileLoc, settingsGroup, preferenceName, value);
  242. // Cache the update
  243. this._prefs = prefs as PreferencesFormat;
  244. }
  245. /**
  246. * Return a preference value or the provided default from the global user settings file located in the project
  247. * @param {string} settingsGroup name of the group these settings should fall under
  248. * @param {string} preferenceName name of the preference to retrieve
  249. * @param {number | boolean | string} defaultValue value to return if pref doesn't exist
  250. * @return {number|boolean|string}
  251. */
  252. getApplicationPreference(settingsGroup: string, preferenceName: string, defaultValue?: number): number;
  253. getApplicationPreference(settingsGroup: string, preferenceName: string, defaultValue?: string): string;
  254. getApplicationPreference(settingsGroup: string, preferenceName: string, defaultValue?: boolean): boolean;
  255. getApplicationPreference(settingsGroup: string, preferenceName: string, defaultValue?: any): any {
  256. // Cache the settings so we don't keep going out to the file
  257. if (this._prefs == null) {
  258. this.read();
  259. }
  260. if (this._prefs && this._prefs[settingsGroup]) {
  261. return this._prefs[settingsGroup][preferenceName] || defaultValue;
  262. }
  263. // if all else fails
  264. return defaultValue;
  265. }
  266. /**
  267. * Sets a group of user preference values in the user settings file located in the project. Elements in the
  268. * group will merge in with existing group preferences. Use this method if setting a bunch of settings
  269. * at once.
  270. * @param {string} settingsGroup name of the group the preference lives under
  271. * @param {string} groupPreferenceValues an object literal containing all of the preferences for the group.
  272. */
  273. setUserPreferenceGroup(settingsGroup: string, groupPreferenceValues: Object) {
  274. const prefsFileLoc = ToolCore.toolSystem.project.userPrefsFullPath;
  275. let prefs = {};
  276. if (Atomic.fileSystem.fileExists(prefsFileLoc)) {
  277. let prefsFile = new Atomic.File(prefsFileLoc, Atomic.FileMode.FILE_READ);
  278. try {
  279. prefs = JSON.parse(prefsFile.readText());
  280. } finally {
  281. prefsFile.close();
  282. }
  283. }
  284. prefs[settingsGroup] = prefs[settingsGroup] || {};
  285. for (let preferenceName in groupPreferenceValues) {
  286. prefs[settingsGroup][preferenceName] = groupPreferenceValues[preferenceName];
  287. }
  288. let saveFile = new Atomic.File(prefsFileLoc, Atomic.FileMode.FILE_WRITE);
  289. try {
  290. saveFile.writeString(JSON.stringify(prefs, null, " "));
  291. } finally {
  292. saveFile.flush();
  293. saveFile.close();
  294. }
  295. // Cache the update
  296. this._cachedProjectPreferences = prefs;
  297. }
  298. }
  299. interface WindowData {
  300. x: number;
  301. y: number;
  302. width: number;
  303. height: number;
  304. monitor: number;
  305. maximized: boolean;
  306. }
  307. interface MonacoEditorSettings {
  308. theme: string;
  309. fontSize: number;
  310. fontFamily: string;
  311. showInvisibles: boolean;
  312. useSoftTabs: boolean;
  313. tabSize: number;
  314. }
  315. interface UserInterfaceData {
  316. skinPath: string;
  317. defaultSkinPath: string;
  318. fontFile: string;
  319. fontName: string;
  320. fontSize: number;
  321. }
  322. interface EditorBuildData {
  323. lastEditorBuildSHA: string;
  324. }
  325. interface EditorFeatures {
  326. closePlayerLog: boolean;
  327. defaultPath: string;
  328. defaultLanguage: string;
  329. }
  330. class PreferencesFormat {
  331. constructor() {
  332. this.setDefault();
  333. }
  334. setDefault() {
  335. this.recentProjects = [];
  336. this.colorHistory = [ "#000000", "#ffffff", "#00ff00", "#0000ff", "#ff0000", "#ff00ff", "#ffff00", "#668866" ];
  337. this.editorWindow = {
  338. x: 0,
  339. y: 0,
  340. width: 0,
  341. height: 0,
  342. monitor: 0,
  343. maximized: true
  344. };
  345. this.playerWindow = {
  346. x: 0,
  347. y: 0,
  348. width: 0,
  349. height: 0,
  350. monitor: 0,
  351. maximized: false
  352. };
  353. this.codeEditor = {
  354. theme: "vs-dark",
  355. fontSize: 12,
  356. fontFamily: "",
  357. showInvisibles: false,
  358. useSoftTabs: true,
  359. tabSize: 4
  360. };
  361. this.uiData = {
  362. skinPath: "AtomicEditor/editor/skin/",
  363. defaultSkinPath: "AtomicEditor/resources/default_skin/",
  364. fontFile: "AtomicEditor/resources/vera.ttf",
  365. fontName: "Vera",
  366. fontSize: 12
  367. };
  368. this.editorBuildData = {
  369. lastEditorBuildSHA: "Unversioned Build"
  370. };
  371. var fileSystem = Atomic.getFileSystem();
  372. var userDocuments = fileSystem.userDocumentsDir;
  373. if (Atomic.platform == "MacOSX") userDocuments += "Documents/";
  374. userDocuments += "AtomicProjects";
  375. this.editorFeatures = {
  376. closePlayerLog: true,
  377. defaultPath: userDocuments,
  378. defaultLanguage: "JavaScript"
  379. };
  380. }
  381. /**
  382. * Run through a provided prefs block and verify that all the sections are present. If any
  383. * are missing, add the defaults in
  384. * @param {PreferencesFormat} prefs
  385. * @return boolean returns true if any missing defaults were updated
  386. */
  387. applyMissingDefaults(prefs: PreferencesFormat) {
  388. let updatedMissingDefaults = false;
  389. if (!prefs.recentProjects) {
  390. prefs.recentProjects = this.recentProjects;
  391. updatedMissingDefaults = true;
  392. }
  393. if (!prefs.colorHistory) {
  394. prefs.colorHistory = this.colorHistory;
  395. updatedMissingDefaults = true;
  396. }
  397. if (!prefs.editorWindow) {
  398. prefs.editorWindow = this.editorWindow;
  399. updatedMissingDefaults = true;
  400. }
  401. if (!prefs.playerWindow) {
  402. prefs.playerWindow = this.playerWindow;
  403. updatedMissingDefaults = true;
  404. }
  405. if (!prefs.codeEditor) {
  406. prefs.codeEditor = this.codeEditor;
  407. updatedMissingDefaults = true;
  408. }
  409. if (!prefs.uiData) {
  410. prefs.uiData = this.uiData;
  411. updatedMissingDefaults = true;
  412. }
  413. if (!prefs.editorBuildData) {
  414. prefs.editorBuildData = this.editorBuildData;
  415. updatedMissingDefaults = true;
  416. }
  417. if (!prefs.editorFeatures) {
  418. prefs.editorFeatures = this.editorFeatures;
  419. updatedMissingDefaults = true;
  420. }
  421. if (!prefs.editorFeatures.defaultPath) {
  422. prefs.editorFeatures.defaultPath = this.editorFeatures.defaultPath;
  423. updatedMissingDefaults = true;
  424. }
  425. return updatedMissingDefaults;
  426. }
  427. recentProjects: string[];
  428. editorWindow: WindowData;
  429. playerWindow: WindowData;
  430. codeEditor: MonacoEditorSettings;
  431. uiData: UserInterfaceData;
  432. editorBuildData: EditorBuildData;
  433. colorHistory: string[];
  434. editorFeatures: EditorFeatures;
  435. }
  436. export = Preferences;