This repository was 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.5k
Expand file tree
/
Copy pathPreferencesBase.js
More file actions
1724 lines (1548 loc) · 64.5 KB
/
PreferencesBase.js
File metadata and controls
1724 lines (1548 loc) · 64.5 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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2013 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 Base */
/**
* Infrastructure for the preferences system.
*
* At the top, the level at which most people will interact, is the `PreferencesSystem` object.
* The most common operation is `get(id)`, which simply retrieves the value of a given preference.
*
* The PreferencesSystem has a collection of Scopes, which it traverses in a specified order.
* Each Scope holds one level of settings.
*
* PreferencesManager.js sets up a singleton PreferencesSystem that has the following Scopes:
*
* * default (the default values for any settings that are explicitly registered)
* * user (the user's customized settings – the equivalent of Brackets' old
* localStorage-based system. This is the settings file that lives in AppData)
* * Additional scopes for each .brackets.json file going upward in the file tree from the
* current file
*
* For example, if spaceUnits has a value set in a .brackets.json file near the open file,
* then a call to get("spaceUnits") would return the value from that file. File values come
* first, user values next, default values last. If the setting is not known
* at all, undefined is returned.
*
* Each Scope has an associated Storage object that knows how to load and
* save the preferences value for that Scope. There are two implementations:
* MemoryStorage and FileStorage.
*
* The final concept used is that of Layers, which can be added to Scopes. Generally, a Layer looks
* for a collection of preferences that are nested in some fashion in the Scope's
* data. Under certain circumstances (decided upon by the Layer object),
* those nested preferences will take precedence over the main preferences in the Scope.
*/
define(function (require, exports, module) {
"use strict";
var FileUtils = require("file/FileUtils"),
FileSystem = require("filesystem/FileSystem"),
ExtensionLoader = require("utils/ExtensionLoader"),
CollectionUtils = require("utils/CollectionUtils"),
_ = require("thirdparty/lodash"),
Async = require("utils/Async"),
globmatch = require("thirdparty/globmatch");
// CONSTANTS
var PREFERENCE_CHANGE = "change",
SCOPEORDER_CHANGE = "scopeOrderChange";
/*
* Storages manage the loading and saving of preference data.
*/
/**
* MemoryStorage, as the name implies, stores the preferences in memory.
* This is suitable for single session data or testing.
*
* @param {?Object} data Initial data for the storage.
*/
function MemoryStorage(data) {
this.data = data || {};
}
MemoryStorage.prototype = {
/**
* *Synchronously* returns the data stored in this storage.
* The original object (not a clone) is returned.
*
* @return {Promise} promise that is already resolved
*/
load: function () {
var result = $.Deferred();
result.resolve(this.data);
return result.promise();
},
/**
* *Synchronously* saves the data to this storage. This saves
* the `newData` object reference without cloning it.
*
* @param {Object} newData The data to store.
* @return {Promise} promise that is already resolved
*/
save: function (newData) {
var result = $.Deferred();
this.data = newData;
result.resolve();
return result.promise();
},
/**
* MemoryStorage is not stored in a file, so fileChanged is ignored.
*
* @param {string} filePath File that has changed
*/
fileChanged: function (filePath) {
}
};
/**
* Error type for problems parsing preference files.
*
* @param {string} message Error message
*/
function ParsingError(message) {
this.name = "ParsingError";
this.message = message || "";
}
ParsingError.prototype = new Error();
/**
* Loads/saves preferences from a JSON file on disk.
*
* @param {string} path Path to the preferences file
* @param {boolean} createIfNew True if the file should be created if it doesn't exist.
* If this is not true, an exception will be thrown if the
* file does not exist.
*/
function FileStorage(path, createIfNew) {
this.path = path;
this.createIfNew = createIfNew;
this._lineEndings = FileUtils.getPlatformLineEndings();
}
FileStorage.prototype = {
/**
* Loads the preferences from disk. Can throw an exception if the file is not
* readable or parseable.
*
* @return {Promise} Resolved with the data once it has been parsed.
*/
load: function () {
var result = $.Deferred();
var path = this.path;
var createIfNew = this.createIfNew;
var self = this;
if (path) {
var prefFile = FileSystem.getFileForPath(path);
prefFile.read({}, function (err, text) {
if (err) {
if (createIfNew) {
result.resolve({});
} else {
result.reject(new Error("Unable to load prefs at " + path + " " + err));
}
return;
}
self._lineEndings = FileUtils.sniffLineEndings(text);
// If the file is empty, turn it into an empty object
if (/^\s*$/.test(text)) {
result.resolve({});
} else {
try {
result.resolve(JSON.parse(text));
} catch (e) {
result.reject(new ParsingError("Invalid JSON settings at " + path + "(" + e.toString() + ")"));
}
}
});
} else {
result.resolve({});
}
return result.promise();
},
/**
* Saves the new data to disk.
*
* @param {Object} newData data to save
* @return {Promise} Promise resolved (with no arguments) once the data has been saved
*/
save: function (newData) {
var result = $.Deferred();
var path = this.path;
var prefFile = FileSystem.getFileForPath(path);
if (path) {
try {
var text = JSON.stringify(newData, null, 4);
// maintain the original line endings
text = FileUtils.translateLineEndings(text, this._lineEndings);
prefFile.write(text, {}, function (err) {
if (err) {
result.reject("Unable to save prefs at " + path + " " + err);
} else {
result.resolve();
}
});
} catch (e) {
result.reject("Unable to convert prefs to JSON" + e.toString());
}
} else {
result.resolve();
}
return result.promise();
},
/**
* Changes the path to the preferences file.
* This sends a "changed" event to listeners, regardless of whether
* the path has changed.
*
* @param {string} newPath location of this settings file
*/
setPath: function (newPath) {
this.path = newPath;
$(this).trigger("changed");
},
/**
* If the filename matches this Storage's path, a changed message is triggered.
*
* @param {string} filePath File that has changed
*/
fileChanged: function (filePath) {
if (filePath === this.path) {
$(this).trigger("changed");
}
}
};
/**
* A `Scope` is a data container that is tied to a `Storage`.
*
* Additionally, `Scope`s support "layers" which are additional levels of preferences
* that are stored within a single preferences file.
*
* @param {Storage} storage Storage object from which prefs are loaded/saved
*/
function Scope(storage) {
this.storage = storage;
$(storage).on("changed", this.load.bind(this));
this.data = {};
this._dirty = false;
this._layers = [];
this._layerMap = {};
this._exclusions = [];
}
_.extend(Scope.prototype, {
/**
* Loads the prefs for this `Scope` from the `Storage`.
*
* @return {Promise} Promise that is resolved once loading is complete
*/
load: function () {
var result = $.Deferred();
this.storage.load()
.then(function (data) {
var oldKeys = this.getKeys();
this.data = data;
result.resolve();
$(this).trigger(PREFERENCE_CHANGE, {
ids: _.union(this.getKeys(), oldKeys)
});
}.bind(this))
.fail(function (error) {
result.reject(error);
});
return result.promise();
},
/**
* Saves the prefs for this `Scope`.
*
* @return {Promise} promise resolved once the data is saved.
*/
save: function () {
var self = this;
if (this._dirty) {
self._dirty = false;
return this.storage.save(this.data);
} else {
return $.Deferred().resolve().promise();
}
},
/**
* Sets the value for `id`. The value is set at the location given, or at the current
* location for the preference if no location is specified. If an invalid location is
* given, nothing will be set and no exception is thrown.
*
* @param {string} id Key to set
* @param {*} value Value for this key
* @param {Object=} context Optional additional information about the request (typically used for layers)
* @param {{layer: ?string, layerID: ?Object}=} location Optional location in which to set the value.
* If the object is empty, the value will be
* set at the Scope's base level.
* @return {boolean} true if the value was set
*/
set: function (id, value, context, location) {
if (!location) {
location = this.getPreferenceLocation(id, context);
}
if (location && location.layer) {
var layer = this._layerMap[location.layer];
if (layer) {
if (this.data[layer.key] === undefined) {
this.data[layer.key] = {};
}
var wasSet = layer.set(this.data[layer.key], id, value, context, location.layerID);
this._dirty = this._dirty || wasSet;
return wasSet;
} else {
return false;
}
} else {
return this._performSet(id, value);
}
},
/**
* @private
*
* Performs the set operation on this Scope's data, deleting the given ID if
* the new value is undefined. The dirty flag will be set as well.
*
* @param {string} id key to set or delete
* @param {*} value value for this key (undefined to delete)
* @return {boolean} true if the value was set.
*/
_performSet: function (id, value) {
if (!_.isEqual(this.data[id], value)) {
this._dirty = true;
if (value === undefined) {
delete this.data[id];
} else {
this.data[id] = _.cloneDeep(value);
}
return true;
}
return false;
},
/**
* Get the value for id, given the context. The context is provided to layers
* which may override the value from the main data of the Scope. Note that
* layers will often exclude values from consideration.
*
* @param {string} id Preference to retrieve
* @param {?Object} context Optional additional information about the request
* @return {*} Current value of the Preference
*/
get: function (id, context) {
var layerCounter,
layers = this._layers,
layer,
data = this.data,
result;
context = context || {};
for (layerCounter = 0; layerCounter < layers.length; layerCounter++) {
layer = layers[layerCounter];
result = layer.get(data[layer.key], id, context);
if (result !== undefined) {
return result;
}
}
if (this._exclusions.indexOf(id) === -1) {
return data[id];
}
},
/**
* Get the location in this Scope (if any) where the given preference is set.
*
* @param {string} id Name of the preference for which the value should be retrieved
* @param {Object=} context Optional context object to change the preference lookup
* @return {{layer: ?string, layerID: ?object}|undefined} Object describing where the preferences came from.
* An empty object means that it was defined in the Scope's
* base data. Undefined means the pref is not
* defined in this Scope.
*/
getPreferenceLocation: function (id, context) {
var layerCounter,
layers = this._layers,
layer,
data = this.data,
result;
context = context || {};
for (layerCounter = 0; layerCounter < layers.length; layerCounter++) {
layer = layers[layerCounter];
result = layer.getPreferenceLocation(data[layer.key], id, context);
if (result !== undefined) {
return {
layer: layer.key,
layerID: result
};
}
}
if (this._exclusions.indexOf(id) === -1 && data[id] !== undefined) {
// The value is defined in this Scope, which means we need to return an
// empty object as a signal to the PreferencesSystem that this pref
// is defined in this Scope (in the base data)
return {};
}
// return undefined when this Scope does not have the requested pref
return undefined;
},
/**
* Get the preference IDs that are set in this Scope. All layers are added
* in. If context is not provided, the set of all keys in the Scope including
* all keys in each layer will be returned.
*
* @param {?Object} context Optional additional information for looking up the keys
* @return {Array.<string>} Set of preferences set by this Scope
*/
getKeys: function (context) {
context = context || {};
var layerCounter,
layers = this._layers,
layer,
data = this.data;
var keySets = [_.difference(_.keys(data), this._exclusions)];
for (layerCounter = 0; layerCounter < layers.length; layerCounter++) {
layer = layers[layerCounter];
keySets.push(layer.getKeys(data[layer.key], context));
}
return _.union.apply(null, keySets);
},
/**
* Adds a Layer to this Scope. The Layer object should define a `key`, which
* represents the subset of the preference data that the Layer works with.
* Layers should also define `get` and `getKeys` operations that are like their
* counterparts in Scope but take "data" as the first argument.
*
* Listeners are notified of potential changes in preferences with the addition of
* this layer.
*
* @param {Layer} layer Layer object to add to this Scope
*/
addLayer: function (layer) {
this._layers.push(layer);
this._layerMap[layer.key] = layer;
this._exclusions.push(layer.key);
$(this).trigger(PREFERENCE_CHANGE, {
ids: layer.getKeys(this.data[layer.key], {})
});
},
/**
* Tells the Scope that the given file has been changed so that the
* Storage can be reloaded if needed.
*
* @param {string} filePath File that has changed
*/
fileChanged: function (filePath) {
this.storage.fileChanged(filePath);
},
/**
* Determines if there are likely to be any changes based on a change
* to the default filename used in lookups.
*
* @param {string} filename New filename
* @param {string} oldFilename Old filename
* @return {Array.<string>} List of changed IDs
*/
defaultFilenameChanged: function (filename, oldFilename) {
var changes = [],
data = this.data;
_.each(this._layers, function (layer) {
if (layer.defaultFilenameChanged && data[layer.key]) {
var changesInLayer = layer.defaultFilenameChanged(data[layer.key],
filename,
oldFilename);
if (changesInLayer) {
changes.push(changesInLayer);
}
}
});
return _.union.apply(null, changes);
}
});
// Utility functions for the PathLayer
/**
* @private
*
* Look for a matching file glob among the collection of paths.
*
* @param {Object} pathData The keys are globs and the values are the preferences for that glob
* @param {string} filename relative filename to match against the globs
* @return {?string} glob pattern that matched, if any
*/
function _findMatchingGlob(pathData, filename) {
var globs = Object.keys(pathData),
globCounter;
if (!filename) {
return;
}
for (globCounter = 0; globCounter < globs.length; globCounter++) {
var glob = globs[globCounter];
if (globmatch(filename, glob)) {
return glob;
}
}
}
/**
* @constructor
*
* Create a default project layer object that has a single property "key"
* with "project" as its value.
*
*/
function ProjectLayer() {
this.projectPath = null;
}
ProjectLayer.prototype = {
key: "project",
/**
* Retrieve the current value based on the current project path
* in the layer.
*
* @param {Object} data the preference data from the Scope
* @param {string} id preference ID to look up
*/
get: function (data, id) {
if (!data || !this.projectPath) {
return;
}
if (data[this.projectPath] && data[this.projectPath][id]) {
return data[this.projectPath][id];
}
return;
},
/**
* Gets the location in which the given pref was set, if it was set within
* this project layer for the current project path.
*
* @param {Object} data the preference data from the Scope
* @param {string} id preference ID to look up
* @return {string} the Layer ID, in this case the current project path.
*/
getPreferenceLocation: function (data, id) {
if (!data || !this.projectPath) {
return;
}
if (data[this.projectPath] && data[this.projectPath][id]) {
return this.projectPath;
}
return;
},
/**
* Sets the preference value in the given data structure for the layerID provided. If no
* layerID is provided, then the current project path is used. If a layerID is provided
* and it does not exist, it will be created.
*
* This function returns whether or not a value was set.
*
* @param {Object} data the preference data from the Scope
* @param {string} id preference ID to look up
* @param {Object} value new value to assign to the preference
* @param {Object} context Object with scope and layer key-value pairs (not yet used in project layer)
* @param {string=} layerID Optional: project path to be used for setting value
* @return {boolean} true if the value was set
*/
set: function (data, id, value, context, layerID) {
if (!layerID) {
layerID = this.getPreferenceLocation(data, id);
}
if (!layerID) {
return false;
}
var section = data[layerID];
if (!section) {
data[layerID] = section = {};
}
if (!_.isEqual(section[id], value)) {
if (value === undefined) {
delete section[id];
} else {
section[id] = _.cloneDeep(value);
}
return true;
}
return false;
},
/**
* Retrieves the keys provided by this layer object.
*
* @param {Object} data the preference data from the Scope
*/
getKeys: function (data) {
if (!data) {
return;
}
return _.union.apply(null, _.map(_.values(data), _.keys));
},
/**
* Set the project path to be used as the layer ID of this layer object.
*
* @param {string} projectPath Path of the project root
*/
setProjectPath: function (projectPath) {
this.projectPath = projectPath;
}
};
/**
* Provides layered preferences based on file globs, generally following the model provided
* by [EditorConfig](http://editorconfig.org/). In usage, it looks something like this
* (switching to single line comments because the glob interferes with the multiline comment):
*/
// "path": {
// "src/thirdparty/CodeMirror2/**/*.js": {
// "spaceUnits": 2,
// "linting.enabled": false
// }
// }
/**
* There can be multiple paths and they are each checked in turn. The first that matches the
* currently edited file wins.
*
* @param {string} prefFilePath path to the preference file
*/
function PathLayer(prefFilePath) {
this.setPrefFilePath(prefFilePath);
}
PathLayer.prototype = {
key: "path",
/**
* Retrieve the current value based on the filename in the context
* object, comparing globs relative to the prefFilePath that this
* PathLayer was set up with.
*
* @param {Object} data the preference data from the Scope
* @param {string} id preference ID to look up
* @param {Object} context Object with filename that will be compared to the globs
*/
get: function (data, id, context) {
var glob = this.getPreferenceLocation(data, id, context);
if (!glob) {
return;
}
return data[glob][id];
},
/**
* Gets the location in which the given pref was set, if it was set within
* this path layer for the current path.
*
* @param {Object} data the preference data from the Scope
* @param {string} id preference ID to look up
* @param {Object} context Object with filename that will be compared to the globs
* @return {string} the Layer ID, in this case the glob that matched
*/
getPreferenceLocation: function (data, id, context) {
if (!data) {
return;
}
var relativeFilename = FileUtils.getRelativeFilename(this.prefFilePath, context.filename);
if (!relativeFilename) {
return;
}
return _findMatchingGlob(data, relativeFilename);
},
/**
* Sets the preference value in the given data structure for the layerID provided. If no
* layerID is provided, then the current layer is used. If a layerID is provided and it
* does not exist, it will be created.
*
* This function returns whether or not a value was set.
*
* @param {Object} data the preference data from the Scope
* @param {string} id preference ID to look up
* @param {Object} value new value to assign to the preference
* @param {Object} context Object with filename that will be compared to the globs
* @param {string=} layerID Optional: glob pattern for a specific section to set the value in
* @return {boolean} true if the value was set
*/
set: function (data, id, value, context, layerID) {
if (!layerID) {
layerID = this.getPreferenceLocation(data, id, context);
}
if (!layerID) {
return false;
}
var section = data[layerID];
if (!section) {
data[layerID] = section = {};
}
if (!_.isEqual(section[id], value)) {
if (value === undefined) {
delete section[id];
} else {
section[id] = _.cloneDeep(value);
}
return true;
}
return false;
},
/**
* Retrieves the keys provided by this layer object. If context with a filename is provided,
* only the keys for the matching file glob are given. Otherwise, all keys for all globs
* are provided.
*
* @param {Object} data the preference data from the Scope
* @param {?Object} context Additional context data (filename in particular is important)
*/
getKeys: function (data, context) {
if (!data) {
return;
}
var relativeFilename = FileUtils.getRelativeFilename(this.prefFilePath, context.filename);
if (relativeFilename) {
var glob = _findMatchingGlob(data, relativeFilename);
if (glob) {
return _.keys(data[glob]);
} else {
return [];
}
}
return _.union.apply(null, _.map(_.values(data), _.keys));
},
/**
* Changes the preference file path.
*
* @param {string} prefFilePath New path to the preferences file
*/
setPrefFilePath: function (prefFilePath) {
if (!prefFilePath) {
this.prefFilePath = "/";
} else {
this.prefFilePath = FileUtils.getDirectoryPath(prefFilePath);
}
},
/**
* Determines if there are preference IDs that could change as a result of
* a change to the default filename.
*
* @param {Object} data Data in the Scope
* @param {string} filename New filename
* @param {string} oldFilename Old filename
* @return {Array.<string>} list of preference IDs that could have changed
*/
defaultFilenameChanged: function (data, filename, oldFilename) {
var newGlob = _findMatchingGlob(data,
FileUtils.getRelativeFilename(this.prefFilePath, filename)),
oldGlob = _findMatchingGlob(data,
FileUtils.getRelativeFilename(this.prefFilePath, oldFilename));
if (newGlob === oldGlob) {
return;
}
if (newGlob === undefined) {
return _.keys(data[oldGlob]);
}
if (oldGlob === undefined) {
return _.keys(data[newGlob]);
}
return _.union(_.keys(data[oldGlob]), _.keys(data[newGlob]));
}
};
/**
* Represents a single, known Preference.
*
* @param {Object} properties Information about the Preference that is stored on this object
*/
function Preference(properties) {
_.extend(this, properties);
}
_.extend(Preference.prototype, {
/**
* Sets an event handler on this Preference.
*
* @param {string} event Event name
* @param {Function} handler Function to handle the event
*/
on: function (event, handler) {
$(this).on(event, handler);
},
/**
* Removes an event handler from this Preference
*
* @param {string} event Event name
* @param {?Function} handler Optional specific function to stop receiving events
*/
off: function (event, handler) {
$(this).off(event, handler);
}
});
/**
* Provides a subset of the PreferencesSystem functionality with preference
* access always occurring with the given prefix.
*
* @param {PreferencesSystem} baseSystem The real PreferencesSystem that is backing this one
* @param {string} prefix Prefix that is used for preferences lookup. Any separator characters should already be added.
*/
function PrefixedPreferencesSystem(base, prefix) {
this.base = base;
this.prefix = prefix;
this._listenerInstalled = false;
}
PrefixedPreferencesSystem.prototype = {
/**
* Defines a new (prefixed) preference.
*
* @param {string} id unprefixed identifier of the preference. Generally a dotted name.
* @param {string} type Data type for the preference (generally, string, boolean, number)
* @param {Object} initial Default value for the preference
* @param {?Object} options Additional options for the pref. Can include name and description
* that will ultimately be used in UI.
* @return {Object} The preference object.
*/
definePreference: function (id, type, initial, options) {
return this.base.definePreference(this.prefix + id, type, initial, options);
},
/**
* Get the prefixed preference object
*
* @param {string} id ID of the pref to retrieve.
*/
getPreference: function (id) {
return this.base.getPreference(this.prefix + id);
},
/**
* Gets the prefixed preference
*
* @param {string} id Name of the preference for which the value should be retrieved
* @param {Object=} context Optional context object to change the preference lookup
*/
get: function (id, context) {
return this.base.get(this.prefix + id, context);
},
/**
* Gets the location in which the value of a prefixed preference has been set.
*
* @param {string} id Name of the preference for which the value should be retrieved
* @param {Object=} context Optional context object to change the preference lookup
* @return {{scope: string, layer: ?string, layerID: ?object}} Object describing where the preferences came from
*/
getPreferenceLocation: function (id, context) {
return this.base.getPreferenceLocation(this.prefix + id, context);
},
/**
* Sets the prefixed preference
*
* @param {string} id Identifier of the preference to set
* @param {Object} value New value for the preference
* @param {{location: ?Object, context: ?Object}=} options Specific location in which to set the value or the context to use when setting the value
* @return {boolean} true if a value was set
*/
set: function (id, value, options) {
return this.base.set(this.prefix + id, value, options);
},
/**
* @private
*
* Listens for events on the base PreferencesSystem to filter down to the
* events that consumers of this PreferencesSystem would be interested in.
*/
_installListener: function () {
if (this._listenerInstalled) {
return;
}
var $this = $(this),
prefix = this.prefix;
var onlyWithPrefix = function (id) {
if (id.substr(0, prefix.length) === prefix) {
return true;
}
return false;
};
var withoutPrefix = function (id) {
return id.substr(prefix.length);
};
$(this.base).on(PREFERENCE_CHANGE, function (e, data) {
var prefixedIds = data.ids.filter(onlyWithPrefix);
if (prefixedIds.length > 0) {
$this.trigger(PREFERENCE_CHANGE, {
ids: prefixedIds.map(withoutPrefix)
});
}
});
this._listenerInstalled = true;
},
/**
* Sets up a listener for events for this PrefixedPreferencesSystem. Only prefixed events
* will notify. Optionally, you can set up a listener for a
* specific preference.
*
* @param {string} event Name of the event to listen for
* @param {string|Function} preferenceID Name of a specific preference or the handler function
* @param {?Function} handler Handler for the event
*/
on: function (event, preferenceID, handler) {
if (typeof preferenceID === "function") {
handler = preferenceID;
preferenceID = null;
}
if (preferenceID) {
var pref = this.getPreference(preferenceID);
pref.on(event, handler);
} else {
this._installListener();
$(this).on(event, handler);
}
},
/**
* Turns off the event handlers for a given event, optionally for a specific preference
* or a specific handler function.
*