comparison background.js @ 0:480f8e4f4500

Initial revision
author Guido Berhoerster <guido+tab-mover@berhoerster.name>
date Sun, 19 Feb 2017 00:20:26 +0100
parents
children 2a87d7a3863f
comparison
equal deleted inserted replaced
-1:000000000000 0:480f8e4f4500
1 /*
2 * Copyright (C) 2017 Guido Berhoerster <guido+tab-mover@berhoerster.name>
3 *
4 * This Source Code Form is subject to the terms of the Mozilla Public
5 * License, v. 2.0. If a copy of the MPL was not distributed with this
6 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
7 */
8
9 'use strict';
10
11 function createContextMenuItem(createProperties) {
12 return new Promise((resolve, reject) => {
13 browser.contextMenus.create(createProperties, () => {
14 if (browser.runtime.lastError) {
15 reject(browser.runtime.lastError);
16 } else {
17 resolve();
18 }
19 });
20 });
21 }
22
23 const Observable = (superclass) => class extends superclass {
24 constructor(...args) {
25 super(...args);
26
27 this._observers = new Map();
28 }
29
30 addObserver(eventName, observer, thisArg) {
31 if (!this._observers.has(eventName)) {
32 this._observers.set(eventName, new Set());
33 }
34
35 this._observers.get(eventName).add(observer);
36 }
37
38 deleteObserver(eventName, observer) {
39 if (this._observers.has(eventName)) {
40 this._observers.get(eventName).delete(observer);
41 }
42 }
43
44 notifyObservers(eventName, ...args) {
45 if (!this._observers.has(eventName)) {
46 return;
47 }
48
49 for (let observer of this._observers.get(eventName)) {
50 observer(eventName, ...args);
51 }
52 }
53 }
54
55 class WindowsModel extends Observable(Object) {
56 constructor() {
57 super();
58
59 this.windows = new Map();
60 this.focusedWindowId = browser.windows.WINDOW_ID_NONE;
61 }
62
63 hasWindow(id) {
64 return this.windows.has(id);
65 }
66
67 getWindow(id) {
68 return this.windows.get(id);
69 }
70
71 getAllWindows() {
72 return this.windows.values();
73 }
74
75 getfocusedWindowId() {
76 return this.focusedWindowId;
77 }
78
79 openWindow(id, incognito = false) {
80 this.windows.set(id, {
81 id,
82 title: browser.i18n.getMessage(incognito ?
83 'defaultIncognitoWindowTitle' : 'defaultWindowTitle', id),
84 incognito
85 });
86
87 this.notifyObservers('window-opened', id);
88 }
89
90 updateWindowTitle(id, title) {
91 if (!this.windows.has(id)) {
92 return;
93 }
94
95 let windowInfo = this.windows.get(id)
96 windowInfo.title = browser.i18n.getMessage(windowInfo.incognito ?
97 'incognitoWindowTitle' : 'windowTitle', title);
98
99 this.notifyObservers('window-title-updated', id, title);
100 }
101
102 focusWindow(id) {
103 let oldId = this.focusedWindowId;
104 this.focusedWindowId = this.windows.has(id) ? id :
105 browser.windows.WINDOW_ID_NONE;
106
107 this.notifyObservers('window-focus-changed', oldId, id);
108 }
109
110 closeWindow(id) {
111 if (!this.windows.has(id)) {
112 return;
113 }
114
115 this.windows.delete(id);
116
117 if (id === this.focusedWindowId) {
118 this.focusedWindowId = browser.windows.WINDOW_ID_NONE;
119 }
120
121 this.notifyObservers('window-closed', id);
122 }
123 }
124
125 class MenuView {
126 constructor(model) {
127 this.model = model;
128 this.moveMenuIds = new Set();
129 this.reopenMenuIds = new Set();
130 this.menuContexts = ['tab'];
131
132 browser.runtime.getBrowserInfo().then(browserInfo => {
133 // Firefox before version 53 does not support tab context menus
134 let majorVersion = browserInfo.version.match(/^\d+/);
135 if (majorVersion !== null && majorVersion < 53) {
136 this.menuContexts = ['all'];
137 }
138
139 return Promise.all([
140 // create submenus
141 createContextMenuItem({
142 id: 'move-menu',
143 title: browser.i18n.getMessage('moveToWindowMenu'),
144 enabled: false,
145 contexts: this.menuContexts
146 }),
147 createContextMenuItem({
148 id: 'reopen-menu',
149 title: browser.i18n.getMessage('reopenInWindowMenu'),
150 enabled: false,
151 contexts: this.menuContexts
152 })
153 ]);
154 }).then(values => {
155 this.model.addObserver('window-opened',
156 this.onWindowOpened.bind(this));
157 this.model.addObserver('window-title-updated',
158 this.onWindowTitleUpdated.bind(this));
159 this.model.addObserver('window-focus-changed',
160 this.onWindowFocusChanged.bind(this));
161 this.model.addObserver('window-closed',
162 this.onWindowClosed.bind(this));
163 }).catch(error => {
164 console.log('Error:', error);
165 });
166 }
167
168 enableMenus() {
169 return Promise.all([
170 browser.contextMenus.update('move-menu', {
171 enabled: this.moveMenuIds.size > 0
172 }),
173 browser.contextMenus.update('reopen-menu', {
174 enabled: this.reopenMenuIds.size > 0
175 })
176 ]);
177 }
178
179 onWindowOpened(eventName, windowId) {
180 let focusedWindowId = this.model.getfocusedWindowId();
181 if (focusedWindowId === browser.windows.WINDOW_ID_NONE) {
182 return;
183 }
184
185 let menuId = String(windowId);
186 let windowInfo = this.model.getWindow(windowId);
187 let incognito = this.model.getWindow(focusedWindowId).incognito;
188
189 if (incognito && !windowInfo.incognito) {
190 this.reopenMenuIds.add(menuId);
191 } else {
192 this.moveMenuIds.add(menuId);
193 }
194
195 createContextMenuItem({
196 id: menuId,
197 title: windowInfo.title,
198 contexts: this.menuContexts,
199 parentId: (incognito && !windowInfo.incognito) ?
200 'reopen-menu' : 'move-menu'
201 }).then(() => {
202 return this.enableMenus();
203 }).catch(error => {
204 console.log('Error:', error);
205 });
206 }
207
208 onWindowTitleUpdated(eventName, windowId, title) {
209 if (this.model.getfocusedWindowId() ===
210 browser.windows.WINDOW_ID_NONE) {
211 return;
212 }
213
214 browser.contextMenus.update(String(windowId), {title}).catch(error => {
215 console.log('Error:', error);
216 });
217 }
218
219 onWindowFocusChanged(eventName, oldWindowId, newWindowId) {
220 let promises = [
221 // disable submenus
222 browser.contextMenus.update('move-menu', {
223 enabled: false
224 }),
225 browser.contextMenus.update('reopen-menu', {
226 enabled: false
227 })
228 ];
229
230 if (newWindowId === browser.windows.WINDOW_ID_NONE) {
231 // just disable the submenus if focus moved to a window not tracked
232 Promise.all(promises).catch(error => {
233 console.log('Error:', error);
234 });
235 return;
236 }
237
238 Promise.all(promises).then(values => {
239 // remove all submenu items
240 let promises = new Array(...this.moveMenuIds,
241 ...this.reopenMenuIds).map(menuId => {
242 this.moveMenuIds.delete(menuId) ||
243 this.reopenMenuIds.delete(menuId);
244
245 return browser.contextMenus.remove(menuId);
246 });
247
248 return Promise.all(promises);
249 }).then(values => {
250 let incognito = this.model.getWindow(newWindowId).incognito;
251
252 // rebuild submenus
253 let promises = [];
254 for (let windowInfo of this.model.getAllWindows()) {
255 if (windowInfo.id === newWindowId) {
256 // skip the currently focused window
257 continue;
258 }
259
260 let menuId = String(windowInfo.id);
261 if (incognito && !windowInfo.incognito) {
262 this.reopenMenuIds.add(menuId);
263 } else {
264 this.moveMenuIds.add(menuId);
265 }
266
267 // create menu item
268 promises.push(createContextMenuItem({
269 id: menuId,
270 title: windowInfo.title,
271 contexts: this.menuContexts,
272 parentId: (incognito && !windowInfo.incognito) ?
273 'reopen-menu' : 'move-menu'
274 }));
275 }
276
277 return Promise.all(promises);
278 }).then(values => {
279 return this.enableMenus();
280 }).catch(error => {
281 console.log('Error:', error);
282 });
283 }
284
285 onWindowClosed(eventName, windowId) {
286 if (this.model.getfocusedWindowId() ===
287 browser.windows.WINDOW_ID_NONE) {
288 return;
289 }
290
291 let menuId = String(windowId);
292
293 this.moveMenuIds.delete(menuId) || this.reopenMenuIds.delete(menuId);
294
295 browser.contextMenus.remove(menuId).then(() => {
296 return this.enableMenus();
297 }).catch(error => {
298 console.log('Error:', error);
299 });
300 }
301 }
302
303 class Presenter {
304 constructor(model, view) {
305 this.model = model;
306 this.view = view;
307
308 browser.windows.getAll({windowTypes: ['normal']}).then(windows => {
309 // populate model with existing windows
310 for (let windowInfo of windows) {
311 this.onWindowCreated(windowInfo);
312
313 if (windowInfo.focused) {
314 this.onWindowFocusChanged(windowInfo.id);
315 }
316 }
317
318 browser.windows.onCreated
319 .addListener(this.onWindowCreated.bind(this));
320 browser.windows.onRemoved
321 .addListener(this.onWindowRemoved.bind(this));
322 browser.windows.onFocusChanged
323 .addListener(this.onWindowFocusChanged.bind(this));
324 browser.contextMenus.onClicked
325 .addListener(this.onMenuItemClicked.bind(this));
326 }).catch(error => {
327 console.log('Error:', error);
328 });
329 }
330
331 onWindowCreated(windowInfo) {
332 // only track normal windows
333 if (windowInfo.type !== 'normal') {
334 return;
335 }
336
337 this.model.openWindow(windowInfo.id, windowInfo.incognito);
338
339 // get the window title and update the model
340 browser.tabs.query({
341 active: true,
342 windowId: windowInfo.id
343 }).then(tabs => {
344 this.model.updateWindowTitle(tabs[0].windowId, tabs[0].title)
345 }).catch(error => {
346 console.log('Error:', error);
347 });
348 }
349
350 onWindowRemoved(windowId) {
351 this.model.closeWindow(windowId);
352 }
353
354 onWindowFocusChanged(windowId) {
355 let prevFocusedWindowId = this.model.getfocusedWindowId();
356 if (prevFocusedWindowId !== browser.windows.WINDOW_ID_NONE) {
357 // get title of the previously focused window and update the model
358 browser.tabs.query({
359 active: true,
360 windowId: prevFocusedWindowId
361 }).then(tabs => {
362 this.model.updateWindowTitle(tabs[0].windowId, tabs[0].title)
363 }).catch(error => {
364 console.log('Error:', error);
365 });
366 }
367
368 this.model.focusWindow(windowId);
369 }
370
371 onMenuItemClicked(info, tab) {
372 if (info.parentMenuItemId === 'move-menu') {
373 // move tab from the current window to the selected window
374 browser.tabs.move(tab.id, {
375 windowId: parseInt(info.menuItemId),
376 index: -1
377 }).catch(error => {
378 console.log('Error:', error);
379 });
380 } else {
381 // open the URL of the current tab in the selected window and close
382 // the current tab
383 browser.tabs.create({
384 url: tab.url,
385 windowId: parseInt(info.menuItemId),
386 index: -1
387 }).then(newTab => {
388 return browser.tabs.remove(tab.id);
389 }).catch(error => {
390 console.log('Error:', error);
391 });
392 }
393 }
394 }
395
396 let windowsModel = new WindowsModel();
397 let menuView = new MenuView(windowsModel);
398 let presenter = new Presenter(windowsModel, menuView);