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