1 { unload } = require 'unload'
6 ADDON_ID = 'VimFx@akhodakivskiy.github.com'
8 { classes: Cc, interfaces: Ci, utils: Cu } = Components
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
22 _clip = Cc['@mozilla.org/widget/clipboard;1'].getService(Ci.nsIClipboard)
25 constructor: (@idFunc, @newFunc) ->
30 if container = @bucket[id]
33 return @bucket[id] = @newFunc(obj)
36 delete @bucket[id] if id = @idFunc(obj)
38 getEventWindow = (event) ->
39 if event.originalTarget instanceof Window
40 return event.originalTarget
42 doc = event.originalTarget.ownerDocument or event.originalTarget
43 if doc instanceof HTMLDocument or doc instanceof XULDocument
44 return doc.defaultView
46 getEventRootWindow = (event) ->
47 return unless window = getEventWindow(event)
48 return getRootWindow(window)
50 getEventCurrentTabWindow = (event) ->
51 return unless rootWindow = getEventRootWindow(event)
52 return getCurrentTabWindow(rootWindow)
54 getRootWindow = (window) ->
56 .QueryInterface(Ci.nsIInterfaceRequestor)
57 .getInterface(Ci.nsIWebNavigation)
58 .QueryInterface(Ci.nsIDocShellTreeItem)
60 .QueryInterface(Ci.nsIInterfaceRequestor)
63 getCurrentTabWindow = (window) ->
64 return window.gBrowser.selectedTab.linkedBrowser.contentWindow
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
70 { activeElement } = window.document
71 if isElementEditable(activeElement)
74 isTextInputElement = (element) ->
75 return element instanceof HTMLInputElement or \
76 element instanceof HTMLTextAreaElement
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'
89 getWindowId = (window) ->
91 .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
92 .getInterface(Components.interfaces.nsIDOMWindowUtils)
96 Cc['@mozilla.org/browser/sessionstore;1'].getService(Ci.nsISessionStore)
98 # Function that returns a URI to the css file that's part of the extension
101 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
102 uri = Services.io.newURI("resources/#{ name }.css", null, baseURI)
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
109 sss = Cc['@mozilla.org/content/style-sheet-service;1'].getService(Ci.nsIStyleSheetService)
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
115 if !sss.sheetRegistered(uri, sss.AGENT_SHEET)
116 sss.loadAndRegisterSheet(uri, sss.AGENT_SHEET)
119 sss.unregisterSheet(uri, sss.AGENT_SHEET)
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
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)
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
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) ->
144 .QueryInterface(Ci.nsIInterfaceRequestor)
145 .getInterface(Ci.nsIDOMWindowUtils)
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)
153 0, 0, # Line or Page deltas (x, y)
157 # Write a string into system clipboard
158 writeToClipboard = (window, text) ->
159 str = Cc['@mozilla.org/supports-string;1'].createInstance(Ci.nsISupportsString)
162 trans = Cc['@mozilla.org/widget/transferable;1'].createInstance(Ci.nsITransferable)
165 privacyContext = window
166 .QueryInterface(Ci.nsIInterfaceRequestor)
167 .getInterface(Ci.nsIWebNavigation)
168 .QueryInterface(Ci.nsILoadContext)
169 trans.init(privacyContext)
171 trans.addDataFlavor('text/unicode')
172 trans.setTransferData('text/unicode', str, text.length * 2)
174 _clip.setData(trans, null, Ci.nsIClipboard.kGlobalClipboard)
176 # Write a string into system clipboard
177 readFromClipboard = (window) ->
178 trans = Cc['@mozilla.org/widget/transferable;1'].createInstance(Ci.nsITransferable)
181 privacyContext = window
182 .QueryInterface(Ci.nsIInterfaceRequestor)
183 .getInterface(Ci.nsIWebNavigation)
184 .QueryInterface(Ci.nsILoadContext)
185 trans.init(privacyContext)
187 trans.addDataFlavor('text/unicode')
189 _clip.getData(trans, Ci.nsIClipboard.kGlobalClipboard)
194 trans.getTransferData('text/unicode', str, strLength)
197 str = str.value.QueryInterface(Ci.nsISupportsString)
198 return str.data.substring(0, strLength.value / 2)
202 # Executes function `func` and mearues how much time it took
203 timeIt = (func, msg) ->
204 start = new Date().getTime()
206 end = new Date().getTime()
208 console.log(msg, end - start)
211 isBlacklisted = (str) ->
212 matchingRules = getMatchingBlacklistRules(str)
213 return (matchingRules.length != 0)
215 # Returns all rules in the blacklist that match the provided string
216 getMatchingBlacklistRules = (str) ->
218 for rule in getBlacklist()
220 regexifiedRule = regexpEscape(rule).replace(/\\\*/g, '.*').replace(/!/g, '.')
221 if str.match(///^#{ regexifiedRule }$///)
222 matchingRules.push(rule)
227 return splitBlacklistString(getPref('black_list'))
229 setBlacklist = (blacklist) ->
230 setPref('black_list', blacklist.join(', '))
232 splitBlacklistString = (str) ->
233 # Comma/space separated list
234 return str.split(/[\s,]+/)
236 updateBlacklist = ({ add, remove} = {}) ->
237 blacklist = getBlacklist()
240 blacklist.push(splitBlacklistString(add)...)
242 blacklist = blacklist.filter((rule) -> rule != '')
243 blacklist = removeDuplicates(blacklist)
246 for rule in splitBlacklistString(remove) when rule in blacklist
247 blacklist.splice(blacklist.indexOf(rule), 1)
249 setBlacklist(blacklist)
251 # Gets VimFx verions. AddonManager only provides async API to access addon data, so it's a bit tricky...
257 Cu.import('resource://gre/modules/AddonManager.jsm', scope)
258 scope.AddonManager.getAddonByID(ADDON_ID, (addon) -> version = addon.version)
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)
268 createElement = (document, type, attributes = {}) ->
269 element = document.createElement(type)
271 for attribute, value of attributes
272 element.setAttribute(attribute, value)
274 if document instanceof HTMLDocument
275 element.classList.add('VimFxReset')
279 # Uses nsIIOService to parse a string as a URL and find out if it is a URL
282 url = Cc['@mozilla.org/network/io-service;1']
283 .getService(Ci.nsIIOService)
284 .newURI(str, null, null)
285 .QueryInterface(Ci.nsIURL)
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)
295 engine = ss.currentEngine or ss.defaultEngine
296 return engine.getSubmission(str, null)
298 # Get hint characters, convert them to lower case, and filter duplicates
300 hintChars = getPref('hint_chars')
301 # Make sure that hint chars contain at least two characters
302 if hintChars.length < 2
305 return removeDuplicateCharacters(hintChars)
307 # Remove duplicate characters from string (case insensitive)
308 removeDuplicateCharacters = (str) ->
309 return removeDuplicates( str.toLowerCase().split('') ).join('')
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)
316 # Escape string to render it usable in regular expressions
317 regexpEscape = (s) -> s and s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
319 removeDuplicates = (array) ->
321 return array.filter((item) -> if seen[item] then false else (seen[item] = true))
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(' | ')
329 namespaceResolver = (namespace) ->
330 if namespace == 'xhtml' then 'http://www.w3.org/1999/xhtml' else null
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)
336 exports.Bucket = Bucket
337 exports.getEventWindow = getEventWindow
338 exports.getEventRootWindow = getEventRootWindow
339 exports.getEventCurrentTabWindow = getEventCurrentTabWindow
340 exports.getRootWindow = getRootWindow
341 exports.getCurrentTabWindow = getCurrentTabWindow
343 exports.getWindowId = getWindowId
344 exports.blurActiveElement = blurActiveElement
345 exports.isTextInputElement = isTextInputElement
346 exports.isElementEditable = isElementEditable
347 exports.getSessionStore = getSessionStore
349 exports.loadCss = loadCss
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
360 exports.getMatchingBlacklistRules = getMatchingBlacklistRules
361 exports.isBlacklisted = isBlacklisted
362 exports.updateBlacklist = updateBlacklist
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