This repository has been archived by the owner on Sep 6, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7.6k
/
Copy pathPreferencesManager.js
335 lines (286 loc) · 12.3 KB
/
PreferencesManager.js
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
/*
* Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
*
* 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.
*
*/
/*global define, $, localStorage, brackets, console */
/*unittests: Preferences Manager */
/**
* PreferencesManager
*
*/
define(function (require, exports, module) {
"use strict";
var OldPreferenceStorage = require("preferences/PreferenceStorage").PreferenceStorage,
FileUtils = require("file/FileUtils"),
ExtensionLoader = require("utils/ExtensionLoader"),
PreferencesBase = require("preferences/PreferencesBase"),
FileSystem = require("filesystem/FileSystem"),
_ = require("thirdparty/lodash");
/**
* The local storage ID
* @const
* @type {string}
*/
var PREFERENCES_CLIENT_ID = "com.adobe.brackets.preferences";
/**
* The prefix used in the generated client ID
* @const
* @type {string}
*/
var CLIENT_ID_PREFIX = "com.adobe.brackets.";
// Private Properties
var preferencesKey,
prefStorage,
persistentStorage,
extensionPaths,
doLoadPreferences = false;
/**
* @private
* Returns an array with the extension paths used in Brackets. The result is stored on a
* private variable on the first call and used to return the value on the next calls.
* @return {Array.<string>}
*/
function _getExtensionPaths() {
if (!extensionPaths) {
var dirPath = FileUtils.getNativeBracketsDirectoryPath();
extensionPaths = [
dirPath + "/extensions/default/",
dirPath + "/extensions/dev/",
ExtensionLoader.getUserExtensionPath() + "/"
];
}
return extensionPaths;
}
/**
* This method returns a standardized ClientID for a given requireJS module object
* @param {!{id: string, uri: string}} module - A requireJS module object
* @return {string} The ClientID
*/
function getClientID(module) {
var paths = exports._getExtensionPaths();
var pathExp, pathUrl, clientID;
paths.some(function (path) {
if (module.uri.toLocaleLowerCase().indexOf(path.toLocaleLowerCase()) === 0) {
pathUrl = path;
return true;
}
});
if (pathUrl) {
clientID = CLIENT_ID_PREFIX + module.uri.replace(pathUrl, "");
} else {
clientID = CLIENT_ID_PREFIX + module.id;
}
return clientID;
}
/**
* Retreive the preferences data for the given clientID.
* @param {string|{id: string, uri: string}} clientID - A unique identifier or a requireJS module object
* @param {string=} defaults - Default preferences stored as JSON
* @param {boolean=} _doNotCreate Do not create the storage if it does not already exist. Used for conversion.
* @return {PreferenceStorage}
*/
function getPreferenceStorage(clientID, defaults, _doNotCreate) {
if (!clientID || (typeof clientID === "object" && (!clientID.id || !clientID.uri))) {
console.error("Invalid clientID");
return;
}
if (typeof clientID === "object") {
clientID = getClientID(clientID);
}
var prefs = prefStorage[clientID];
if (prefs === undefined) {
if (_doNotCreate) {
return;
}
// create a new empty preferences object
prefs = (defaults && JSON.stringify(defaults)) ? defaults : {};
prefStorage[clientID] = prefs;
} else if (defaults) {
// add new defaults
_.forEach(defaults, function (value, key) {
if (prefs[key] === undefined) {
prefs[key] = value;
}
});
}
return new OldPreferenceStorage(clientID, prefs);
}
/**
* Save all preference clients.
*/
function savePreferences() {
// save all preferences
persistentStorage.setItem(preferencesKey, JSON.stringify(prefStorage));
}
/**
* @private
* Reset preferences and callbacks
*/
function _reset() {
prefStorage = {};
// Note that storage.clear() is not used. Production and unit test code
// both rely on the same backing storage but unique item keys.
persistentStorage.setItem(preferencesKey, JSON.stringify(prefStorage));
}
/**
* @private
* Initialize persistent storage implementation
*/
function _initStorage(storage) {
persistentStorage = storage;
if (doLoadPreferences) {
prefStorage = JSON.parse(persistentStorage.getItem(preferencesKey));
}
// initialize empty preferences if none were found in storage
if (!prefStorage) {
_reset();
}
}
// Check localStorage for a preferencesKey. Production and unit test keys
// are used to keep preferences separate within the same storage implementation.
preferencesKey = localStorage.getItem("preferencesKey");
if (!preferencesKey) {
// use default key if none is found
preferencesKey = PREFERENCES_CLIENT_ID;
doLoadPreferences = true;
} else {
// using a non-default key, check for additional settings
doLoadPreferences = !!(localStorage.getItem("doLoadPreferences"));
}
// Use localStorage by default
_initStorage(localStorage);
// Public API
exports.getPreferenceStorage = getPreferenceStorage;
exports.savePreferences = savePreferences;
exports.getClientID = getClientID;
// Unit test use only
exports._reset = _reset;
exports._getExtensionPaths = _getExtensionPaths;
// New code follows. The code above (with the exception of the imports) is
// deprecated.
// The SETTINGS_FILENAME is used with a preceding "." within user projects
var SETTINGS_FILENAME = "brackets.json",
STATE_FILENAME = "state.json";
// User-level preferences
var userPrefFile = brackets.app.getApplicationSupportDirectory() + "/" + SETTINGS_FILENAME;
/**
* Get the full path to the user-level preferences file.
*
* @return {string} Path to the preferences file
*/
function getUserPrefFile() {
return userPrefFile;
}
var preferencesManager = new PreferencesBase.PreferencesSystem();
var userScope = preferencesManager.addScope("user", new PreferencesBase.FileStorage(userPrefFile, true));
// Set up the .brackets.json file handling
preferencesManager.addPathScopes(".brackets.json", {
before: "user",
checkExists: function (filename) {
var result = new $.Deferred(),
file = FileSystem.getFileForPath(filename);
file.exists(function (err, doesExist) {
result.resolve(doesExist);
});
return result.promise();
},
getScopeForFile: function (filename) {
return new PreferencesBase.Scope(new PreferencesBase.FileStorage(filename));
}
});
/**
* Creates an extension-specific preferences manager using the prefix given.
* A `.` character will be appended to the prefix. So, a preference named `foo`
* with a prefix of `myExtension` will be stored as `myExtension.foo` in the
* preferences files.
*
* @param {string} prefix Prefix to be applied
*/
function getExtensionPrefs(prefix) {
return preferencesManager.getPrefixedSystem(prefix);
}
/**
* Converts from the old localStorage-based preferences to the new-style
* preferences according to the "rules" given.
*
* `rules` is an object, the keys of which refer to the preference names.
* The value tells the converter what to do. The following values are available:
*
* * `user`: convert to a user-level preference
* * `user newkey`: convert to a user-level preference, changing the key to newkey
*
* Once a key has been converted, it will not be converted again.
*
* @param {string|Object} clientID ClientID used in the old preferences
* @param {Object} rules Rules for conversion (as defined above)
*/
function convertPreferences(clientID, rules) {
userScope.done(function () {
var prefs = getPreferenceStorage(clientID, null, true);
if (!prefs) {
return;
}
var prefsID = getClientID(clientID);
if (prefStorage.convertedKeysMap === undefined) {
prefStorage.convertedKeysMap = {};
}
var convertedKeysMap = prefStorage.convertedKeysMap;
prefs.convert(rules, convertedKeysMap[prefsID]).done(function (complete, convertedKeys) {
prefStorage.convertedKeysMap[prefsID] = convertedKeys;
savePreferences();
});
}).fail(function (error) {
console.error("Error while converting ", getClientID(clientID));
console.error(error);
});
}
// "State" is stored like preferences but it is not generally intended to be user-editable.
// It's for more internal, implicit things like window size, working set, etc.
var stateManager = new PreferencesBase.PreferencesSystem();
var userStateFile = brackets.app.getApplicationSupportDirectory() + "/" + STATE_FILENAME;
stateManager.addScope("user", new PreferencesBase.FileStorage(userStateFile, true));
// Convenience function that sets a preference and then saves the file, mimicking the
// old behavior a bit more closely.
function setValueAndSave(scopeName, id, value) {
preferencesManager.set(scopeName, id, value);
preferencesManager.save();
}
// Private API for unit testing and use elsewhere in Brackets core
exports._manager = preferencesManager;
exports._setCurrentEditingFile = preferencesManager.setPathScopeContext.bind(preferencesManager);
// Public API
exports.getUserPrefFile = getUserPrefFile;
exports.get = preferencesManager.get.bind(preferencesManager);
exports.set = preferencesManager.set.bind(preferencesManager);
exports.save = preferencesManager.save.bind(preferencesManager);
exports.on = preferencesManager.on.bind(preferencesManager);
exports.off = preferencesManager.off.bind(preferencesManager);
exports.getPreference = preferencesManager.getPreference.bind(preferencesManager);
exports.getExtensionPrefs = getExtensionPrefs;
exports.setValueAndSave = setValueAndSave;
exports.addScope = preferencesManager.addScope.bind(preferencesManager);
exports.stateManager = stateManager;
exports.FileStorage = PreferencesBase.FileStorage;
exports.SETTINGS_FILENAME = SETTINGS_FILENAME;
exports.definePreference = preferencesManager.definePreference.bind(preferencesManager);
exports.fileChanged = preferencesManager.fileChanged.bind(preferencesManager);
exports.convertPreferences = convertPreferences;
});