-
Notifications
You must be signed in to change notification settings - Fork 1
/
extension.js
322 lines (276 loc) · 9.36 KB
/
extension.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
315
316
317
318
319
320
321
322
var vscode = require('vscode')
var mkdirp = require('mkdirp')
var fs = require('fs')
var path = require('path')
var trash = require('trash')
var exec = require('child_process').exec
var DEFAULT_HOSTNAME = 'https://quiet-shelf-57463.herokuapp.com'
var config = vscode.workspace.getConfiguration('multihack-vscode')
var context = null
var remote = null
var projectBasePath = null
var relativePath = null
var isSyncing = false
var currentEditor = null
var editorMutexLock = false
var watcher = null
var workspaceEditQueue = []
var dumpingWorkspaceQueue = false
function activate (newContext) {
console.log('Congratulations, your extension "multihack-vscode" is now active!')
context = newContext
console.log(context.storagePath)
vscode.commands.registerCommand('extension.multihackJoinRoom', handleStart)
vscode.commands.registerCommand('extension.multihackLeaveRoom', handleStop)
vscode.commands.registerCommand('extension.multihackFetchCode', requestProject)
}
exports.activate = activate
function deactivate () {
handleStop()
}
exports.deactivate = deactivate
function handleStart () {
if (isSyncing) handleStop() // clean up before joining a new room
if (!vscode.workspace.rootPath) return vscode.window.showErrorMessage('Multihack: Open a folder before joining a room!')
projectBasePath = vscode.workspace.rootPath
setupEventListeners()
installElectron(function () {
getRoomAndNickname(function (roomID, nickname) {
var RemoteManager = require('./lib/remote')
remote = new RemoteManager(config.get('multihack.hostname') || DEFAULT_HOSTNAME, roomID, nickname)
remote.on('changeFile', handleRemoteChangeFile)
remote.on('deleteFile', handleRemoteDeleteFile)
remote.on('requestProject', handleRequestProject)
remote.on('provideFile', handleProvideFile)
remote.once('gotPeer', function () {
console.log('gotPeer')
remote.requestProject()
})
remote.on('lostPeer', function (peer) {
vscode.window.showInformationMessage('Multihack: Lost connection to '+peer.metadata.nickname)
})
isSyncing = true
console.log('MH started')
})
})
}
function setupEventListeners () {
vscode.workspace.onDidChangeConfiguration(function () {
if (projectBasePath !== vscode.workspace.rootPath) handleStop() // stop on new project opened
})
vscode.window.onDidChangeActiveTextEditor(handleEditorChange)
handleEditorChange()
vscode.workspace.onDidChangeTextDocument(handleLocalChangeFile)
watcher = vscode.workspace.createFileSystemWatcher('**/*', false, true, false)
watcher.onDidDelete(handleLocalDeleteFile)
watcher.onDidCreate(handleLocalCreateFile)
}
function handleRequestProject (requester) {
// vscode is an electron app, so we don't have to worry about forwarding limits
vscode.workspace.findFiles('**/*').then(function (uris) {
uris.forEach(function (uri) {
fs.readFile(uri.path, function (err, content) {
if (err) return
var filePath = toWebPath(vscode.workspace.asRelativePath(uri.path))
remote.provideFile(filePath, content.toString(), requester)
console.log('provided', filePath)
})
})
}, noop)
}
function handleProvideFile (data) {
var filePath = projectBasePath+data.filePath
var range = new vscode.Range(0, 0, Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER)
var textEdit = new vscode.TextEdit(range, data.content)
applyWorkspaceEdits(filePath, [textEdit], noop)
}
function handleEditorChange () {
currentEditor = vscode.window.activeTextEditor
if (currentEditor) relativePath = toWebPath(vscode.workspace.asRelativePath(currentEditor.document.fileName))
}
function handleLocalCreateFile (uri) {
var relativePath = toWebPath(vscode.workspace.asRelativePath(uri.path))
fs.readFile(uri.path, function (err, content) {
if (err) return
remote.changeFile(relativePath, {
from: {line: 0, ch: 0},
to: { line: 0, ch: 0},
text: content.toString(),
origin: 'paste'
})
})
}
function handleLocalDeleteFile (uri) {
remote.deleteFile(toWebPath(vscode.workspace.asRelativePath(uri.path)))
}
function handleLocalChangeFile (e) {
if (editorMutexLock || !isSyncing) return
for (var i=0; i<e.contentChanges.length; i++) {
var change = toCodeMirrorChange(e.contentChanges[i])
console.log(relativePath, change)
remote.changeFile(relativePath, change)
}
}
function handleRemoteChangeFile (data) {
console.log(data)
if (data.change.type === 'rename') {
return //todo
} else if (data.change.type === 'selection') {
return // todo
} else {
applyChange(data.filePath, data.change)
}
}
function handleRemoteDeleteFile (data) {
var absPath = projectBasePath+data.filePath
trash([absPath])
}
function applyChange (filePath, change) {
var workspaceEdit = new vscode.WorkspaceEdit()
var textEdit = toVscodeEdit(change, null)
applyWorkspaceEdits(projectBasePath+filePath, [textEdit], function (err) {
workspaceEditQueue.push({
filePath: filePath,
edit: textEdit
})
if (!dumpingWorkspaceQueue) {
dumpingWorkspaceQueue = true
setTimeout(dumpWorkspaceQueue, 10)
}
})
}
// same as above, but for workspace
function dumpWorkspaceQueue () {
// group by filePath (alphabetical sort)
workspaceEditQueue.sort(function (a, b) {
return a.filePath.localeCompare(b.filePath)
})
var currentGroup = [] // current group of edits
var currentPath = null // current uri of file being edited
workspaceEditQueue.forEach(function (x) {
if (x.filePath !== currentPath) { // new group
if (currentPath !== null) {
// apply the group
applyWorkspaceEdits(projectBasePath+currentPath, currentGroup, function (err) {
vscode.window.showErrorMessage('Multihack: Failed to apply changes!')
})
}
currentGroup = [x.edit]
currentPath = x.filePath
} else { // same group
currentGroup.push(x.edit)
}
})
}
function applyWorkspaceEdits (filePath, edits, errorCallback) {
var workspaceEdit = new vscode.WorkspaceEdit()
vscode.workspace.openTextDocument(filePath).then(function (doc) {
workspaceEdit.set(doc.uri, edits)
editorMutexLock = true
vscode.workspace.applyEdit(workspaceEdit).then(function () {
editorMutexLock = false
vscode.workspace.saveAll()
}, function (err) {
editorMutexLock = false
errorCallback(err)
})
}, function (err) {
if (err.indexOf('File not found') !== -1) {
var parentPath = filePath.split('/').slice(0, -1).join('/')
mkdirp(parentPath, function (err) {
if (err) console.error(err)
fs.writeFile(filePath, '', function () {
applyWorkspaceEdits(filePath, edits, errorCallback)
})
})
}
})
}
// convert a vscode change event to a CodeMirror one
function toCodeMirrorChange (change) {
return {
from: {
ch: change.range.start.character,
line: change.range.start.line
},
to: {
ch: change.range.end.character,
line: change.range.end.line
},
text: change.text,
removed: '', // todo?
origin: '' // todo?
}
}
// build a vscode TextEdit from a Codemirror Change
// if editBuilder is defined, the edit will be applied to that builder
// if not, it returns the TextEdit
function toVscodeEdit(change, editBuilder) {
var start = new vscode.Position(change.from.line, change.from.ch)
var end = new vscode.Position(change.to.line, change.to.ch)
var range = new vscode.Range(start, end)
if (editBuilder) {
editBuilder.replace(range, change.text.join('\n'))
} else {
return new vscode.TextEdit(range, change.text.join('\n'))
}
}
function toWebPath (path) {
return path[0] === '/' ? path : '/'+path
}
function fromWebPath (path) {
return path[0] === '/' ? path.slice(1) : path
}
function getDocumentFromEditor (vsEditor) {
return typeof vsEditor._documentData !== 'undefined' ? vsEditor._documentData : vsEditor._document
}
function handleStop () {
if (!isSyncing) return
remote.destroy()
remote = null
isSyncing = false
watcher.dispose()
console.log('MH stopped')
}
function requestProject () {
if (!isSyncing) return
remote.requestProject()
}
function getRoomAndNickname (cb) {
var defaultRoom = config.get('multihack.defaultRoom') || ''
if (!defaultRoom) {
defaultRoom = Math.random().toString(36).substr(2, 20)
}
vscode.window.showInputBox({
prompt: 'Enter the ID for the room you want to join:',
placeHolder: 'RoomID',
value: defaultRoom,
ignoreFocusOut: true
}).then(function (roomID) {
if (!roomID) return
vscode.window.showInputBox({
prompt: 'Enter a nickname so your team knows who you are:',
placeHolder: 'Nickname',
ignoreFocusOut: true
}).then(function (nickname) {
nickname = nickname || 'Guest'
cb(roomID, nickname)
})
})
}
function installElectron (cb) {
var extPath = vscode.extensions.getExtension('rationalcoding.multihack-vscode').extensionPath
fs.stat(path.join(extPath, 'electron-ok'), function (err) {
if (err) {
vscode.window.showInformationMessage('Multihack: Initializing, please wait. (This will only happen once)')
exec('cd '+extPath+' && npm install electron && mkdir electron-ok', function (err, stdout, stderr) {
vscode.window.showInformationMessage('Multihack: Initializion completed! Enjoy!')
cb()
}, noop)
} else {
console.log('electron is ok')
cb()
}
})
}
function noop () {}