]> git.gir.st - VimFx.git/blob - extension/packages/utils.coffee
Add live validation of the hint chars setting
[VimFx.git] / extension / packages / utils.coffee
1 { unload } = require 'unload'
2 { getPref
3 , getDefaultPref
4 } = require 'prefs'
5
6 { classes: Cc, interfaces: Ci, utils: Cu } = Components
7
8 HTMLInputElement = Ci.nsIDOMHTMLInputElement
9 HTMLTextAreaElement = Ci.nsIDOMHTMLTextAreaElement
10 HTMLSelectElement = Ci.nsIDOMHTMLSelectElement
11 XULDocument = Ci.nsIDOMXULDocument
12 XULElement = Ci.nsIDOMXULElement
13 HTMLDocument = Ci.nsIDOMHTMLDocument
14 HTMLElement = Ci.nsIDOMHTMLElement
15 Window = Ci.nsIDOMWindow
16 ChromeWindow = Ci.nsIDOMChromeWindow
17
18 _clip = Cc['@mozilla.org/widget/clipboard;1'].getService(Ci.nsIClipboard)
19
20 class Bucket
21 constructor: (@idFunc, @newFunc) ->
22 @bucket = {}
23
24 get: (obj) ->
25 id = @idFunc(obj)
26 if container = @bucket[id]
27 return container
28 else
29 return @bucket[id] = @newFunc(obj)
30
31 forget: (obj) ->
32 delete @bucket[id] if id = @idFunc(obj)
33
34 # Returns the `window` from the currently active tab.
35 getCurrentTabWindow = (event) ->
36 if window = getEventWindow(event)
37 if rootWindow = getRootWindow(window)
38 return rootWindow.gBrowser.selectedTab.linkedBrowser.contentWindow
39
40 # Returns the window associated with the event
41 getEventWindow = (event) ->
42 if event.originalTarget instanceof Window
43 return event.originalTarget
44 else
45 doc = event.originalTarget.ownerDocument or event.originalTarget
46 if doc instanceof HTMLDocument or doc instanceof XULDocument
47 return doc.defaultView
48
49 getEventRootWindow = (event) ->
50 if window = getEventWindow(event)
51 return getRootWindow(window)
52
53 getEventTabBrowser = (event) ->
54 cw.gBrowser if cw = getEventRootWindow(event)
55
56 getRootWindow = (window) ->
57 return window.QueryInterface(Ci.nsIInterfaceRequestor)
58 .getInterface(Ci.nsIWebNavigation)
59 .QueryInterface(Ci.nsIDocShellTreeItem)
60 .rootTreeItem
61 .QueryInterface(Ci.nsIInterfaceRequestor)
62 .getInterface(Window)
63
64 isTextInputElement = (element) ->
65 return element instanceof HTMLInputElement or \
66 element instanceof HTMLTextAreaElement
67
68 isElementEditable = (element) ->
69 return element.isContentEditable or \
70 element instanceof HTMLInputElement or \
71 element instanceof HTMLTextAreaElement or \
72 element instanceof HTMLSelectElement or \
73 element.getAttribute('g_editable') == 'true' or \
74 element.getAttribute('contenteditable')?.toLowerCase() == 'true' or \
75 element.ownerDocument?.designMode?.toLowerCase() == 'on'
76
77 getWindowId = (window) ->
78 return window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
79 .getInterface(Components.interfaces.nsIDOMWindowUtils)
80 .outerWindowID
81
82 getSessionStore = ->
83 Cc['@mozilla.org/browser/sessionstore;1'].getService(Ci.nsISessionStore)
84
85 # Function that returns a URI to the css file that's part of the extension
86 cssUri = do ->
87 (name) ->
88 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
89 uri = Services.io.newURI("resources/#{ name }.css", null, baseURI)
90 return uri
91
92 # Loads the css identified by the name in the StyleSheetService as User Stylesheet
93 # The stylesheet is then appended to every document, but it can be overwritten by
94 # any user css
95 loadCss = do ->
96 sss = Cc['@mozilla.org/content/style-sheet-service;1'].getService(Ci.nsIStyleSheetService)
97 return (name) ->
98 uri = cssUri(name)
99 if !sss.sheetRegistered(uri, sss.AUTHOR_SHEET)
100 sss.loadAndRegisterSheet(uri, sss.AUTHOR_SHEET)
101
102 unload ->
103 sss.unregisterSheet(uri, sss.AUTHOR_SHEET)
104
105 # Simulate mouse click with full chain of event
106 # Copied from Vimium codebase
107 simulateClick = (element, modifiers) ->
108 document = element.ownerDocument
109 window = document.defaultView
110 modifiers ||= {}
111
112 eventSequence = ['mouseover', 'mousedown', 'mouseup', 'click']
113 for event in eventSequence
114 mouseEvent = document.createEvent('MouseEvents')
115 mouseEvent.initMouseEvent(event, true, true, window, 1, 0, 0, 0, 0, modifiers.ctrlKey, false, false,
116 modifiers.metaKey, 0, null)
117 # Debugging note: Firefox will not execute the element's default action if we dispatch this click event,
118 # but Webkit will. Dispatching a click on an input box does not seem to focus it; we do that separately
119 element.dispatchEvent(mouseEvent)
120
121 WHEEL_MODE_PIXEL = Ci.nsIDOMWheelEvent.DOM_DELTA_PIXEL
122 WHEEL_MODE_LINE = Ci.nsIDOMWheelEvent.DOM_DELTA_LINE
123 WHEEL_MODE_PAGE = Ci.nsIDOMWheelEvent.DOM_DELTA_PAGE
124
125 # Simulate mouse scroll event by specific offsets given
126 # that mouse cursor is at specified position
127 simulateWheel = (window, deltaX, deltaY, mode = WHEEL_MODE_PIXEL) ->
128 windowUtils = window.QueryInterface(Ci.nsIInterfaceRequestor)
129 .getInterface(Ci.nsIDOMWindowUtils)
130
131 [pX, pY] = [window.innerWidth / 2, window.innerHeight / 2]
132 windowUtils.sendWheelEvent(
133 pX, pY, # Window offset (x, y) in pixels
134 deltaX, deltaY, 0, # Deltas (x, y, z)
135 mode, # Mode (pixel, line, page)
136 0, # Key Modifiers
137 0, 0, # Line or Page deltas (x, y)
138 0 # Options
139 )
140
141 # Write a string into system clipboard
142 writeToClipboard = (window, text) ->
143 str = Cc['@mozilla.org/supports-string;1'].createInstance(Ci.nsISupportsString)
144 str.data = text
145
146 trans = Cc['@mozilla.org/widget/transferable;1'].createInstance(Ci.nsITransferable)
147
148 if trans.init
149 privacyContext = window.QueryInterface(Ci.nsIInterfaceRequestor)
150 .getInterface(Ci.nsIWebNavigation)
151 .QueryInterface(Ci.nsILoadContext)
152 trans.init(privacyContext)
153
154 trans.addDataFlavor('text/unicode')
155 trans.setTransferData('text/unicode', str, text.length * 2)
156
157 _clip.setData(trans, null, Ci.nsIClipboard.kGlobalClipboard)
158
159 # Write a string into system clipboard
160 readFromClipboard = (window) ->
161 trans = Cc['@mozilla.org/widget/transferable;1'].createInstance(Ci.nsITransferable)
162
163 if trans.init
164 privacyContext = window.QueryInterface(Ci.nsIInterfaceRequestor)
165 .getInterface(Ci.nsIWebNavigation)
166 .QueryInterface(Ci.nsILoadContext)
167 trans.init(privacyContext)
168
169 trans.addDataFlavor('text/unicode')
170
171 _clip.getData(trans, Ci.nsIClipboard.kGlobalClipboard)
172
173 str = {}
174 strLength = {}
175
176 trans.getTransferData('text/unicode', str, strLength)
177
178 if str
179 str = str.value.QueryInterface(Ci.nsISupportsString)
180 return str.data.substring(0, strLength.value / 2)
181
182 return undefined
183
184 # Executes function `func` and mearues how much time it took
185 timeIt = (func, msg) ->
186 start = new Date().getTime()
187 result = func()
188 end = new Date().getTime()
189
190 console.log(msg, end - start)
191 return result
192
193 # Checks if the string provided matches one of the black list entries
194 # `blackList`: comma/space separated list of URLs with wildcards (* and !)
195 isBlacklisted = (str, blackList) ->
196 for rule in blackList.split(/[\s,]+/)
197 rule = rule.replace(/\*/g, '.*').replace(/\!/g, '.')
198 if str.match ///^#{ rule }$///
199 return true
200
201 return false
202
203 # Gets VimFx verions. AddonManager only provides async API to access addon data, so it's a bit tricky...
204 getVersion = do ->
205 version = null
206
207 if version == null
208 scope = {}
209 addonId = getPref('addon_id')
210 Cu.import('resource://gre/modules/AddonManager.jsm', scope)
211 scope.AddonManager.getAddonByID(addonId, (addon) -> version = addon.version)
212
213 return ->
214 return version
215
216 parseHTML = (document, html) ->
217 parser = Cc['@mozilla.org/parserutils;1'].getService(Ci.nsIParserUtils)
218 flags = parser.SanitizerAllowStyle
219 return parser.parseFragment(html, flags, false, null, document.documentElement)
220
221 # Uses nsIIOService to parse a string as a URL and find out if it is a URL
222 isURL = (str) ->
223 try
224 url = Cc['@mozilla.org/network/io-service;1']
225 .getService(Ci.nsIIOService)
226 .newURI(str, null, null)
227 .QueryInterface(Ci.nsIURL)
228 return true
229 catch err
230 return false
231
232 # Use Firefox services to search for a given string
233 browserSearchSubmission = (str) ->
234 ss = Cc['@mozilla.org/browser/search-service;1']
235 .getService(Ci.nsIBrowserSearchService)
236
237 engine = ss.currentEngine or ss.defaultEngine
238 return engine.getSubmission(str, null)
239
240 # Get hint characters, convert them to lower case and fall back
241 # to default hint characters if there are less than 3 chars
242 getHintChars = ->
243 hintChars = removeDuplicateCharacters(getPref('hint_chars'))
244 if hintChars.length < 2
245 hintChars = getDefaultPref('hint_chars')
246
247 return hintChars
248
249 # Remove duplicate characters from string (case insensitive)
250 removeDuplicateCharacters = (str) ->
251 seen = {}
252 return str
253 .toLowerCase()
254 .split('')
255 .filter((char) -> if seen[char] then false else (seen[char] = true))
256 .join('')
257
258 # Return URI to some file in the extension packaged as resource
259 getResourceURI = do ->
260 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
261 return (path) -> Services.io.newURI(path, null, baseURI)
262
263 # Escape string to render it usable in regular expressions
264 regexpEscape = (s) -> s and s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
265
266 exports.Bucket = Bucket
267 exports.getCurrentTabWindow = getCurrentTabWindow
268 exports.getEventWindow = getEventWindow
269 exports.getEventRootWindow = getEventRootWindow
270 exports.getEventTabBrowser = getEventTabBrowser
271
272 exports.getWindowId = getWindowId
273 exports.getRootWindow = getRootWindow
274 exports.isTextInputElement = isTextInputElement
275 exports.isElementEditable = isElementEditable
276 exports.getSessionStore = getSessionStore
277
278 exports.loadCss = loadCss
279
280 exports.simulateClick = simulateClick
281 exports.simulateWheel = simulateWheel
282 exports.WHEEL_MODE_PIXEL = WHEEL_MODE_PIXEL
283 exports.WHEEL_MODE_LINE = WHEEL_MODE_LINE
284 exports.WHEEL_MODE_PAGE = WHEEL_MODE_PAGE
285 exports.readFromClipboard = readFromClipboard
286 exports.writeToClipboard = writeToClipboard
287 exports.timeIt = timeIt
288 exports.isBlacklisted = isBlacklisted
289 exports.getVersion = getVersion
290 exports.parseHTML = parseHTML
291 exports.isURL = isURL
292 exports.browserSearchSubmission = browserSearchSubmission
293 exports.getHintChars = getHintChars
294 exports.removeDuplicateCharacters = removeDuplicateCharacters
295 exports.getResourceURI = getResourceURI
296 exports.regexpEscape = regexpEscape
Imprint / Impressum