forked from mozilla/twitter-address-bar-search
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbootstrap.js
More file actions
359 lines (301 loc) · 11.3 KB
/
bootstrap.js
File metadata and controls
359 lines (301 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Twitter Address Bar Search.
*
* The Initial Developer of the Original Code is The Mozilla Foundation.
* Portions created by the Initial Developer are Copyright (C) 2011
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Edward Lee <edilee@mozilla.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
"use strict";
const global = this;
const {classes: Cc, interfaces: Ci, manager: Cm, utils: Cu} = Components;
Cu.import("resource://gre/modules/AddonManager.jsm");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
// Remember if we were just installed
let justInstalled = false;
// Remember if we're on Firefox or Fennec
let platform = Services.appinfo.name == "Firefox" ? "desktop" : "mobile";
// Add functionality to search from the location bar and hook up autocomplete
function addTwitterAddressBarSearch(window) {
let {change} = makeWindowHelpers(window);
let {BrowserUI, gBrowser, gURLBar} = window;
// Check the input to see if the twitter icon should be shown
let lastIcon = "";
function checkInput() {
if (skipCheck())
return;
// Only allow single word #tag and @user
let icon = "";
if (twitterLike(urlbar.value))
icon = TWITTER_ICON;
// Remember that the icon is showing
lastIcon = icon;
setIcon(icon);
}
// Convert to twitter urls if necessary
function getTwitterUrl(input) {
// Only fix up the input if we're indicating that it's a twitter term
return lastIcon == TWITTER_ICON ? toTwitterUrl(input, "bar") : input;
}
// Figure out how to implement various functions depending on the platform
let setIcon, skipCheck, urlbar;
if (gBrowser == null) {
setIcon = function(url) BrowserUI._updateIcon(url);
skipCheck = function() false;
urlbar = BrowserUI._edit;
// Check the input on various events
listen(window, BrowserUI._edit, "input", checkInput);
// Convert inputs to twitter urls
change(window.Browser, "getShortcutOrURI", function(orig) {
return function(uri, data) {
uri = getTwitterUrl(uri);
return orig.call(this, uri, data);
};
});
}
else {
setIcon = function(url) window.PageProxySetIcon(url);
skipCheck = function() gURLBar.getAttribute("pageproxystate") == "valid" &&
!gURLBar.hasAttribute("focused");
urlbar = gURLBar;
// Check the input on various events
listen(window, gURLBar, "input", checkInput);
listen(window, gBrowser.tabContainer, "TabSelect", checkInput);
// Convert inputs to twitter urls
change(gURLBar, "_canonizeURL", function(orig) {
return function(event) {
this.value = getTwitterUrl(this.value);
return orig.call(this, event);
};
});
}
// Provide a way to set the autocomplete search engines and initialize
function setSearch(engines) {
urlbar.setAttribute("autocompletesearch", engines);
urlbar.mSearchNames = null;
urlbar.initSearchNames();
};
// Add in the twitter search and remove on cleanup
let origSearch = urlbar.getAttribute("autocompletesearch");
setSearch("twitter " + origSearch);
unload(function() setSearch(origSearch));
}
// Add an autocomplete search engine to provide location bar suggestions
function addTwitterAutocomplete() {
const contract = "@mozilla.org/autocomplete/search;1?name=twitter";
const desc = "Twitter Autocomplete";
const uuid = Components.ID("42778970-8fae-454d-ad3f-eea88b945af1");
// Keep a timer to send a delayed no match
let timer;
function clearTimer() {
if (timer != null)
timer.cancel();
timer = null;
}
function setTimer(callback) {
timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
timer.initWithCallback({
notify: function() {
timer = null;
callback();
}
}, 1000, timer.TYPE_ONE_SHOT);
}
// Implement the autocomplete search that handles twitter queries
let search = {
createInstance: function(outer, iid) search.QueryInterface(iid),
QueryInterface: XPCOMUtils.generateQI([Ci.nsIAutoCompleteSearch]),
// Handle searches from the location bar
startSearch: function(query, param, previous, listener) {
// Always clear the timer on a new search
clearTimer();
// Specially handle twitter-like queries
if (twitterLike(query)) {
let label;
if (query[0] == "#")
label = "Search for " + query;
else
label = "View account for " + query;
// Call the listener immediately with one result
listener.onSearchResult(search, {
getCommentAt: function() "Twitter: " + query,
getImageAt: function() TWITTER_ICON,
getLabelAt: function() label,
getValueAt: function() toTwitterUrl(query, "autocomplete"),
getStyleAt: function() "favicon",
get matchCount() 1,
QueryInterface: XPCOMUtils.generateQI([Ci.nsIAutoCompleteResult]),
removeValueAt: function() {},
searchResult: Ci.nsIAutoCompleteResult.RESULT_SUCCESS,
get searchString() query,
});
}
// Send a delayed NOMATCH so the autocomplete doesn't close early
else {
setTimer(function() {
listener.onSearchResult(search, {
searchResult: Ci.nsIAutoCompleteResult.RESULT_NOMATCH,
});
});
}
},
// Nothing to cancel other than a delayed search as results are synchronous
stopSearch: function() {
clearTimer();
},
};
// Register this autocomplete search service and clean up when necessary
const registrar = Ci.nsIComponentRegistrar;
Cm.QueryInterface(registrar).registerFactory(uuid, desc, contract, search);
unload(function() {
Cm.QueryInterface(registrar).unregisterFactory(uuid, search);
});
}
// Add a default search engine and move it to the right place
function addTwitterSearchEngine() {
// Hide any existing "Twitter" searches
let origEngine = Services.search.getEngineByName("Twitter");
if (origEngine != null) {
origEngine.hidden = true;
unload(function() origEngine.hidden = false);
}
// Add the "Twitter " search engine if necessary
let engineName = "Twitter ";
try {
Services.search.addEngineWithDetails(engineName, TWITTER_ICON, "", "",
"GET", getTwitterBase("search/{searchTerms}", "search"));
}
catch(ex) {}
// Get the just-added or existing engine
let engine = Services.search.getEngineByName(engineName);
if (engine == null)
return;
// Move it to position #2 after Google for the partner package
Services.search.moveEngine(engine, 1);
// Clean up when disabling
unload(function() Services.search.removeEngine(engine));
}
// Make sure the window has an app tab set to Twitter
function ensureTwitterAppTab(window) {
// Only bother if we were just installed and support app tabs
if (!justInstalled || platform != "desktop")
return;
// Try again after a short delay if session store is initializing
let {__SSi, __SS_restoreID, gBrowser, setTimeout} = window;
if (__SSi == null || __SS_restoreID != null) {
setTimeout(function() ensureTwitterAppTab(window), 1000);
return;
}
// Figure out if we already have a pinned twitter
let twitterTab = findOpenTab(gBrowser, function(tab, URI) {
return tab.pinned && URI.host == "twitter.com";
});
// Always remove the twitter tab when uninstalling
unload(function() gBrowser.removeTab(twitterTab));
// No need to add!
if (twitterTab != null)
return;
// Add the tab and pin it as the last app tab
twitterTab = gBrowser.addTab(getTwitterBase("", "apptab"));
gBrowser.pinTab(twitterTab);
}
// Open a new tab for the landing page and select it
function showLandingPage(window) {
// Only bother if we were just installed and haven't shown yet
if (!justInstalled || showLandingPage.shown)
return;
// Do the appropriate thing on each platform
if (platform == "desktop") {
// Try again after a short delay if session store is initializing
let {__SSi, __SS_restoreID, gBrowser, setTimeout} = window;
if (__SSi == null || __SS_restoreID != null) {
setTimeout(function() showLandingPage(window), 1000);
return;
}
// Figure out if we already have a landing page
let landingTab = findOpenTab(gBrowser, function(tab, URI) {
return URI.spec == LANDING_PAGE;
});
// Always remove the landing page when uninstalling
unload(function() gBrowser.removeTab(landingTab));
// Add the landing page if not open yet
if (landingTab == null)
landingTab = gBrowser.loadOneTab(LANDING_PAGE);
// Make sure it's focused
gBrowser.selectedTab = landingTab;
}
else {
let {BrowserUI} = window;
let tab = BrowserUI.newTab(LANDING_PAGE);
unload(function() BrowserUI.closeTab(tab));
}
// Only show the landing page once
showLandingPage.shown = true;
}
/**
* Handle the add-on being activated on install/enable
*/
function startup({id}, reason) AddonManager.getAddonByID(id, function(addon) {
// Load various javascript includes for helper functions
["helper", "utils"].forEach(function(fileName) {
let fileURI = addon.getResourceURI("scripts/" + fileName + ".js");
Services.scriptloader.loadSubScript(fileURI.spec, global);
});
// Add twitter support to the browser
watchWindows(addTwitterAddressBarSearch);
addTwitterAutocomplete();
addTwitterSearchEngine();
watchWindows(ensureTwitterAppTab);
watchWindows(showLandingPage);
// We're no longer just installed after we get some windows loaded
watchWindows(function(window) {
if (justInstalled)
window.setTimeout(function() justInstalled = false, 5000);
});
})
/**
* Handle the add-on being deactivated on uninstall/disable
*/
function shutdown(data, reason) {
// Clean up with unloaders when we're deactivating
if (reason != APP_SHUTDOWN)
unload();
}
/**
* Handle the add-on being installed
*/
function install(data, reason) {
justInstalled = reason == ADDON_INSTALL;
}
/**
* Handle the add-on being uninstalled
*/
function uninstall(data, reason) {}