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