]> git.gir.st - VimFx.git/blob - extension/lib/prefs.coffee
Change license to MIT
[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 branch.getComplexValue(key, Ci.nsISupportsString).data
27
28 set = (branch, key, value) ->
29 switch typeof value
30 when 'boolean'
31 branch.setBoolPref(key, value)
32 when 'number'
33 branch.setIntPref(key, value) # `value` will be `Math.floor`ed.
34 when 'string'
35 str = Cc['@mozilla.org/supports-string;1']
36 .createInstance(Ci.nsISupportsString)
37 str.data = value
38 branch.setComplexValue(key, Ci.nsISupportsString, str)
39 else
40 if value == null
41 branch.clearUserPref(key)
42 else
43 throw new Error(
44 "VimFx: Options may only be set to a boolean, number, string or null.
45 Got: #{typeof value}"
46 )
47
48 has = (branch, key) ->
49 branch.prefHasUserValue(key)
50
51 tmp = (branch, pref, temporaryValue) ->
52 previousValue = if has(branch, pref) then get(branch, pref) else null
53 set(branch, pref, temporaryValue)
54 return -> set(branch, pref, previousValue)
55
56 observe = (branch, domain, callback) ->
57 observer = {observe: (branch, topic, changedPref) -> callback(changedPref)}
58 branch.addObserver(domain, observer, false)
59 module.onShutdown(->
60 branch.removeObserver(domain, observer)
61 )
62
63 module.exports = {
64 get: get.bind(null, branches.addon.user)
65 set: set.bind(null, branches.addon.user)
66 has: has.bind(null, branches.addon.user)
67 tmp: tmp.bind(null, branches.addon.user)
68 observe: observe.bind(null, branches.addon.user)
69 default: {
70 get: get.bind(null, branches.addon.default)
71 set: set.bind(null, branches.addon.default)
72 init: ->
73 for key, value of defaults.all_prefs
74 module.exports.default.set(key, value)
75 return
76 }
77 root: {
78 get: get.bind(null, branches.root.user)
79 set: set.bind(null, branches.root.user)
80 has: has.bind(null, branches.root.user)
81 tmp: tmp.bind(null, branches.root.user)
82 observe: observe.bind(null, branches.root.user)
83 default: {
84 get: get.bind(null, branches.root.default)
85 set: set.bind(null, branches.root.default)
86 }
87 }
88 unbound: {get, set, has, tmp, observe}
89 }
Imprint / Impressum