This repository was archived by the owner on Apr 6, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 925
/
Copy pathserver.js
1227 lines (1081 loc) · 36.9 KB
/
server.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
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
require("amd-loader");
var fs = require("fs");
var join = require("path").join;
var proc = require("child_process");
var path = require("path");
// set up env variables for windows
if (process.platform == "win32") {
process.env.CYGWIN = "nodosfilewarning " + (process.env.CYGWIN || "");
process.env.CHERE_INVOKING = 1; // prevent cygwin from changing bash path
}
// HOME usually isn't defined on windows, so weload settings/standalone which adds it
var localSettings = require(join(__dirname, "../settings/local.js"))({ revision: " " }, null);
// Ports on which we'd like to run preview (see http://saucelabs.com/docs/connect#localhost)
var SAFE_PORTS = [2222, 2310, 3000, 3001, 3030, 3210, 3333, 4000, 4001,
4040, 4321, 4502, 4503, 4567, 5000, 5001, 5050, 5555,
5432, 6000, 6001, 6060, 6666, 6543, 7000, 7070, 7774,
7777, 8000, 8001, 8003, 8031, 8080, 8081, 8765, 8777,
8888, 9000, 9001, 9080, 9090, 9876, 9877, 9999, 49221];
var installPath = process.platform == "dar-win" // disabled for sdk
? "/Library/Application Support/Cloud9"
: join(process.env.HOME, ".c9");
// Support legacy installations
if (installPath === "/Library/Application Support/Cloud9"
&& !fs.existsSync(join(installPath, "version"))
&& fs.existsSync(join(process.env.HOME, installPath, "version")))
installPath = join(process.env.HOME, installPath);
var nodePath = process.platform == "win32"
? join(installPath, "node.exe")
: installPath + "/node/bin/node";
var logStream;
// this seems to be needed in both window and server
process.on("uncaughtException", function(err) {
console.error(err);
});
function toInternalPath(path) {
if (process.platform == "win32")
path = path.replace(/^[/]*/, "/").replace(/[\\/]+/g, "/");
return path;
}
var App = window.nwGui.App;
var argv = App.argv;
argv.parsed = parseArgs(argv);
var settingDir = argv.parsed["--setting-path"]
? path.resolve(argv.parsed["--setting-path"])
: (installPath === "/Library/Application Support/Cloud9"
? path.join(process.env.HOME, installPath)
: installPath);
function parseArgs(argv) {
if (typeof argv == "string")
argv = argv.match(/(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'|((?:[^ \\]|\\.)+))/g)
.map(function(x) { return x.replace(/^["']|["']$/g, ""); });
var parsed = {
_: [],
"--setting-path": "",
"-w": ""
};
var argname;
for (var i = 0; i < argv.length; i++) {
var arg = argv[i];
if (arg[0] === "-") {
argname = arg;
if (!(argname in parsed)) {
parsed[argname] = true;
argname = "";
}
} else if (argname) {
parsed[argname] = arg;
argname = "";
} else {
parsed._.push(arg);
}
}
return parsed;
}
var server = {
writePIDFile : function(path){
function write(pid){
fs.writeFile(process.env.HOME + "/.c9/pid", pid + ":" + path,
function(err){});
}
// In OSX the pid is not the nw process, but a child
// We'll look up the parent
if (process.platform == "darwin") {
proc.execFile("ps", ["-axf"], function(err, stdout, stderr){
if (err) return console.log("Could not write PID file: ",
(err.message || err) );
var re = new RegExp("[ \\d]*?\\s" + process.pid
+ "\\s+(\\d+)\\s+.*Contents\\/Frameworks\\/node\\-webkit");
var m = stdout.match(re);
if (!m) return console.log("Could not write PID file");
write(m[1]);
});
}
else
write(process.pid);
},
start : function(options, callback){
if (nwProcessId) {
return windowManager.connection.call(0, {
type: "serverStart",
options: options,
}, callback);
}
var self = this;
if (this.process) {
return process.nextTick(function() {
callback(null, self.options.port);
});
}
// console.log("Starting Cloud9...", port);
var allowExit;
var path = options.path;
if (!path)
path = process.env.HOME || "/";
// Write PID file
this.writePIDFile(path);
// Listen for exit signals
process.on("exit", function(){
if (p) p.kill();
fs.unlink(process.env.HOME + "/.c9/pid", function(){});
});
var args = [
join(__dirname, "../server.js"),
"local",
"--setting-path", settingDir,
"-s", "local",
"--listen", options.host,
"-w", path,
"-p", options.port,
"--collab", options.collab
];
if (options.wsType)
args.push("--workspacetype", options.wsType);
if (options.inProcess) {
var server = require("../server");
args.shift();
return server(args, "local", function() {
callback(null, options.port);
});
}
var env = {};
Object.keys(process.env).forEach(function(name){
env[name] = process.env[name];
});
env["NODE_PATH"] = (process.platform == "win32"
? join(nodePath, "../deps")
: installPath) + "/node_modules";
var p = proc.spawn(nodePath, args, { env: env });
// Do Nothing
function done(){
p.stderr.removeListener("data", waitErr);
p.stdout.removeListener("data", waitOut);
}
function waitErr(chunk){
chunk = chunk.toString();
if (chunk.indexOf("EADDRINUSE") > -1) {
done();
p.kill();
var err = new Error(chunk);
err.code = "EADDRINUSE";
err.options = options;
allowExit = true;
callback(err);
}
}
function waitOut(chunk){
chunk = chunk.toString();
console.warn("SERVER:", chunk);
if (chunk.indexOf("Started") > -1) {
done();
callback(null, options.port);
}
}
p.stderr.on("data", waitErr);
p.stdout.on("data", waitOut);
p.stderr.on("data", function(e) {
console.error(e+"");
});
p.stdout.on("data", function(e) {
console.log(e+"");
});
p.on("exit", function() {
self.process = null;
setTimeout(function() {
if (p.exitCode && !allowExit && !self.process)
self.start(options, function(){});
}, 1000);
});
self.options = options;
self.process = p;
},
findFreePort : function(host, callback) {
var ports = SAFE_PORTS.slice();
find();
function find() {
var port = ports.pop();
if (!port)
return callback(new Error("Could not find an available port"));
require("netutil").isPortOpen(host, port, 2000, function(open) {
if (!open)
return callback(null, port);
find();
});
}
},
stop : function() {
this.process.kill();
},
restart : function() {
this.stop();
this.start(this.options);
},
getPlugins : function(options, cb, restoreWindow) {
var windowConfig = options.windowConfig || {};
var configPath = join(__dirname, "../configs/ide/default-local.js");
var themeDir = join(__dirname, "../build/standalone/skin/" +
(windowConfig.isRemote ? "full" : "default-local"));
var stateConfigFilePath = windowConfig.id
? join(settingDir, "windows/" + windowConfig.id + "-state.settings")
: join(settingDir, "state.settings");
function getConfig(options) {
options.installed = true;
options.settingDir = settingDir;
var settings = {
"user": join(settingDir, "user.settings"),
"profile": join(settingDir, "profile.settings"),
"project": join(settingDir, "project.settings"),
"state": stateConfigFilePath
};
for (var type in settings) {
settings[type] = readJSONFile(settings[type]);
}
if (windowConfig.stateSettings) {
settings.state = windowConfig.stateSettings;
delete windowConfig.stateSettings;
}
options.settings = settings;
if (settings.profile.id) {
options.user = settings.profile;
if (settings.profile.saucelabs) {
options.saucelabs.account = settings.profile.saucelabs;
}
}
else {
options.user = {
id: -1,
name: "Anonymous",
fullname: "Anonymous",
email: "",
pubkey: null
};
}
if (process.platform == "win32")
options.sauceConnectPath = join(nodePath, "../deps");
return require(configPath)(options);
}
function updateFilePaths(plugins, cb) {
var stateSettings, userSettings, preloadPlugin;
function fixCssStaticPath(str) {
if (options.windowLocation && str)
return str.replace(/(url\(["']?)\/(?:standalone\/)?static/g, "$1" + options.windowLocation);
return str;
}
function loadTheme(name, cb) {
if (preloadPlugin[name])
return cb(null, preloadPlugin[name]);
fs.readFile(themeDir + "/" + name + ".css", "utf8", function(err, data) {
// todo rebuild missing themes
data = fixCssStaticPath(data);
preloadPlugin[name] = data;
cb && cb(err, data);
});
}
var isRemote = windowConfig.isRemote;
for (var i = 0; i < plugins.length; i++) {
var p = plugins[i];
if (p.packagePath === "plugins/c9.ide.layout.classic/preload") {
preloadPlugin = p;
if (options.packed || isRemote)
p.loadTheme = loadTheme;
else
p.themePrefix = "/static/standalone/skin/default-local";
}
else if (p.packagePath === "plugins/c9.vfs.client/endpoint") {
p.getServers = options.getServers;
}
else if (p.packagePath == "plugins/c9.ide.language/language") {
p.useUIWorker = options.noWorker;
if (options.packed) {
p.staticPrefix = options.windowLocation;
p.workerPrefix = settings.CORSWorkerPrefix;
} else {
p.staticPrefix = p.workerPrefix = null;
}
}
else if (p.packagePath == "plugins/c9.core/settings") {
if (!isRemote)
p.stateConfigFilePath = stateConfigFilePath;
stateSettings = p.settings.state;
if (typeof stateSettings == "string") {
try {
stateSettings = JSON.parse(stateSettings);
} catch(e) {}
}
userSettings = p.settings.user;
if (typeof userSettings == "string") {
try {
userSettings = JSON.parse(userSettings);
} catch(e) {}
}
}
if (p.staticPrefix && options.windowLocation && (options.packed || isRemote)) {
p.staticPrefix = p.staticPrefix.replace(/^\/static/, options.windowLocation);
}
}
var themeName = userSettings && userSettings.general && userSettings.general["@skin"] || "dark";
restoreWindow && restoreWindow(stateSettings);
loadTheme(themeName, cb);
}
var settings = localSettings;
settings.packed = options.packed;
settings.vfsServers = options.vfsServers;
settings.workspaceDir = options.workspaceDir;
settings.CORSWorkerPrefix = (
options.windowLocation && options.packed ? options.windowLocation + "/build/" : "/static/"
) + "standalone/worker";
if (windowConfig.isRemote)
settings.remoteWorkspace = windowConfig.name;
if (settings.remoteWorkspace) {
getRemoteWorkspaceConfig(windowConfig.name, function(err, config) {
if (err) {
plugins = getConfig(settings);
addErrorHandlerPlugin(plugins, windowConfig);
}
else {
plugins = require(configPath).makeLocal(config.plugins, settings);
settings.url = config.url;
}
plugins.forEach(function(p) {
if (p.staticPrefix)
p.staticPrefix = p.staticPrefix.replace(/^https?:\/\/.*?\/static/, "/static");
})
updateFilePaths(plugins, function(){
cb(plugins, settings);
});
});
} else {
var plugins = getConfig(settings);
updateFilePaths(plugins, function(){
cb(plugins, settings);
});
}
},
appendLog : function(message) {
logStream && logStream.write(message);
},
__dirname : __dirname,
installPath : installPath,
argv: argv,
openWindow : openWindow,
parseArgs : parseArgs,
getRecentWindows: getRecentWindows,
getRemoteWorkspaceConfig: getRemoteWorkspaceConfig
};
function addErrorHandlerPlugin(plugins, windowConfig) {
plugins.push({
provides: [],
consumes: ["c9", "auth", "restore", "dialog.alert", "commands"],
setup: function(options, imports, register) {
imports.auth.on("login", function() {
getRemoteWorkspaceConfig(windowConfig.name, function(err, config) {
if (err) {
return imports["dialog.alert"].alert(
"Error loading remote workspace",
"Couldn't load config for " + windowConfig.name
);
}
imports.commands.exec("restartc9");
});
});
register(null, {});
}
});
}
/*****************************************************************/
/* windowManager: move to own file once build tool supports that */
/*****************************************************************/
var MAX_RECENT_WINDOWS = 20;
var MAX_SAME_PROCESS = 1;
var processIdCounter = 1;
var activeWindowId = null;
var nwProcessId = 0;
var allWindows = Object.create(null);
var windowData = Object.create(null);
var connection = null;
var windowManager = server.windowManager = {
quit: quit,
quitAll: quitAll,
unquit: unquit,
onClose: onClose,
save: scheduleSave,
statePath: join(settingDir, "window.settings"),
openWindow: openWindow,
$allWindows: allWindows,
$windowData: windowData,
onShowWindow: onShowWindow,
restoreSession: restoreSession,
registerWindow: registerWindow,
getRecentWindows: getRecentWindows,
findWindowForPath: findWindowForPath,
registerSharedModule: registerSharedModule,
signalToAll: signalToAll,
setFavorites: setFavorites,
forEachWindow: forEachWindow,
isPrimaryWindow: isPrimaryWindow,
get connection() { return connection },
get activeWindow() { return allWindows[activeWindowId] },
get activeWindowId() { return activeWindowId },
};
function forEachWindow(fn) {
getRecentWindows().forEach(function(data) {
fn(data, allWindows[data.id]);
});
}
function signalToAll(name, e) {
if (nwProcessId)
return connection.call(0, {type: "signalToAll", arg: [name, e]});
forEachWindow(function(data, win) {
if (win && win.emit) win.emit(name, e);
});
}
function isPrimaryWindow(window) {
if (nwProcessId) return false;
var win = window.win;
if (win.options.nwProcessId)
return false;
return true;
}
function findWindowForPath(path) {
var matches = [];
path = toInternalPath(path);
for (var id in windowData) {
var win = windowData[id];
win.favorites && win.favorites.forEach(function(p, i) {
if (path.indexOf(p) === 0 && (path[p.length] == "/" || !path[p.length])) {
matches.push({
win: win,
dist: path.substr(p.length).split("/").length + (i ? 1 : 0)
});
return true;
}
});
}
matches.sort(function(a, b) {
return a.dist - b.dist;
});
return matches[0] && matches[0].win;
}
function restoreSession(win) {
var state = readJSONFile(this.statePath);
var toOpen = [];
Object.keys(state).forEach(function(id) {
var data = state[id];
if (data.isOpen) {
data.isOpen = false;
toOpen.push(data);
}
if (!data.favorites)
data.favorites = [];
windowData[id] = data;
});
// Deal with user reopening app on osx
App.on("reopen", function(){
openWindow({id: activeWindowId || "latest", focus: true});
});
// Event to open additional files (I hope)
App.on("open", function(cmdLine) {
// console.log(cmdLine);
var parsed = parseArgs(cmdLine);
var path = parsed._.pop();
openWindowForPath(path);
});
var path = argv.parsed._.pop();
if (path) {
// todo handle folders?
openWindowForPath(path);
} else {
if (!toOpen.length)
toOpen.push({id: "latest"});
toOpen.sort(function(a, b) {
return b.time - a.time;
});
toOpen[0].focus = true;
openWindow(toOpen[0]);
}
}
function setFavorites(id, favorites) {
if (windowData[id]) {
windowData[id].favorites = favorites;
scheduleSave();
}
updateTitle(id);
if (nwProcessId)
connection.call(0, {id: id, favorites: favorites, type: "setFavorites"});
}
function updateTitle(id) {
var winData = windowData[id];
var win = allWindows[id];
if (win && winData) {
var favs = winData.favorites;
if (winData.isRemote) {
win.displayName = "Remote " + /[^\/]*\/?$/.exec(winData.name || "")[0];
} else {
win.displayName = /[^\/]*\/?$/.exec(favs[0] || "")[0];
}
}
}
function openWindowForPath(path, forceNew) {
var data = windowManager.findWindowForPath(path);
if (!data && !forceNew)
data = {id : "latest", isRemote: false, isEmpty: true};
data.focus = true;
data.filePath = path;
openWindow(data);
}
function registerWindow(win, id) {
if (typeof id == "string") {
if (id[0] == "{") {
win.options = JSON.parse(id);
id = win.options.id;
}
}
if (!win.options)
win.options = {id: id};
allWindows[id] = win;
activeWindowId = id;
function mainCloseHandler() {
if (win.listeners("close").length == 1) {
onClose(id);
win.close(true);
}
}
// make sure only one mainCloseHandler is attached even after calling win.reload()
win.listeners("close").forEach(function(f) {
if (f.name == "mainCloseHandler")
win.removeListener("close", f);
});
win.on("close", mainCloseHandler);
win.on("focus", function() {
onFocus(id);
});
win.on("savePosition", function() {
savePosition(id);
});
if (id != "root")
scheduleSave();
if (win.options.nwProcessId && !allWindows.root)
nwProcessId = win.options.nwProcessId;
if (nwProcessId)
updateWindowData(win.options);
if (!connection)
connection = new MsgChannel();
if (!logStream) {
try {
logStream = fs.createWriteStream(settingDir + '/log.txt', nwProcessId ? {flags: 'a'} : undefined);
} catch (e) {}
}
// if (id != "root") {
// setTimeout(function() {
// windowManager.registerWindow();
// });
// }
}
function onClose(id) {
delete allWindows[id];
var winState = windowData[id];
if (nwProcessId) {
return connection.call(0, {type: "onClose", id: id});
}
if (Object.keys(allWindows).length <= 1 && allWindows.root) {
if (process.platform != "darwin" || allWindows.root.quitting) {
allWindows.root.close(true);
allWindows.root.quitting = true;
}
}
// Only save state when not quitting the application
if (allWindows.root && !allWindows.root.quitting) {
winState.isOpen = false;
savestate();
}
if (activeWindowId == id)
activeWindowId = 0;
}
function quit() {
if (nwProcessId)
return connection.call(0, {type: "quit"});
var active = allWindows[activeWindowId];
forEachWindow(function(data, win) {
if (win && win != active && win.hide)
win.hide();
});
if (active) {
active.emit("askForQuit", true);
}
}
function quitAll(){
if (nwProcessId)
return connection.call(0, {type: "quitAll"});
if (allWindows.root)
allWindows.root.quitting = true;
forEachWindow(function(data, win) {
if (win && win.emit) win.emit("saveAndQuit");
});
}
function unquit(){
if (nwProcessId)
return connection.call(0, {type: "unquit"});
var active = allWindows[activeWindowId];
forEachWindow(function(data, win) {
if (win && win != active && win.show)
win.show();
});
active && active.show();
}
function onFocus(id) {
if (nwProcessId)
return connection.call(0, {type: "onFocus", id: id});
activeWindowId = id;
if (windowData[id])
windowData[id].time = Date.now();
}
function onShowWindow(win) {
if (win.options && win.options.focus) {
delete win.options.focus;
win.focus();
}
if (win.$onShow) {
win.$onShow(null, win);
win.$onShow = undefined;
}
}
function savePosition(id, position) {
var win = allWindows[id];
if (!position) {
if (!win || win.isMinimized)
return;
position = [win.x, win.y, win.width, win.height];
}
if (nwProcessId)
return connection.call(0, {type: "savePosition", id: id, position: position});
var winData = windowData[id];
if (winData) {
winData.position = position;
scheduleSave();
}
}
function openQuitSure(callback){
}
function openWindow(options, callback) {
if (nwProcessId)
return connection.call(0, {type: "openWindow", options: options}, callback);
options = validateWindowOptions(options);
var id = options.id;
if (allWindows[id]) {
if (options.duplicate && id == activeWindowId) {
id = options.id = options.id + ".1";
} else {
win = allWindows[id];
win.emit("focusWindow");
if (options.filePath)
win.emit("openFile", {path: options.filePath});
return callback && callback();
}
}
var window = allWindows.root.window;
var nwGui = window.require("nw.gui");
var isNewInstance = false;
var inProcessWindows = 0;
for (var i in allWindows) {
if (allWindows[i].options && allWindows[i].options.nwProcessId === 0) {
if (++inProcessWindows >= MAX_SAME_PROCESS) {
isNewInstance = true;
break;
}
}
}
options.nwProcessId = isNewInstance ? processIdCounter++ : 0;
var url = "index.html?id=" + (isNewInstance ? escape(JSON.stringify(options)) : id);
if (options.reset) {
url += "&reset=state";
delete options.reset;
}
var sc = window.screen;
var ah = sc.availHeight, aw = sc.availWidth, ax = sc.availLeft, ay = sc.availTop;
var h, w, x, y;
var position = options.position;
if (!position) {
w = Math.min(1200, Math.round(0.7 * aw));
h = Math.min(960, Math.round(0.8 * ah));
x = Math.round(ax + (aw - w)/2);
y = Math.round(ay + (ah - h)/2);
} else {
x = Math.max(ax - 10, position[0]);
y = Math.max(ay - 10, position[1]);
w = Math.min(aw, position[2]);
h = Math.min(ah, position[3]);
}
var win = nwGui.Window.open(url, {
"new-instance": !!isNewInstance,
height: h,
width: w,
left: x,
top: y,
show: false,
frame: false,
toolbar: false,
title: "Cloud9",
icon: "icon.png",
"win_bg": "#000000"
});
win.moveTo(x, y);
win.options = options;
allWindows[id] = win;
win.$onShow = callback;
if (isNewInstance) {
win.emit = function() {
connection.call(win.options.nwProcessId, {
type: "winEvent",
id: id,
arguments: Array.apply(null, arguments)
});
};
}
updateWindowData(options);
}
function updateWindowData(options) {
var id = options.id;
var winState = windowData[id] || {};
winState.id = id;
if (!winState.favorites)
winState.favorites = [];
winState.isRemote = options.isRemote;
winState.time = Date.now();
winState.isOpen = true;
if (winState.isRemote) {
winState.name = options.name;
}
windowData[id] = winState;
}
function validateWindowOptions(options) {
options = options || {};
if (options.isRemote) {
options.id = "remote/" + options.name;
} else {
var windows = Object.keys(windowData).map(function(id) {
return windowData[id];
}).filter(function(x) {
return !x.isRemote;
}).sort(function(a, b) {
if (Boolean(b.isOpen) !== Boolean(a.isOpen))
return b.isOpen ? 1 : -1;
if (b.isOpen || (a.favorites.length && b.favorites.length))
return b.time - a.time;
return b.favorites.length ? 1 : -1;
});
if (options.id == "latest") {
for (var i = 0; i < windows.length; i++) {
var d = windows[i];
if (options.isOpen === false && d.isOpen)
continue;
if (options.isRemote === false && d.isRemote)
continue;
if (options.isEmpty && d.favorites.length)
continue;
d.filePath = options.filePath;
options = d;
break;
}
if (options.id == "latest")
options.id = 0;
}
if (!options.id) {
var id = 0;
if (windows.length > MAX_RECENT_WINDOWS) {
var last = windows[windows.length - 1];
id = last.isOpen ? 0 : last.id;
}
if (!id) {
do id++;
while (windowData[id]);
}
if (!options.stateSettings)
options.reset = true;
options.id = id;
delete windowData[id];
}
}
if (windowData[options.id] && !options.position)
options.position = windowData[options.id].position;
return options;
}
function readJSONFile(path) {
try {
var data = fs.readFileSync(path, "utf8");
return JSON.parse(data) || {};
}
catch(e){
console.log("Could not parse JSON", e);
return {};
}
}
function getRecentWindows(callback) {
if (nwProcessId && callback)
return connection.call(0, {type: "getRecentWindows"}, callback);
var names = Object.create(null);
var recentWindows = Object.keys(windowData).map(function(id) {
var data = windowData[id];
var name = data.name;
if (!name && data.favorites[0])
name = data.favorites[0].match(/[^\/]*\/?$/)[0];
if (!name)
name = "[Untitled" + (id < 10 ? " " : "") + id + "]";
// todo better handling for duplicate windows
if (names[name]) {
name += " (" + names[name] + ")";
names[name]++;
} else {
names[name] = 1;
}
return {
name: name,
id: id,
time: data.time,
isRemote: !!data.isRemote,
isOpen: !!data.isOpen,
isEmpty: !data.isRemote && !data.favorites.length,
favorites: data.favorites.slice()
};
});
callback && callback(null, recentWindows);
return recentWindows;
}
function registerSharedModule(name, construct) {
if (nwProcessId) return;
var root = allWindows.root;
if (!root.modules)
root.modules = Object.create(null);
if (!root.modules[name]) {
root.modules[name] = construct(windowManager, connection);
//@nightwing why eval?
// root.modules[name] = "(" + global.eval("(" + construct + ")")(windowManager, connection);
}
}
var saveTimer, saving;
function savestate() {
if (nwProcessId)
return connection.call(0, {type: "windowManagerSave"});
if (saving)
return scheduleSave();
var content = JSON.stringify(windowData, function(x,y) { return y || undefined});
saving = true;
var tmp = windowManager.statePath + "~";
fs.writeFile(tmp, content, "utf8", function(err, result) {
saving = false;
fs.rename(tmp, windowManager.statePath, function(err, result) {
saving = false;
});
});
}