-
-
Notifications
You must be signed in to change notification settings - Fork 193
Expand file tree
/
Copy pathThemeManager.js
More file actions
435 lines (368 loc) · 15 KB
/
ThemeManager.js
File metadata and controls
435 lines (368 loc) · 15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
/**
* Brackets Themes Copyright (c) 2014 Miguel Castillo.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*jslint regexp: true */
/*global less */
define(function (require, exports, module) {
var _ = require("thirdparty/lodash"),
EventDispatcher = require("utils/EventDispatcher"),
FileSystem = require("filesystem/FileSystem"),
FileUtils = require("file/FileUtils"),
EditorManager = require("editor/EditorManager"),
ExtensionUtils = require("utils/ExtensionUtils"),
ThemeSettings = require("view/ThemeSettings"),
ThemeView = require("view/ThemeView"),
PreferencesManager = require("preferences/PreferencesManager"),
prefs = PreferencesManager.getExtensionPrefs("themes");
var loadedThemes = {},
currentTheme = null,
styleNode = $(ExtensionUtils.addEmbeddedStyleSheet("")),
defaultTheme = "thor-light-theme",
commentRegex = /\/\*([\s\S]*?)\*\//mg,
scrollbarsRegex = /((?:[^}|,]*)::-webkit-scrollbar(?:[^{]*)[{](?:[^}]*?)[}])/mgi,
stylesPath = FileUtils.getNativeBracketsDirectoryPath() + "/styles/";
/**
* @private
* Takes all dashes and converts them to white spaces. Then takes all first letters
* and capitalizes them.
*
* @param {string} name is what needs to be procseed to generate a display name
* @return {string} theme name properly formatted for display
*/
function toDisplayName(name) {
var extIndex = name.lastIndexOf('.');
name = name.substring(0, extIndex !== -1 ? extIndex : undefined).replace(/-/g, ' ');
return name.split(" ").map(function (part) {
return part[0].toUpperCase() + part.substring(1);
}).join(" ");
}
/**
* @constructor
* Theme contains all the essential bit to load a theme from disk, display a theme in the settings
* dialog, and to properly add a theme into CodeMirror along with the rest of brackets.
*
* @param {File} file for the theme
* @param {{name: string, title: string}} options to configure different
* properties in the theme
*/
function Theme(file, options) {
options = options || {};
var fileName = file.name;
// If no options.name is provided, then we derive the name of the theme from whichever we find
// first, the options.title or the filename.
if (!options.name) {
if (options.title) {
options.name = options.title;
} else {
// Remove the file extension when the filename is used as the theme name. This is to
// follow CodeMirror conventions where themes are just a CSS file and the filename
// (without the extension) is used to build CSS rules. Also handle removing .min
// in case the ".min" is part of the file name.
options.name = FileUtils.getFilenameWithoutExtension(fileName).replace(/\.min$/, "");
}
// We do a bit of string treatment here to make sure we generate theme names that can be
// used as a CSS class name by CodeMirror.
options.name = options.name.toLocaleLowerCase().replace(/[\W]/g, '-');
}
this.file = file;
this.name = options.name;
this.displayName = options.title || toDisplayName(fileName);
this.dark = options.theme !== undefined && options.theme.dark === true;
this.addModeClass = options.theme !== undefined && options.theme.addModeClass === true;
}
/**
* @private
* Extracts the scrollbar text from the css/less content so that it can be treated
* as a separate styling component that can be anabled/disabled independently from
* the theme.
*
* @param {string} content is the css/less input string to be processed
* @return {{content: string, scrollbar: Array.<string>}} content is the new css/less content
* with the scrollbar rules extracted out and put in scrollbar
*/
function extractScrollbars(content) {
var scrollbar = [];
// Go through and extract out scrollbar customizations so that we can
// enable/disable via settings.
content = content
.replace(scrollbarsRegex, function (match) {
scrollbar.push(match);
return "";
});
return {
content: content,
scrollbar: scrollbar
};
}
/**
* @private
* Function will process a string and figure out if it looks like window path with a
* a drive. If that's the case, then we lower case everything.
* --- NOTE: There is a bug in less that only checks for lowercase in order to handle
* the rootPath configuration... Hopefully a PR will be coming their way soon.
*
* @param {string} path is a string to search for drive letters that need to be converted
* to lower case.
*
* @return {string} Windows Drive letter in lowercase.
*/
function fixPath(path) {
return path.replace(/^([A-Z]+:)?\//, function (match) {
return match.toLocaleLowerCase();
});
}
/**
* @private
* Takes the content of a file and feeds it through the less processor in order
* to provide support for less files.
*
* @param {string} content is the css/less string to be processed
* @param {Theme} theme is the object the css/less corresponds to
* @return {$.Promise} promise with the processed css/less as the resolved value
*/
function lessifyTheme(content, theme) {
var deferred = new $.Deferred();
less.render("#editor-holder {" + content + "\n}", {
rootpath: fixPath(stylesPath),
filename: fixPath(theme.file._path)
}, function (err, tree) {
if (err) {
deferred.reject(err);
} else {
deferred.resolve(tree.css);
}
});
return deferred.promise();
}
/**
* @private
* Will search all loaded themes for one the matches the file passed in
*
* @param {File} file is the search criteria
* @return {Theme} theme that matches the file
*/
function getThemeByFile(file) {
var path = file._path;
return _.find(loadedThemes, function (item) {
return item.file._path === path;
});
}
/**
* Get current theme object that is loaded in the editor.
*
* @return {Theme} the current theme instance
*/
function getCurrentTheme() {
if (!currentTheme) {
currentTheme = loadedThemes[prefs.get("theme")] || loadedThemes[defaultTheme];
}
return currentTheme;
}
/**
* Gets all available themes
* @return {Array.<Theme>} collection of all available themes
*/
function getAllThemes() {
return _.map(loadedThemes, function (theme) {
return theme;
});
}
/**
* @private
* Process and load the current theme into the editor
*
* @return {$.Promise} promise object resolved with the theme object and all
* corresponding new css/less and scrollbar information
*/
function loadCurrentTheme() {
var theme = getCurrentTheme();
var pending = theme && FileUtils.readAsText(theme.file)
.then(function (lessContent) {
return lessifyTheme(lessContent.replace(commentRegex, ""), theme);
})
.then(function (content) {
var result = extractScrollbars(content);
theme.scrollbar = result.scrollbar;
return result.content;
})
.then(function (cssContent) {
$("body").toggleClass("dark", theme.dark);
styleNode.text(cssContent);
return theme;
});
return $.when(pending);
}
/**
* Refresh current theme in the editor
*
* @param {boolean} force Forces a reload of the current theme. It reloads the theme file.
*/
function refresh(force) {
if (force) {
currentTheme = null;
}
$.when(force && loadCurrentTheme()).done(function () {
var editor = EditorManager.getActiveEditor();
if (!editor || !editor._codeMirror) {
return;
}
var cm = editor._codeMirror;
ThemeView.updateThemes(cm);
// currentTheme can be undefined, so watch out
cm.setOption("addModeClass", !!(currentTheme && currentTheme.addModeClass));
});
}
/**
*
* @param file FileSystem.getFileForPath object
* @param options
* @private
*/
function _loadThemeFromFile(file, options) {
var currentThemeName = prefs.get("theme");
var theme = new Theme(file, options);
loadedThemes[theme.name] = theme;
ThemeSettings._setThemes(loadedThemes);
// For themes that are loaded after ThemeManager has been loaded,
// we should check if it's the current theme. If it is, then we just
// load it.
if (currentThemeName === theme.name) {
refresh(true);
}
}
/**
* Loads a theme from a url.
*
* @param {string} url is the full hhtp/https url of the theme file
* @param {Object} options is an optional parameter to specify metadata
* for the theme.
* @return {$.Promise} promise object resolved with the theme to be loaded from fileName
*/
function _loadFileFromURL(url, options) {
var deferred = new $.Deferred();
var themeName = options.name || options.theme.title;
var fileName = options.theme.file;
var themePath = path.normalize(brackets.app.getApplicationSupportDirectory() + "/extensions/user/" +
themeName + '_' + fileName);
var file = FileSystem.getFileForPath(themePath);
file.exists(function (err, exists) {
var theme;
if (exists) {
_loadThemeFromFile(file, options);
deferred.resolve(theme);
return;
}
$.get(url).done(function (themeContent) {
// Write theme to file
FileUtils.writeText(file, themeContent).then(function () {
_loadThemeFromFile(file, options);
deferred.resolve(theme);
}, deferred.reject);
}).fail(function (err) {
deferred.reject(err);
});
});
return deferred.promise();
}
/**
* Loads a theme from a file.
*
* @param {string} fileName is the full path to the file to be opened
* @param {Object} options is an optional parameter to specify metadata
* for the theme.
* @return {$.Promise} promise object resolved with the theme to be loaded from fileName
*/
function loadFile(fileName, options) {
if(fileName.startsWith("http://") || fileName.startsWith("https://")) {
return _loadFileFromURL(fileName, options);
}
var deferred = new $.Deferred(),
file = FileSystem.getFileForPath(fileName),
currentThemeName = prefs.get("theme");
file.exists(function (err, exists) {
var theme;
if (exists) {
theme = new Theme(file, options);
loadedThemes[theme.name] = theme;
ThemeSettings._setThemes(loadedThemes);
// For themes that are loaded after ThemeManager has been loaded,
// we should check if it's the current theme. If it is, then we just
// load it.
if (currentThemeName === theme.name) {
refresh(true);
}
deferred.resolve(theme);
} else if (err || !exists) {
deferred.reject(err);
}
});
return deferred.promise();
}
/**
* Loads a theme from an extension package.
*
* @param {Object} themePackage is a package from the extension manager for the theme to be loaded.
* @return {$.Promise} promise object resolved with the theme to be loaded from the pacakge
*/
function loadPackage(themePackage) {
var fileName = themePackage.path + "/" + themePackage.metadata.theme.file;
return loadFile(fileName, themePackage.metadata);
}
prefs.on("change", "theme", function () {
// Make sure we don't reprocess a theme that's already loaded
if (currentTheme && currentTheme.name === prefs.get("theme")) {
return;
}
// Refresh editor with the new theme
refresh(true);
// Process the scrollbars for the editor
ThemeView.updateScrollbars(getCurrentTheme());
// Expose event for theme changes
exports.trigger("themeChange", getCurrentTheme());
});
prefs.on("change", "themeScrollbars", function () {
refresh();
ThemeView.updateScrollbars(getCurrentTheme());
});
// Monitor file changes. If the file that has changed is actually the currently loaded
// theme, then we just reload the theme. This allows to live edit the theme
FileSystem.on("change", function (evt, file) {
if (!file || file.isDirectory) {
return;
}
if (getThemeByFile(file)) {
refresh(true);
}
});
EditorManager.on("activeEditorChange", function () {
refresh();
});
EventDispatcher.makeEventDispatcher(exports);
exports.refresh = refresh;
exports.loadFile = loadFile;
exports.loadPackage = loadPackage;
exports.getCurrentTheme = getCurrentTheme;
exports.getAllThemes = getAllThemes;
// Exposed for testing purposes
exports._toDisplayName = toDisplayName;
exports._extractScrollbars = extractScrollbars;
});