]> git.gir.st - VimFx.git/blob - extension/packages/utils.coffee
Merge branch 'find' into develop
[VimFx.git] / extension / packages / utils.coffee
1 { interfaces: Ci, classes: Cc, utils: Cu } = Components
2
3 HTMLInputElement = Ci.nsIDOMHTMLInputElement
4 HTMLTextAreaElement = Ci.nsIDOMHTMLTextAreaElement
5 HTMLSelectElement = Ci.nsIDOMHTMLSelectElement
6 XULDocument = Ci.nsIDOMXULDocument
7 XULElement = Ci.nsIDOMXULElement
8 HTMLDocument = Ci.nsIDOMHTMLDocument
9 HTMLElement = Ci.nsIDOMHTMLElement
10 Window = Ci.nsIDOMWindow
11 ChromeWindow = Ci.nsIDOMChromeWindow
12
13 _sss = Cc["@mozilla.org/content/style-sheet-service;1"].getService(Ci.nsIStyleSheetService)
14 _clip = Cc["@mozilla.org/widget/clipboard;1"].getService(Ci.nsIClipboard)
15
16 { getPref } = require 'prefs'
17
18 class Bucket
19 constructor: (@idFunc, @newFunc) ->
20 @bucket = {}
21
22 get: (obj) ->
23 id = @idFunc obj
24 if container = @bucket[id]
25 return container
26 else
27 return @bucket[id] = @newFunc obj
28
29 forget: (obj) ->
30 delete @bucket[id] if id = @idFunc obj
31
32 # Returns the `window` from the currently active tab.
33 getCurrentTabWindow = (event) ->
34 if window = getEventWindow event
35 if rootWindow = getRootWindow window
36 return rootWindow.gBrowser.selectedTab.linkedBrowser.contentWindow
37
38 # Returns the window associated with the event
39 getEventWindow = (event) ->
40 if event.originalTarget instanceof Window
41 return event.originalTarget
42 else
43 doc = event.originalTarget.ownerDocument or event.originalTarget
44 if doc instanceof HTMLDocument or doc instanceof XULDocument
45 return doc.defaultView
46
47 getEventRootWindow = (event) ->
48 if window = getEventWindow event
49 return getRootWindow window
50
51 getEventTabBrowser = (event) ->
52 cw.gBrowser if cw = getEventRootWindow event
53
54 getRootWindow = (window) ->
55 return window.QueryInterface(Ci.nsIInterfaceRequestor)
56 .getInterface(Ci.nsIWebNavigation)
57 .QueryInterface(Ci.nsIDocShellTreeItem)
58 .rootTreeItem
59 .QueryInterface(Ci.nsIInterfaceRequestor)
60 .getInterface(Window);
61
62 isElementEditable = (element) ->
63 return element.isContentEditable or \
64 element instanceof HTMLInputElement or \
65 element instanceof HTMLTextAreaElement or \
66 element instanceof HTMLSelectElement or \
67 element.getAttribute('g_editable') == 'true' or \
68 element.getAttribute('contenteditable')?.toLowerCase() == 'true' or \
69 element.ownerDocument?.designMode?.toLowerCase() == 'on'
70
71 getWindowId = (window) ->
72 return window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
73 .getInterface(Components.interfaces.nsIDOMWindowUtils)
74 .outerWindowID
75
76 getSessionStore = ->
77 Cc["@mozilla.org/browser/sessionstore;1"].getService(Ci.nsISessionStore);
78
79 # Function that returns a URI to the css file that's part of the extension
80 cssUri = do () ->
81 (name) ->
82 baseURI = Services.io.newURI __SCRIPT_URI_SPEC__, null, null
83 uri = Services.io.newURI "resources/#{ name }.css", null, baseURI
84 return uri
85
86 # Loads the css identified by the name in the StyleSheetService as User Stylesheet
87 # The stylesheet is then appended to every document, but it can be overwritten by
88 # any user css
89 loadCss = (name) ->
90 uri = cssUri(name)
91 if !_sss.sheetRegistered(uri, _sss.AGENT_SHEET)
92 _sss.loadAndRegisterSheet(uri, _sss.AGENT_SHEET)
93
94 unload ->
95 _sss.unregisterSheet(uri, _sss.AGENT_SHEET)
96
97 # Simulate mouse click with full chain of event
98 # Copied from Vimium codebase
99 simulateClick = (element, modifiers) ->
100 document = element.ownerDocument
101 window = document.defaultView
102 modifiers ||= {}
103
104 eventSequence = ["mouseover", "mousedown", "mouseup", "click"]
105 for event in eventSequence
106 mouseEvent = document.createEvent("MouseEvents")
107 mouseEvent.initMouseEvent(event, true, true, window, 1, 0, 0, 0, 0, modifiers.ctrlKey, false, false,
108 modifiers.metaKey, 0, null)
109 # Debugging note: Firefox will not execute the element's default action if we dispatch this click event,
110 # but Webkit will. Dispatching a click on an input box does not seem to focus it; we do that separately
111 element.dispatchEvent(mouseEvent)
112
113 focusSelection = (document) ->
114 selection = document.getSelection()
115 console.expand selection
116 for i in [0...selection.rangeCount]
117 console.log "range count", selection.rangeCount, i, selection.getRangeAt(i).startContainer
118 if element = selection.getRangeAt(i).startContainer?.parentElement
119 if isElementEditable element
120 range.startContainer.focus()
121 return true
122
123 return false
124
125 # Write a string into system clipboard
126 writeToClipboard = (window, text) ->
127 str = Cc["@mozilla.org/supports-string;1"].createInstance(Ci.nsISupportsString);
128 str.data = text
129
130 trans = Cc["@mozilla.org/widget/transferable;1"].createInstance(Ci.nsITransferable);
131
132 if trans.init
133 privacyContext = window.QueryInterface(Ci.nsIInterfaceRequestor)
134 .getInterface(Ci.nsIWebNavigation)
135 .QueryInterface(Ci.nsILoadContext);
136 trans.init(privacyContext);
137
138 trans.addDataFlavor("text/unicode");
139 trans.setTransferData("text/unicode", str, text.length * 2);
140
141 _clip.setData trans, null, Ci.nsIClipboard.kGlobalClipboard
142 #
143 # Write a string into system clipboard
144 readFromClipboard = (window) ->
145 trans = Cc["@mozilla.org/widget/transferable;1"].createInstance(Ci.nsITransferable);
146
147 if trans.init
148 privacyContext = window.QueryInterface(Ci.nsIInterfaceRequestor)
149 .getInterface(Ci.nsIWebNavigation)
150 .QueryInterface(Ci.nsILoadContext);
151 trans.init(privacyContext);
152
153 trans.addDataFlavor("text/unicode");
154
155 _clip.getData trans, Ci.nsIClipboard.kGlobalClipboard
156
157 str = {}
158 strLength = {}
159
160 trans.getTransferData("text/unicode", str, strLength)
161
162 if str
163 str = str.value.QueryInterface(Ci.nsISupportsString);
164 return str.data.substring 0, strLength.value / 2
165
166 return undefined
167
168 # Executes function `func` and mearues how much time it took
169 timeIt = (func, msg) ->
170 start = new Date().getTime()
171 result = func()
172 end = new Date().getTime()
173
174 console.log msg, end - start
175 return result
176
177 # Checks if the string provided matches one of the black list entries
178 # `blackList`: comma/space separated list of URLs with wildcards (* and !)
179 isBlacklisted = (str, blackList) ->
180 for rule in blackList.split(/[\s,]+/)
181 rule = rule.replace(/\*/g, '.*').replace(/\!/g, '.')
182 if str.match new RegExp("^#{ rule }$")
183 return true
184
185 return false
186
187 # Gets VimFx verions. AddonManager only provides async API to access addon data, so it's a bit tricky...
188 getVersion = do ->
189 version = null
190
191 if version == null
192 scope = {}
193 addonId = getPref 'addon_id'
194 Cu.import("resource://gre/modules/AddonManager.jsm", scope);
195 scope.AddonManager.getAddonByID addonId, ((addon) -> version = addon.version)
196
197 -> version
198
199 # Simulate smooth scrolling
200 smoothScroll = (window, dx, dy, msecs) ->
201 if msecs <= 0 || !Services.prefs.getBoolPref 'general.smoothScroll'
202 window.scrollBy dx, dy
203 else
204 # Callback
205 fn = (_x, _y) ->
206 window.scrollBy(_x, _y)
207 # Number of steps
208 delta = 10
209 l = Math.round(msecs / delta)
210 while l > 0
211 x = Math.round(dx / l)
212 y = Math.round(dy / l)
213 dx -= x
214 dy -= y
215
216 l -= 1
217 window.setTimeout fn, l * delta, x, y
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 regexpEscape = (s) -> return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
225
226 exports.Bucket = Bucket
227 exports.getCurrentTabWindow = getCurrentTabWindow
228 exports.getEventWindow = getEventWindow
229 exports.getEventRootWindow = getEventRootWindow
230 exports.getEventTabBrowser = getEventTabBrowser
231
232 exports.getWindowId = getWindowId
233 exports.getRootWindow = getRootWindow
234 exports.isElementEditable = isElementEditable
235 exports.focusSelection = focusSelection
236 exports.getSessionStore = getSessionStore
237
238 exports.loadCss = loadCss
239
240 exports.simulateClick = simulateClick
241 exports.smoothScroll = smoothScroll
242 exports.readFromClipboard = readFromClipboard
243 exports.writeToClipboard = writeToClipboard
244 exports.timeIt = timeIt
245 exports.isBlacklisted = isBlacklisted
246 exports.getVersion = getVersion
247 exports.parseHTML = parseHTML
248 exports.regexpEscape = regexpEscape
Imprint / Impressum