]> git.gir.st - VimFx.git/blob - extension/lib/prefs.coffee
support for nsPrefBranch::{get,set}StringPref() (#901)
[VimFx.git] / extension / lib / prefs.coffee
1 # This file provides an API a bit more easy to use than the very low-level
2 # Firefox prefs APIs.
3
4 defaults = require('./defaults')
5
6 {prefs} = Services
7
8 branches = {
9 addon: {
10 user: prefs.getBranch(defaults.BRANCH)
11 default: prefs.getDefaultBranch(defaults.BRANCH)
12 }
13 root: {
14 user: prefs
15 default: prefs.getDefaultBranch('')
16 }
17 }
18
19 get = (branch, key) ->
20 return switch branch.getPrefType(key)
21 when branch.PREF_BOOL
22 branch.getBoolPref(key)
23 when branch.PREF_INT
24 branch.getIntPref(key)
25 when branch.PREF_STRING
26 if branch.getStringPref
27 branch.getStringPref(key)
28 else
29 branch.getComplexValue(key, Ci.nsISupportsString).data
30
31 set = (branch, key, value) ->
32 switch typeof value
33 when 'boolean'
34 branch.setBoolPref(key, value)
35 when 'number'
36 branch.setIntPref(key, value) # `value` will be `Math.floor`ed.
37 when 'string'
38 if branch.setStringPref
39 branch.setStringPref(key, value)
40 else
41 str = Cc['@mozilla.org/supports-string;1']
42 .createInstance(Ci.nsISupportsString)
43 str.data = value
44 branch.setComplexValue(key, Ci.nsISupportsString, str)
45 else
46 if value == null
47 branch.clearUserPref(key)
48 else
49 throw new Error(
50 "VimFx: Options may only be set to a boolean, number, string or null.
51 Got: #{typeof value}"
52 )
53
54 has = (branch, key) ->
55 branch.prefHasUserValue(key)
56
57 tmp = (branch, pref, temporaryValue) ->
58 previousValue = if has(branch, pref) then get(branch, pref) else null
59 set(branch, pref, temporaryValue)
60 return -> set(branch, pref, previousValue)
61
62 observe = (branch, domain, callback) ->
63 observer = {observe: (branch, topic, changedPref) -> callback(changedPref)}
64 branch.addObserver(domain, observer, false)
65 module.onShutdown(->
66 branch.removeObserver(domain, observer)
67 )
68
69 module.exports = {
70 get: get.bind(null, branches.addon.user)
71 set: set.bind(null, branches.addon.user)
72 has: has.bind(null, branches.addon.user)
73 tmp: tmp.bind(null, branches.addon.user)
74 observe: observe.bind(null, branches.addon.user)
75 default: {
76 get: get.bind(null, branches.addon.default)
77 set: set.bind(null, branches.addon.default)
78 init: ->
79 for key, value of defaults.all_prefs
80 module.exports.default.set(key, value)
81 return
82 }
83 root: {
84 get: get.bind(null, branches.root.user)
85 set: set.bind(null, branches.root.user)
86 has: has.bind(null, branches.root.user)
87 tmp: tmp.bind(null, branches.root.user)
88 observe: observe.bind(null, branches.root.user)
89 default: {
90 get: get.bind(null, branches.root.default)
91 set: set.bind(null, branches.root.default)
92 }
93 }
94 unbound: {get, set, has, tmp, observe}
95 }
Imprint / Impressum