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