]> git.gir.st - VimFx.git/blob - extension/packages/utils.coffee
Prevent autofocus by blurring the input if it's been focused in the first second...
[VimFx.git] / extension / packages / utils.coffee
1 { unload } = require 'unload'
2 { getPref
3 , setPref
4 } = require 'prefs'
5
6 ADDON_ID = 'VimFx@akhodakivskiy.github.com'
7
8 { classes: Cc, interfaces: Ci, utils: Cu } = Components
9
10 HTMLInputElement = Ci.nsIDOMHTMLInputElement
11 HTMLTextAreaElement = Ci.nsIDOMHTMLTextAreaElement
12 HTMLSelectElement = Ci.nsIDOMHTMLSelectElement
13 XULMenuListElement = Ci.nsIDOMXULMenuListElement
14 XULDocument = Ci.nsIDOMXULDocument
15 XULElement = Ci.nsIDOMXULElement
16 XPathResult = Ci.nsIDOMXPathResult
17 HTMLDocument = Ci.nsIDOMHTMLDocument
18 HTMLElement = Ci.nsIDOMHTMLElement
19 Window = Ci.nsIDOMWindow
20 ChromeWindow = Ci.nsIDOMChromeWindow
21
22 _clip = Cc['@mozilla.org/widget/clipboard;1'].getService(Ci.nsIClipboard)
23
24 class Bucket
25 constructor: (@idFunc, @newFunc) ->
26 @bucket = {}
27
28 get: (obj) ->
29 id = @idFunc(obj)
30 if container = @bucket[id]
31 return container
32 else
33 return @bucket[id] = @newFunc(obj)
34
35 forget: (obj) ->
36 delete @bucket[id] if id = @idFunc(obj)
37
38 getEventWindow = (event) ->
39 if event.originalTarget instanceof Window
40 return event.originalTarget
41 else
42 doc = event.originalTarget.ownerDocument or event.originalTarget
43 if doc instanceof HTMLDocument or doc instanceof XULDocument
44 return doc.defaultView
45
46 getEventRootWindow = (event) ->
47 return unless window = getEventWindow(event)
48 return getRootWindow(window)
49
50 getEventCurrentTabWindow = (event) ->
51 return unless rootWindow = getEventRootWindow(event)
52 return getCurrentTabWindow(rootWindow)
53
54 getRootWindow = (window) ->
55 return window
56 .QueryInterface(Ci.nsIInterfaceRequestor)
57 .getInterface(Ci.nsIWebNavigation)
58 .QueryInterface(Ci.nsIDocShellTreeItem)
59 .rootTreeItem
60 .QueryInterface(Ci.nsIInterfaceRequestor)
61 .getInterface(Window)
62
63 getCurrentTabWindow = (window) ->
64 return window.gBrowser.selectedTab.linkedBrowser.contentWindow
65
66 blurActiveElement = (window) ->
67 # Only blur editable elements, in order not to interfere with the browser too much. TODO: Is that
68 # really needed? What if a website has made more elements focusable -- shouldn't those also be
69 # blurred?
70 { activeElement } = window.document
71 if isElementEditable(activeElement)
72 activeElement.blur()
73
74 isTextInputElement = (element) ->
75 return element instanceof HTMLInputElement or \
76 element instanceof HTMLTextAreaElement
77
78 isElementEditable = (element) ->
79 return element.isContentEditable or \
80 element instanceof HTMLInputElement or \
81 element instanceof HTMLTextAreaElement or \
82 element instanceof HTMLSelectElement or \
83 element instanceof XULMenuListElement or \
84 element.ownerDocument?.designMode?.toLowerCase() == 'on' or \
85 element.getAttribute?('g_editable') == 'true' or \
86 element.getAttribute?('contenteditable')?.toLowerCase() == 'true' or \
87 element.ownerDocument?.designMode?.toLowerCase() == 'on'
88
89 getWindowId = (window) ->
90 return window
91 .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
92 .getInterface(Components.interfaces.nsIDOMWindowUtils)
93 .outerWindowID
94
95 getSessionStore = ->
96 Cc['@mozilla.org/browser/sessionstore;1'].getService(Ci.nsISessionStore)
97
98 # Function that returns a URI to the css file that's part of the extension
99 cssUri = do ->
100 (name) ->
101 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
102 uri = Services.io.newURI("resources/#{ name }.css", null, baseURI)
103 return uri
104
105 # Loads the css identified by the name in the StyleSheetService as User Stylesheet
106 # The stylesheet is then appended to every document, but it can be overwritten by
107 # any user css
108 loadCss = do ->
109 sss = Cc['@mozilla.org/content/style-sheet-service;1'].getService(Ci.nsIStyleSheetService)
110 return (name) ->
111 uri = cssUri(name)
112 # `AGENT_SHEET` is used to override userContent.css and Stylish. Custom website themes installed
113 # by users often make the hint markers unreadable, for example. Just using `!important` in the
114 # CSS is not enough.
115 if !sss.sheetRegistered(uri, sss.AGENT_SHEET)
116 sss.loadAndRegisterSheet(uri, sss.AGENT_SHEET)
117
118 unload ->
119 sss.unregisterSheet(uri, sss.AGENT_SHEET)
120
121 # Simulate mouse click with full chain of event
122 # Copied from Vimium codebase
123 simulateClick = (element, modifiers = {}) ->
124 document = element.ownerDocument
125 window = document.defaultView
126
127 eventSequence = ['mouseover', 'mousedown', 'mouseup', 'click']
128 for event in eventSequence
129 mouseEvent = document.createEvent('MouseEvents')
130 mouseEvent.initMouseEvent(event, true, true, window, 1, 0, 0, 0, 0, modifiers.ctrlKey, false, false,
131 modifiers.metaKey, 0, null)
132 # Debugging note: Firefox will not execute the element's default action if we dispatch this click event,
133 # but Webkit will. Dispatching a click on an input box does not seem to focus it; we do that separately
134 element.dispatchEvent(mouseEvent)
135
136 WHEEL_MODE_PIXEL = Ci.nsIDOMWheelEvent.DOM_DELTA_PIXEL
137 WHEEL_MODE_LINE = Ci.nsIDOMWheelEvent.DOM_DELTA_LINE
138 WHEEL_MODE_PAGE = Ci.nsIDOMWheelEvent.DOM_DELTA_PAGE
139
140 # Simulate mouse scroll event by specific offsets given
141 # that mouse cursor is at specified position
142 simulateWheel = (window, deltaX, deltaY, mode = WHEEL_MODE_PIXEL) ->
143 windowUtils = window
144 .QueryInterface(Ci.nsIInterfaceRequestor)
145 .getInterface(Ci.nsIDOMWindowUtils)
146
147 [pX, pY] = [window.innerWidth / 2, window.innerHeight / 2]
148 windowUtils.sendWheelEvent(
149 pX, pY, # Window offset (x, y) in pixels
150 deltaX, deltaY, 0, # Deltas (x, y, z)
151 mode, # Mode (pixel, line, page)
152 0, # Key Modifiers
153 0, 0, # Line or Page deltas (x, y)
154 0 # Options
155 )
156
157 # Write a string into system clipboard
158 writeToClipboard = (window, text) ->
159 str = Cc['@mozilla.org/supports-string;1'].createInstance(Ci.nsISupportsString)
160 str.data = text
161
162 trans = Cc['@mozilla.org/widget/transferable;1'].createInstance(Ci.nsITransferable)
163
164 if trans.init
165 privacyContext = window
166 .QueryInterface(Ci.nsIInterfaceRequestor)
167 .getInterface(Ci.nsIWebNavigation)
168 .QueryInterface(Ci.nsILoadContext)
169 trans.init(privacyContext)
170
171 trans.addDataFlavor('text/unicode')
172 trans.setTransferData('text/unicode', str, text.length * 2)
173
174 _clip.setData(trans, null, Ci.nsIClipboard.kGlobalClipboard)
175
176 # Write a string into system clipboard
177 readFromClipboard = (window) ->
178 trans = Cc['@mozilla.org/widget/transferable;1'].createInstance(Ci.nsITransferable)
179
180 if trans.init
181 privacyContext = window
182 .QueryInterface(Ci.nsIInterfaceRequestor)
183 .getInterface(Ci.nsIWebNavigation)
184 .QueryInterface(Ci.nsILoadContext)
185 trans.init(privacyContext)
186
187 trans.addDataFlavor('text/unicode')
188
189 _clip.getData(trans, Ci.nsIClipboard.kGlobalClipboard)
190
191 str = {}
192 strLength = {}
193
194 trans.getTransferData('text/unicode', str, strLength)
195
196 if str
197 str = str.value.QueryInterface(Ci.nsISupportsString)
198 return str.data.substring(0, strLength.value / 2)
199
200 return undefined
201
202 # Executes function `func` and mearues how much time it took
203 timeIt = (func, msg) ->
204 start = new Date().getTime()
205 result = func()
206 end = new Date().getTime()
207
208 console.log(msg, end - start)
209 return result
210
211 isBlacklisted = (str) ->
212 matchingRules = getMatchingBlacklistRules(str)
213 return (matchingRules.length != 0)
214
215 # Returns all rules in the blacklist that match the provided string
216 getMatchingBlacklistRules = (str) ->
217 matchingRules = []
218 for rule in getBlacklist()
219 # Wildcards: * and !
220 regexifiedRule = regexpEscape(rule).replace(/\\\*/g, '.*').replace(/!/g, '.')
221 if str.match(///^#{ regexifiedRule }$///)
222 matchingRules.push(rule)
223
224 return matchingRules
225
226 getBlacklist = ->
227 return splitBlacklistString(getPref('black_list'))
228
229 setBlacklist = (blacklist) ->
230 setPref('black_list', blacklist.join(', '))
231
232 splitBlacklistString = (str) ->
233 # Comma/space separated list
234 return str.split(/[\s,]+/)
235
236 updateBlacklist = ({ add, remove} = {}) ->
237 blacklist = getBlacklist()
238
239 if add
240 blacklist.push(splitBlacklistString(add)...)
241
242 blacklist = blacklist.filter((rule) -> rule != '')
243 blacklist = removeDuplicates(blacklist)
244
245 if remove
246 for rule in splitBlacklistString(remove) when rule in blacklist
247 blacklist.splice(blacklist.indexOf(rule), 1)
248
249 setBlacklist(blacklist)
250
251 # Gets VimFx verions. AddonManager only provides async API to access addon data, so it's a bit tricky...
252 getVersion = do ->
253 version = null
254
255 if version == null
256 scope = {}
257 Cu.import('resource://gre/modules/AddonManager.jsm', scope)
258 scope.AddonManager.getAddonByID(ADDON_ID, (addon) -> version = addon.version)
259
260 return ->
261 return version
262
263 parseHTML = (document, html) ->
264 parser = Cc['@mozilla.org/parserutils;1'].getService(Ci.nsIParserUtils)
265 flags = parser.SanitizerAllowStyle
266 return parser.parseFragment(html, flags, false, null, document.documentElement)
267
268 createElement = (document, type, attributes = {}) ->
269 element = document.createElement(type)
270
271 for attribute, value of attributes
272 element.setAttribute(attribute, value)
273
274 if document instanceof HTMLDocument
275 element.classList.add('VimFxReset')
276
277 return element
278
279 # Uses nsIIOService to parse a string as a URL and find out if it is a URL
280 isURL = (str) ->
281 try
282 url = Cc['@mozilla.org/network/io-service;1']
283 .getService(Ci.nsIIOService)
284 .newURI(str, null, null)
285 .QueryInterface(Ci.nsIURL)
286 return true
287 catch err
288 return false
289
290 # Use Firefox services to search for a given string
291 browserSearchSubmission = (str) ->
292 ss = Cc['@mozilla.org/browser/search-service;1']
293 .getService(Ci.nsIBrowserSearchService)
294
295 engine = ss.currentEngine or ss.defaultEngine
296 return engine.getSubmission(str, null)
297
298 # Get hint characters, convert them to lower case, and filter duplicates
299 getHintChars = ->
300 hintChars = getPref('hint_chars')
301 # Make sure that hint chars contain at least two characters
302 if hintChars.length < 2
303 hintChars = 'fj'
304
305 return removeDuplicateCharacters(hintChars)
306
307 # Remove duplicate characters from string (case insensitive)
308 removeDuplicateCharacters = (str) ->
309 return removeDuplicates( str.toLowerCase().split('') ).join('')
310
311 # Return URI to some file in the extension packaged as resource
312 getResourceURI = do ->
313 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
314 return (path) -> return Services.io.newURI(path, null, baseURI)
315
316 # Escape string to render it usable in regular expressions
317 regexpEscape = (s) -> s and s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
318
319 removeDuplicates = (array) ->
320 seen = {}
321 return array.filter((item) -> if seen[item] then false else (seen[item] = true))
322
323 # Returns elements that qualify as links
324 # Generates and memoizes an XPath query internally
325 getDomElements = (elements) ->
326 reduce = (m, rule) -> m.concat(["//#{ rule }", "//xhtml:#{ rule }"])
327 xpath = elements.reduce(reduce, []).join(' | ')
328
329 namespaceResolver = (namespace) ->
330 if namespace == 'xhtml' then 'http://www.w3.org/1999/xhtml' else null
331
332 # The actual function that will return the desired elements
333 return (document, resultType = XPathResult.ORDERED_NODE_SNAPSHOT_TYPE) ->
334 return document.evaluate(xpath, document.documentElement, namespaceResolver, resultType, null)
335
336 exports.Bucket = Bucket
337 exports.getEventWindow = getEventWindow
338 exports.getEventRootWindow = getEventRootWindow
339 exports.getEventCurrentTabWindow = getEventCurrentTabWindow
340 exports.getRootWindow = getRootWindow
341 exports.getCurrentTabWindow = getCurrentTabWindow
342
343 exports.getWindowId = getWindowId
344 exports.blurActiveElement = blurActiveElement
345 exports.isTextInputElement = isTextInputElement
346 exports.isElementEditable = isElementEditable
347 exports.getSessionStore = getSessionStore
348
349 exports.loadCss = loadCss
350
351 exports.simulateClick = simulateClick
352 exports.simulateWheel = simulateWheel
353 exports.WHEEL_MODE_PIXEL = WHEEL_MODE_PIXEL
354 exports.WHEEL_MODE_LINE = WHEEL_MODE_LINE
355 exports.WHEEL_MODE_PAGE = WHEEL_MODE_PAGE
356 exports.readFromClipboard = readFromClipboard
357 exports.writeToClipboard = writeToClipboard
358 exports.timeIt = timeIt
359
360 exports.getMatchingBlacklistRules = getMatchingBlacklistRules
361 exports.isBlacklisted = isBlacklisted
362 exports.updateBlacklist = updateBlacklist
363
364 exports.getVersion = getVersion
365 exports.parseHTML = parseHTML
366 exports.createElement = createElement
367 exports.isURL = isURL
368 exports.browserSearchSubmission = browserSearchSubmission
369 exports.getHintChars = getHintChars
370 exports.removeDuplicateCharacters = removeDuplicateCharacters
371 exports.getResourceURI = getResourceURI
372 exports.getDomElements = getDomElements
373 exports.ADDON_ID = ADDON_ID
Imprint / Impressum