-
-
Notifications
You must be signed in to change notification settings - Fork 11.2k
/
options-store.js
571 lines (500 loc) · 17.9 KB
/
options-store.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
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
/*
* Copyright Adam Pritchard 2015
* MIT License : https://adampritchard.mit-license.org/
*/
;(function() {
"use strict";
/*global module:false, chrome:false, Components:false*/
if (typeof(Utils) === 'undefined' && typeof(Components) !== 'undefined') {
var scriptLoader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"]
.getService(Components.interfaces.mozIJSSubScriptLoader);
scriptLoader.loadSubScript('resource://markdown_here_common/utils.js');
}
// Common defaults
var DEFAULTS = {
'math-enabled': false,
'math-value': '<img src="https://latex.codecogs.com/png.image?\\dpi{120}\\inline&space;{urlmathcode}" alt="{mathcode}">',
'hotkey': { shiftKey: false, ctrlKey: true, altKey: true, key: 'M' },
'forgot-to-render-check-enabled': false,
'header-anchors-enabled': false,
'gfm-line-breaks-enabled': true
};
/*? if(platform!=='thunderbird'){ */
/*
* Chrome storage helper. Gets around the synchronized value size limit.
* Overall quota limits still apply (or less, but we should stay well within).
* Limitations:
* - `get` gets the entire options object and `set` sets the entire options
* object (unlike the underlying `chrome.storage.sync` functions).
*
* Long strings are broken into pieces and stored in separate fields. They are
* recombined when retrieved.
*
* Note that we fall back to (unsynced) localStorage if chrome.storage isn't
* available. This is the case in Chromium v18 (currently the latest available
* via Ubuntu repo). Part of the reason we JSON-encode values is to get around
* the fact that you can only store strings with localStorage.
*
* Chrome note/warning: OptionsStore can't be used directly from a content script.
* When it tries to fill in the CSS defaults with a XHR request, it'll fail with
* a cross-domain restriction error. Instead use the service provided by the
* background script.
*/
// TODO: Check for errors. See: https://code.google.com/chrome/extensions/dev/storage.html
var ChromeOptionsStore = {
// The options object will be passed to `callback`
get: function(callback) {
var that = this;
this._storageGet(function(sync) {
// Process the object, recombining divided entries.
var tempobj = {}, finalobj = {};
for (var key in sync) {
var val = sync[key];
var divIndex = key.indexOf(that._div);
if (divIndex < 0) {
finalobj[key] = val;
}
else {
var keybase = key.slice(0, divIndex);
var keynum = key.slice(divIndex+that._div.length);
tempobj[keybase] = tempobj[keybase] || [];
tempobj[keybase][keynum] = val;
}
}
// Recombine the divided entries.
for (key in tempobj) {
finalobj[key] = tempobj[key].join('');
}
that._fillDefaults(finalobj, callback);
});
},
// Store `obj`, splitting long strings when necessary. `callback` will be
// called (with no arguments) when complete.
set: function(obj, callback) {
var that = this;
// First clear out existing entries.
this._clearExisting(obj, function() {
// Split long string entries into pieces, so we don't exceed the limit.
var finalobj = {};
for (var key in obj) {
var val = obj[key];
if (typeof(val) !== 'string' || val.length < that._maxlen()) {
// Don't need to split, or can't.
finalobj[key] = val;
}
else {
var pieces = Math.ceil(val.length / that._maxlen());
for (var i = 0; i < pieces; i++) {
finalobj[key+that._div+i] = val.substr(i*that._maxlen(), that._maxlen());
}
}
}
that._storageSet(finalobj, function() {
if (callback) callback();
});
});
},
remove: function(arrayOfKeys, callback) {
var that = this;
if (typeof(arrayOfKeys) === 'string') {
arrayOfKeys = [arrayOfKeys];
}
this._clearExisting(arrayOfKeys, callback);
},
// The default values or URLs for our various options.
defaults: {
'main-css': {'__defaultFromFile__': '/common/default.css', '__dataType__': 'text'},
'syntax-css': {'__defaultFromFile__': '/common/highlightjs/styles/github.css', '__dataType__': 'text'},
'math-enabled': DEFAULTS['math-enabled'],
'math-value': DEFAULTS['math-value'],
'hotkey': DEFAULTS['hotkey'],
'forgot-to-render-check-enabled': DEFAULTS['forgot-to-render-check-enabled'],
'header-anchors-enabled': DEFAULTS['header-anchors-enabled'],
'gfm-line-breaks-enabled': DEFAULTS['gfm-line-breaks-enabled']
},
// Stored string pieces look like: {'key##0': 'the quick ', 'key##1': 'brown fox'}
_div: '##',
// HACK: Using the full length, or length-keylength, gives quota error.
// Because
_maxlen: function() {
// Note that chrome.storage.sync.QUOTA_BYTES_PER_ITEM is in bytes, but JavaScript
// strings are UTF-16, so we need to divide by 2.
// Some JS string info: https://rosettacode.org/wiki/String_length#JavaScript
if (chrome.storage && chrome.storage.sync && chrome.storage.sync.QUOTA_BYTES_PER_ITEM) {
return chrome.storage.sync.QUOTA_BYTES_PER_ITEM / 2;
}
else {
// 8192 is the default value for chrome.storage.sync.QUOTA_BYTES_PER_ITEM, so...
return 8192 / 2;
}
},
_storageGet: function(callback) {
if (chrome.storage) {
(chrome.storage.sync || chrome.storage.local).get(null, function(obj) {
var key;
for (key in obj) {
// Older settings aren't JSON-encoded, so they'll throw an exception.
try {
obj[key] = JSON.parse(obj[key]);
}
catch (ex) {
// do nothing, leave the value as-is
}
}
callback(obj);
});
return;
}
else {
// Make this actually an async call.
Utils.nextTick(function() {
var i, obj = {};
for (i = 0; i < localStorage.length; i++) {
// Older settings aren't JSON-encoded, so they'll throw an exception.
try {
obj[localStorage.key(i)] = JSON.parse(localStorage.getItem(localStorage.key(i)));
}
catch (ex) {
obj[localStorage.key(i)] = localStorage.getItem(localStorage.key(i));
}
}
callback(obj);
});
return;
}
},
_storageSet: function(obj, callback) {
var key, finalobj = {};
for (key in obj) {
finalobj[key] = JSON.stringify(obj[key]);
}
if (chrome.storage) {
(chrome.storage.sync || chrome.storage.local).set(finalobj, callback);
return;
}
else {
// Make this actually an async call.
Utils.nextTick(function() {
var key;
for (key in finalobj) {
localStorage.setItem(key, finalobj[key]);
}
if (callback) callback();
});
return;
}
},
_storageRemove: function(keysToDelete, callback) {
if (chrome.storage) {
(chrome.storage.sync || chrome.storage.local).remove(keysToDelete, callback);
return;
}
else {
// Make this actually an async call.
Utils.nextTick(function() {
var i;
for (i = 0; i < keysToDelete.length; i++) {
localStorage.removeItem(keysToDelete[i]);
}
callback();
});
return;
}
},
// Clear any existing entries that match the given object's members.
_clearExisting: function(obj, callback) {
var that = this, newObj = {}, i;
if (obj.constructor === Array) {
newObj = {};
for (i = 0; i < obj.length; i++) {
newObj[obj[i]] = null;
}
obj = newObj;
}
this._storageGet(function(sync) {
var keysToDelete = [];
for (var objKey in obj) {
for (var syncKey in sync) {
if (syncKey === objKey || syncKey.indexOf(objKey+that._div) === 0) {
keysToDelete.push(syncKey);
}
}
}
if (keysToDelete.length > 0) {
that._storageRemove(keysToDelete, callback);
}
else {
if (callback) callback();
}
});
}
};
/*? } */
/*? if(platform==='thunderbird'){ */
/*
* Mozilla preferences storage helper
*/
var MozillaOptionsStore = {
get: function(callback) {
var that = this;
this._sendRequest({verb: 'get'}, function(prefsObj) {
that._fillDefaults(prefsObj, callback);
});
},
set: function(obj, callback) {
this._sendRequest({verb: 'set', obj: obj}, callback);
},
remove: function(arrayOfKeys, callback) {
this._sendRequest({verb: 'clear', obj: arrayOfKeys}, callback);
},
// The default values or URLs for our various options.
defaults: {
'local-first-run': true,
'main-css': {'__defaultFromFile__': 'resource://markdown_here_common/default.css', '__dataType__': 'text/css'},
'syntax-css': {'__defaultFromFile__': 'resource://markdown_here_common/highlightjs/styles/github.css', '__dataType__': 'text/css'},
'math-enabled': DEFAULTS['math-enabled'],
'math-value': DEFAULTS['math-value'],
'hotkey': DEFAULTS['hotkey'],
'forgot-to-render-check-enabled': DEFAULTS['forgot-to-render-check-enabled'],
'header-anchors-enabled': DEFAULTS['header-anchors-enabled'],
'gfm-line-breaks-enabled': DEFAULTS['gfm-line-breaks-enabled']
},
// This is called both from content and background scripts, and we need vastly
// different code in those cases. When calling from a content script, we need
// to make a request to a background service (found in firefox/chrome/content/background-services.js).
// When called from a background script, we're going to access the browser prefs
// directly. Unfortunately, this means duplicating some code from the background
// service.
_sendRequest: function(data, callback) { // analogue of chrome.runtime.sendMessage
var privileged, prefsBranch, prefKeys, prefsObj, i;
privileged = (typeof(Components) !== 'undefined' && typeof(Components.classes) !== 'undefined');
if (!privileged) {
// This means that this code is being called from a content script.
// We need to send a request from this non-privileged context to the
// privileged background script.
data.action = 'prefs-access';
Utils.makeRequestToPrivilegedScript(
document,
data,
callback);
return;
}
prefsBranch = Components.classes['@mozilla.org/preferences-service;1']
.getService(Components.interfaces.nsIPrefService)
.getBranch('extensions.markdown-here.');
if (data.verb === 'get') {
prefKeys = prefsBranch.getChildList('');
prefsObj = {};
for (i = 0; i < prefKeys.length; i++) {
// All of our legitimate prefs should be strings, but issue #237 suggests
// that things may sometimes get into a bad state. We will check and delete
// and prefs that aren't strings.
// https://github.com/adam-p/markdown-here/issues/237
if (prefsBranch.getPrefType(prefKeys[i]) !== prefsBranch.PREF_STRING) {
prefsBranch.clearUserPref(prefKeys[i]);
continue;
}
prefsObj[prefKeys[i]] = Utils.getMozJsonPref(prefsBranch, prefKeys[i]);
}
callback(prefsObj);
return;
}
else if (data.verb === 'set') {
for (i in data.obj) {
Utils.setMozJsonPref(prefsBranch, i, data.obj[i]);
}
if (callback) callback();
return;
}
else if (data.verb === 'clear') {
if (typeof(data.obj) === 'string') {
data.obj = [data.obj];
}
for (i = 0; i < data.obj.length; i++) {
prefsBranch.clearUserPref(data.obj[i]);
}
if (callback) return callback();
return;
}
}
};
/*? } */
/*? if(platform==='safari'){ */
/*
* When called from the options page, this is effectively a content script, so
* we'll have to make calls to the background script in that case.
*/
var SafariOptionsStore = {
// The options object will be passed to `callback`
get: function(callback) {
var that = this;
this._getPreferences(function(options) {
that._fillDefaults(options, callback);
});
},
// Store `obj`. `callback` will be called (with no arguments) when complete.
set: function(obj, callback) {
this._setPreferences(obj, callback);
},
remove: function(arrayOfKeys, callback) {
this._removePreferences(arrayOfKeys, callback);
},
_getPreferences: function(callback) {
// Only the background script has `safari.extension.settings`.
if (typeof(safari.extension.settings) === 'undefined') {
// We're going to assume we have Utils and document available here, which
// should be the case, since we should be running as a content script.
Utils.makeRequestToPrivilegedScript(
document,
{ action: 'get-options' },
callback);
}
else {
// Make this actually asynchronous
Utils.nextTick(function() {
if (callback) callback(safari.extension.settings);
});
}
},
_setPreferences: function(obj, callback) {
// Only the background script has `safari.extension.settings`.
if (typeof(safari.extension.settings) === 'undefined') {
// We're going to assume we have Utils and document available here, which
// should be the case, since we should be running as a content script.
Utils.makeRequestToPrivilegedScript(
document,
{ action: 'set-options', options: obj },
callback);
}
else {
// Make this actually asynchronous
Utils.nextTick(function() {
for (var key in obj) {
safari.extension.settings[key] = obj[key];
}
if (callback) callback();
});
}
},
_removePreferences: function(arrayOfKeys, callback) {
// Only the background script has `safari.extension.settings`.
if (typeof(safari.extension.settings) === 'undefined') {
// We're going to assume we have Utils and document available here, which
// should be the case, since we should be running as a content script.
Utils.makeRequestToPrivilegedScript(
document,
{ action: 'remove-options', arrayOfKeys: arrayOfKeys },
callback);
}
else {
// Make this actually asynchronous
Utils.nextTick(function() {
var i;
if (typeof(arrayOfKeys) === 'string') {
arrayOfKeys = [arrayOfKeys];
}
for (i = 0; i < arrayOfKeys.length; i++) {
delete safari.extension.settings[arrayOfKeys[i]];
}
if (callback) callback();
});
}
},
// The default values or URLs for our various options.
defaults: {
'main-css': {'__defaultFromFile__': (typeof(safari) !== 'undefined' ? safari.extension.baseURI : '')+'markdown-here/src/common/default.css', '__dataType__': 'text/css'},
'syntax-css': {'__defaultFromFile__': (typeof(safari) !== 'undefined' ? safari.extension.baseURI : '')+'markdown-here/src/common/highlightjs/styles/github.css', '__dataType__': 'text/css'},
'math-enabled': DEFAULTS['math-enabled'],
'math-value': DEFAULTS['math-value'],
'hotkey': DEFAULTS['hotkey'],
'forgot-to-render-check-enabled': DEFAULTS['forgot-to-render-check-enabled'],
'header-anchors-enabled': DEFAULTS['header-anchors-enabled'],
'gfm-line-breaks-enabled': DEFAULTS['gfm-line-breaks-enabled']
}
};
/*? } */
// Choose which OptionsStore engine we should use.
// (This if-structure is ugly to work around the preprocessor logic.)
/*? if(platform==='chrome' || platform==='firefox'){ */
if (typeof(navigator) !== 'undefined'
&& (navigator.userAgent.indexOf('Chrome') >= 0
|| navigator.userAgent.indexOf('Firefox') >= 0)) {
this.OptionsStore = ChromeOptionsStore;
}
/*? } */
/*? if(platform==='safari'){ */
if (!this.OptionsStore
&& typeof(navigator) !== 'undefined'
&& navigator.userAgent.match(/AppleWebKit.*Version.*Safari/)) {
this.OptionsStore = SafariOptionsStore;
}
/*? } */
/*? if(platform==='thunderbird'){ */
// Thunderbird, Icedove
if (!this.OptionsStore) {
this.OptionsStore = MozillaOptionsStore;
}
/*? } */
this.OptionsStore._fillDefaults = function(prefsObj, callback) {
var that = this;
// Upgrade the object, if necessary.
// Motivation: Our default for the LaTeX renderer used to be Google Charts API. Google
// discontinued the service and we switched the default to CodeCogs, but because it was
// the default, it will be set in many users' OptionsStore. We need to forcibly replace it.
if (typeof prefsObj['math-value'] === 'string' && prefsObj['math-value'].indexOf('chart.googleapis.com') >= 0) {
prefsObj['math-value'] = that.defaults['math-value'];
}
var key, allKeys = [];
for (key in that.defaults) {
if (that.defaults.hasOwnProperty(key)) {
allKeys.push(key);
}
}
doNextKey();
function doNextKey() {
if (allKeys.length === 0) {
// All done.
// Ensure this function is actually asynchronous.
Utils.nextTick(function() {
callback(prefsObj);
});
return;
}
// Keep processing keys (and recurse)
doDefaultForKey(allKeys.pop(), doNextKey);
}
// This function may be asynchronous (if XHR occurs) or it may be a straight
// synchronous callback invocation.
function doDefaultForKey(key, callback) {
// Only take action if the key doesn't already have a value set.
if (typeof(prefsObj[key]) === 'undefined') {
if (that.defaults[key].hasOwnProperty('__defaultFromFile__')) {
Utils.getLocalFile(
that.defaults[key]['__defaultFromFile__'],
that.defaults[key]['__dataType__'] || 'text',
function(data) {
prefsObj[key] = data;
callback();
});
return;
}
else {
// Set the default.
prefsObj[key] = that.defaults[key];
// Recurse
callback();
return;
}
}
else {
// Key already has a value -- skip it.
callback();
return;
}
}
};
var EXPORTED_SYMBOLS = ['OptionsStore'];
this.EXPORTED_SYMBOLS = EXPORTED_SYMBOLS;
}).call(function() {
return this || (typeof window !== 'undefined' ? window : global);
}());