-
-
Notifications
You must be signed in to change notification settings - Fork 116
/
lib.js
314 lines (280 loc) · 9.65 KB
/
lib.js
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
'use strict';
/**
* GhostText for Chrome lib.
*
* @licence The MIT License (MIT)
* @author Guido Krömer <mail 64 cacodaemon 46 de>
* @author Federico Brigante
*/
var GhostText = {
/**
* @type {number} The GhostText protocol version.
* @private
* @const
*/
protocolVersion: 1,
/**
* Chrome tab id to WebSocket mapping.
* @type {Array<WebSocket>}
* @private
* @static
*/
connections: {},
/**
* Call the callback with the current tab id (async)
*
* @param {function} callback The function to call with the id
*/
inCurrentTab: function (callback) {
chrome.tabs.query({
active: true,
currentWindow: true
}, function(tabs){
callback(tabs[0].id);
});
},
/**
* Gets or sets the GhostText server main port.
*
* @param {number} port The TCP port number.
* @returns {number} The TCP port number.
* @public
* @static
*/
serverPort: function(port) {
if (!port) {
return localStorage.getItem('server-port-v1') || 4001;
}
localStorage.setItem('server-port-v1', port);
},
/**
* Make sure that content scripts and styles are only loaded once
*
* @param {number} tabId The tab in which to inject the content scripts
* @param {function} callback The function to call after the scripts have been loaded
*/
loadContentJs: function (tabId, callback) {
chrome.tabs.executeScript(tabId, {
code: '!!window.GhostTextContent'//check if it's already loaded
}, function (hasContentJs) {
if (hasContentJs[0]) {
callback();
} else {
chrome.tabs.insertCSS(tabId, { file: 'vendor/humane-ghosttext.css' });
chrome.tabs.executeScript(tabId, { file: 'vendor/humane-ghosttext.min.js' });
chrome.tabs.executeScript(tabId, { file: 'scripts/input-area.js' });
chrome.tabs.executeScript(tabId, { file: 'scripts/content.js' }, callback);
}
});
},
/**
* Handles incoming connections from the content script.
* Has to be started in the background script.
* @public
* @static
*/
connectionHandler: function () {
chrome.runtime.onConnect.addListener(GhostText.connectionHandlerOnConnect);
chrome.runtime.onMessage.addListener(GhostText.messageHandler);
chrome.browserAction.onClicked.addListener(GhostText.toggleCurrentTab);
chrome.commands.onCommand.addListener(function (command) {
if (command === 'toggle') {
GhostText.toggleCurrentTab();
}
});
},
/**
* Enable or disable GT in the current tab
* @public
* @static
*/
toggleCurrentTab: function () {
GhostText.inCurrentTab(function (tabId) {
GhostText.loadContentJs(tabId, function () {
if (GhostText.connections[tabId]) {
GhostText.closeConnection(tabId);
} else {
chrome.tabs.sendMessage(tabId, {
action: 'select-field',
tabId: tabId
});
}
});
});
},
/**
* Handles incoming chrome messages, used by the connectionHandler.
*
* @param {*} port
* @see https://developer.chrome.com/extensions/runtime#type-Port
* @private
*/
connectionHandlerOnConnect: function(port) {
if (port.name !== 'GhostText') {
return;
}
port.onMessage.addListener(function(msg) {
/** @type {string} The chrome tab id. */
var tabId = msg.tabId;
if (GhostText.connections[tabId] && GhostText.connections[tabId].readyState === 1) { // 1 - connection established
GhostText.connections[tabId].send(msg.change);
return;
}
fetch('http://localhost:' + GhostText.serverPort())
.then(r => r.json())
.then(({ProtocolVersion, WebSocketPort}) => {
if (!GhostText.checkProtocolVersion(ProtocolVersion)) {
return;
}
try {
GhostText.connections[tabId] = new WebSocket('ws://localhost:' + WebSocketPort);
} catch (e) {
GhostText.errorHandler(e);
return;
}
GhostText.connections[tabId].onopen = function () {
chrome.browserAction.setBadgeText({
text: /OS X/i.test(navigator.userAgent)?'✓':'ON',
tabId: tabId
});
chrome.browserAction.setBadgeBackgroundColor({
color: '#008040',
tabId: tabId
});
GhostText.connections[tabId].send(msg.change);
console.log('Connection: opened');
chrome.tabs.sendMessage(tabId, {
action: 'enable-field',
tabId: tabId
});
};
GhostText.connections[tabId].onclose = function () {
GhostText.closeConnection(tabId);
};
GhostText.connections[tabId].onerror = function (event) {
GhostText.closeConnection(tabId);
console.log('Connection: error:', event);
GhostText.errorHandler(event);
};
GhostText.connections[tabId].onmessage = function (event) {
port.postMessage({
tabId: tabId,
change: event.data
});
};
}).catch(GhostText.errorHandler);
});
},
/**
* Closes a WebSocket connected to a tab.
*
* @param {number} tabId
* @returns {boolean}
* @private
* @static
*/
closeConnection: function(tabId) {
if (!GhostText.connections[tabId]) {
return false;
}
if (GhostText.connections[tabId].readyState !== 3) { // 3 - connection closed or could not open
try {
GhostText.connections[tabId].close();
} catch (e) {
console.log('Connection: error during closing:', e);
}
}
delete GhostText.connections[tabId];
console.log('Connection: closed');
try { //inform tab that the connection was closed
chrome.tabs.sendMessage(tabId, {
action: 'disable-field',
tabId: tabId
});
chrome.browserAction.setBadgeText({
text: '',
tabId: tabId
});
// we need to query it again because windowId might have changed in the meanwhile
chrome.tabs.get(tabId, function(tab){
//focus window back
chrome.windows.update(tab.windowId, {
focused: true
});
//focus tab
chrome.tabs.update(tabId, {
active: true
});
});
} catch (e) {
//tab might have been closed already; don't know how to detect it first.
}
return true;
},
/**
* A general error handler.
*
* @param {Error} e
* @private
* @static
*/
errorHandler: function(e) {
if(e && (e.target && e.target.readyState === 3) || e.status === 404 || e.status === 0) {
GhostText.notifyUser('error',
'Connection error.',
'\nMake sure that Sublime Text is open and has GhostText installed.',
'\nTry closing and opening it and try again.',
'\nMake sure that the port matches (4001 is the default).',
'\nSee if there are any errors in Sublime Text\'s console.'
);
}
},
/**
* Prints a error message if the server's protocol version differs from the clients.
*
* @param {number} version The protocol version.
* @private
* @static
*/
checkProtocolVersion: function(version) {
version = parseFloat(version);
if (version === GhostText.protocolVersion) {
return true;
}
GhostText.notifyUser('error', 'Can\'t connect to this GhostText server, the server\'s protocol version is', version, 'the client\'s protocol version is:', GhostText.protocolVersion);
return false;
},
/**
* Handles messages sent from other parts of the extension
*
* @param {object} request The request object passed by Chrome
*/
messageHandler: function (request) {
if (!request || !request.action) {
return;
}
switch (request.action) {
case 'close-connection':
GhostText.closeConnection(request.tabId);
break;
}
},
/**
* Pipe messages to the document thought content.js
*
* @param {string} type The type of message: error|info
* @param {...(number|string)} [message] Message to display
* @static
*/
notifyUser: function (type, message) {
message = [].slice.call(arguments, 1).join(' ');//get the rest parameters and join them
GhostText.inCurrentTab(function (tabId) {
chrome.tabs.sendMessage(tabId, {
tabId: tabId,
type: type,
action: 'notify',
message: message
});
});
}
};