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