This repository has been archived by the owner on Sep 6, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7.6k
/
LiveDevelopment.js
1553 lines (1325 loc) · 54 KB
/
LiveDevelopment.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
/*
* Copyright (c) 2012 - present Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*global open */
/**
* LiveDevelopment manages the Inspector, all Agents, and the active LiveDocument
*
* __STARTING__
*
* To start a session call `open`. This will read the currentDocument from brackets,
* launch the LiveBrowser (currently Chrome) with the remote debugger port open,
* establish the Inspector connection to the remote debugger, and finally load all
* agents.
*
* __STOPPING__
*
* To stop a session call `close`. This will close the active browser window,
* disconnect the Inspector, unload all agents, and clean up.
*
* __STATUS__
*
* Status updates are dispatched as `statusChange` jQuery events. The status
* is passed as the first parameter and the reason for the change as the second
* parameter. Currently only the "Inactive" status supports the reason parameter.
* The status codes are:
*
* -1: Error
* 0: Inactive
* 1: Connecting to the remote debugger
* 2: Loading agents
* 3: Active
* 4: Out of sync
* 5: Sync error
*
* The reason codes are:
* - null (Unknown reason)
* - "explicit_close" (LiveDevelopment.close() was called)
* - "navigated_away" (The browser changed to a location outside of the project)
* - "detached_target_closed" (The tab or window was closed)
* - "detached_replaced_with_devtools" (The developer tools were opened in the browser)
*/
define(function LiveDevelopment(require, exports, module) {
"use strict";
require("utils/Global");
var _ = require("thirdparty/lodash");
// Status Codes
var STATUS_ERROR = exports.STATUS_ERROR = -1;
var STATUS_INACTIVE = exports.STATUS_INACTIVE = 0;
var STATUS_CONNECTING = exports.STATUS_CONNECTING = 1;
var STATUS_LOADING_AGENTS = exports.STATUS_LOADING_AGENTS = 2;
var STATUS_ACTIVE = exports.STATUS_ACTIVE = 3;
var STATUS_OUT_OF_SYNC = exports.STATUS_OUT_OF_SYNC = 4;
var STATUS_SYNC_ERROR = exports.STATUS_SYNC_ERROR = 5;
var Async = require("utils/Async"),
CSSUtils = require("language/CSSUtils"),
Dialogs = require("widgets/Dialogs"),
DefaultDialogs = require("widgets/DefaultDialogs"),
DocumentManager = require("document/DocumentManager"),
EditorManager = require("editor/EditorManager"),
EventDispatcher = require("utils/EventDispatcher"),
FileServer = require("LiveDevelopment/Servers/FileServer").FileServer,
FileSystemError = require("filesystem/FileSystemError"),
FileUtils = require("file/FileUtils"),
LiveDevelopmentUtils = require("LiveDevelopment/LiveDevelopmentUtils"),
LiveDevServerManager = require("LiveDevelopment/LiveDevServerManager"),
MainViewManager = require("view/MainViewManager"),
NativeApp = require("utils/NativeApp"),
PreferencesDialogs = require("preferences/PreferencesDialogs"),
ProjectManager = require("project/ProjectManager"),
Strings = require("strings"),
StringUtils = require("utils/StringUtils"),
UserServer = require("LiveDevelopment/Servers/UserServer").UserServer,
WebSocketTransport = require("LiveDevelopment/transports/WebSocketTransport"),
PreferencesManager = require("preferences/PreferencesManager"),
HealthLogger = require("utils/HealthLogger");
// Inspector
var Inspector = require("LiveDevelopment/Inspector/Inspector");
// Documents
var CSSDocument = require("LiveDevelopment/Documents/CSSDocument"),
CSSPreprocessorDocument = require("LiveDevelopment/Documents/CSSPreprocessorDocument"),
HTMLDocument = require("LiveDevelopment/Documents/HTMLDocument"),
JSDocument = require("LiveDevelopment/Documents/JSDocument");
// Document errors
var SYNC_ERROR_CLASS = "live-preview-sync-error";
// Agents
var CSSAgent = require("LiveDevelopment/Agents/CSSAgent");
var agents = {
"console" : require("LiveDevelopment/Agents/ConsoleAgent"),
"remote" : require("LiveDevelopment/Agents/RemoteAgent"),
"network" : require("LiveDevelopment/Agents/NetworkAgent"),
"dom" : require("LiveDevelopment/Agents/DOMAgent"),
"css" : CSSAgent,
"script" : require("LiveDevelopment/Agents/ScriptAgent"),
"highlight" : require("LiveDevelopment/Agents/HighlightAgent"),
"goto" : require("LiveDevelopment/Agents/GotoAgent"),
"edit" : require("LiveDevelopment/Agents/EditAgent")
};
// construct path to launch.html
// window location is can be one of the following:
// Installed: /path/to/Brackets.app/Contents/www/index.html
// Installed, dev: /path/to/Brackets.app/Contents/dev/src/index.html
// Installed, dev, test: /path/to/Brackets.app/Contents/dev/test/SpecRunner.html
// Arbitrary git repo: /path/to/brackets/src/index.html
// Arbitrary git repo, test: /path/to/brackets/test/SpecRunner.html
var launcherUrl = window.location.pathname;
// special case for test/SpecRunner.html since we can't tell how requirejs
// baseUrl is configured dynamically
launcherUrl = launcherUrl.replace("/test/SpecRunner.html", "/src/index.html");
launcherUrl = launcherUrl.substr(0, launcherUrl.lastIndexOf("/")) + "/LiveDevelopment/launch.html";
launcherUrl = window.location.origin + launcherUrl;
// Some agents are still experimental, so we don't enable them all by default
// However, extensions can enable them by calling enableAgent().
// This object is used as a set (thus all properties have the value 'true').
// Property names should match property names in the 'agents' object.
var _enabledAgentNames = {
"console" : true,
"remote" : true,
"network" : true,
"css" : true,
"highlight" : true
};
/**
* Store the names (matching property names in the 'agent' object) of agents that we've loaded
* @type {string}
*/
var _loadedAgentNames = [];
/**
* Live Preview current Document info
* @type {HTMLDocument}
*/
var _liveDocument;
/**
* Related Live Documents
* @type {Object.<string: (HTMLDocument|CSSDocument)>}
*/
var _relatedDocuments = {};
/**
* Promise returned for each call to open()
* @type {jQuery.Deferred}
*/
var _openDeferred;
/**
* Promise returned for each call to close()
* @type {jQuery.Deferred}
*/
var _closeDeferred;
// Disallow re-entrancy of loadAgents()
var _loadAgentsPromise;
/**
* Current live preview server
* @type {BaseServer}
*/
var _server;
/**
* @private
* Handles of registered servers
*/
var _regServers = [];
PreferencesManager.definePreference("livedev.wsPort", "number", 8125, {
description: Strings.DESCRIPTION_LIVEDEV_WEBSOCKET_PORT
});
PreferencesManager.definePreference("livedev.enableReverseInspect", "boolean", true, {
description: Strings.DESCRIPTION_LIVEDEV_ENABLE_REVERSE_INSPECT
});
function _isPromisePending(promise) {
return promise && promise.state() === "pending";
}
/** Get the current document from the document manager
* _adds extension, url and root to the document
*/
function _getCurrentDocument() {
return DocumentManager.getCurrentDocument();
}
/** Determine which document class should be used for a given document
* @param {Document} document
*/
function _classForDocument(doc) {
switch (doc.getLanguage().getId()) {
case "less":
case "scss":
return CSSPreprocessorDocument;
case "css":
return CSSDocument;
case "javascript":
return exports.config.experimental ? JSDocument : null;
}
if (LiveDevelopmentUtils.isHtmlFileExt(doc.file.fullPath)) {
return HTMLDocument;
}
return null;
}
function getLiveDocForPath(path) {
if (!_server) {
return undefined;
}
return _server.get(path);
}
function getLiveDocForEditor(editor) {
if (!editor) {
return null;
}
return getLiveDocForPath(editor.document.file.fullPath);
}
/**
* @private
* Clears errors from line number gutter (line class)
* @param {HTMLDocument|CSSDocument} liveDocument
*/
function _doClearErrors(liveDocument) {
var lineHandle;
if (!liveDocument.editor ||
!liveDocument._errorLineHandles ||
!liveDocument._errorLineHandles.length) {
return;
}
liveDocument.editor._codeMirror.operation(function () {
while (true) {
// Iterate over all lines that were previously marked with an error
lineHandle = liveDocument._errorLineHandles.pop();
if (!lineHandle) {
break;
}
liveDocument.editor._codeMirror.removeLineClass(lineHandle, "wrap", SYNC_ERROR_CLASS);
}
});
}
/**
* @private
* Make a message to direct users to the troubleshooting page
* @param {string} msg Original message
* @return {string} Original message plus link to troubleshooting page.
*/
function _makeTroubleshootingMessage(msg) {
return msg + " " + StringUtils.format(Strings.LIVE_DEVELOPMENT_TROUBLESHOOTING, brackets.config.troubleshoot_url);
}
/**
* @private
* Close a live document
*/
function _closeDocument(liveDocument) {
_doClearErrors(liveDocument);
liveDocument.close();
if (liveDocument.editor) {
liveDocument.editor.off(".livedev");
}
liveDocument.off(".livedev");
}
/**
* Removes the given CSS/JSDocument from _relatedDocuments. Signals that the
* given file is no longer associated with the HTML document that is live (e.g.
* if the related file has been deleted on disk).
*/
function _closeRelatedDocument(liveDoc) {
if (_relatedDocuments[liveDoc.doc.url]) {
delete _relatedDocuments[liveDoc.doc.url];
}
if (_server) {
_server.remove(liveDoc);
}
_closeDocument(liveDoc);
}
/**
* Update the status. Triggers a statusChange event.
* @param {number} status new status
* @param {?string} closeReason Optional string key suffix to display to
* user when closing the live development connection (see LIVE_DEV_* keys)
*/
function _setStatus(status, closeReason) {
// Don't send a notification when the status didn't actually change
if (status === exports.status) {
return;
}
exports.status = status;
var reason = status === STATUS_INACTIVE ? closeReason : null;
exports.trigger("statusChange", status, reason);
}
/**
* @private
* Event handler for live document errors. Displays error status in the editor gutter.
* @param {$.Event} event
* @param {HTMLDocument|CSSDocument} liveDocument
* @param {Array.<{token: SimpleNode, startPos: Pos, endPos: Pos}>} errors
*/
function _handleLiveDocumentStatusChanged(liveDocument) {
var startLine,
endLine,
i,
lineHandle,
status = (liveDocument.errors.length) ? STATUS_SYNC_ERROR : STATUS_ACTIVE;
_setStatus(status);
if (!liveDocument.editor) {
return;
}
// Buffer addLineClass DOM changes in a CodeMirror operation
liveDocument.editor._codeMirror.operation(function () {
// Remove existing errors before marking new ones
_doClearErrors(liveDocument);
liveDocument._errorLineHandles = liveDocument._errorLineHandles || [];
liveDocument.errors.forEach(function (error) {
startLine = error.startPos.line;
endLine = error.endPos.line;
for (i = startLine; i < endLine + 1; i++) {
lineHandle = liveDocument.editor._codeMirror.addLineClass(i, "wrap", SYNC_ERROR_CLASS);
liveDocument._errorLineHandles.push(lineHandle);
}
});
});
}
/**
* @private
* Close all live documents
*/
function _closeDocuments() {
if (_liveDocument) {
_closeDocument(_liveDocument);
_liveDocument = undefined;
}
Object.keys(_relatedDocuments).forEach(function (url) {
_closeDocument(_relatedDocuments[url]);
delete _relatedDocuments[url];
});
// Clear all documents from request filtering
if (_server) {
_server.clear();
}
}
/**
* @private
* Create a live version of a Brackets document
* @param {Document} doc Current document
* @param {Editor} editor Current editor
* @return {?(HTMLDocument|CSSDocument)}
*/
function _createDocument(doc, editor) {
var DocClass = _classForDocument(doc),
liveDocument = new DocClass(doc, editor);
if (!DocClass) {
return null;
}
liveDocument.on("statusChanged.livedev", function () {
_handleLiveDocumentStatusChanged(liveDocument);
});
return liveDocument;
}
/**
* @private
* Initialize `_liveDocument`.
* @param {Document} doc Current document
*/
function _createLiveDocumentForFrame(doc) {
// create live document
doc._ensureMasterEditor();
_liveDocument = _createDocument(doc, doc._masterEditor);
_server.add(_liveDocument);
}
/** Enable an agent. Takes effect next time a connection is made. Does not affect
* current live development sessions.
*
* @param {string} name of agent to enable
*/
function enableAgent(name) {
if (agents.hasOwnProperty(name) && !_enabledAgentNames.hasOwnProperty(name)) {
_enabledAgentNames[name] = true;
}
}
/** Disable an agent. Takes effect next time a connection is made. Does not affect
* current live development sessions.
*
* @param {string} name of agent to disable
*/
function disableAgent(name) {
if (_enabledAgentNames.hasOwnProperty(name)) {
delete _enabledAgentNames[name];
}
}
/** Documents are considered to be out-of-sync if they are dirty and
* do not have "update while editing" support
* @param {Document} doc
*/
function _docIsOutOfSync(doc) {
var liveDoc = _server && _server.get(doc.file.fullPath),
isLiveEditingEnabled = liveDoc && liveDoc.isLiveEditingEnabled();
return doc.isDirty && !isLiveEditingEnabled;
}
/** Triggered by Inspector.error */
function _onError(event, error, msgData) {
var message;
// Sometimes error.message is undefined
if (!error.message) {
console.warn("Expected a non-empty string in error.message, got this instead:", error.message);
message = JSON.stringify(error);
} else {
message = error.message;
}
// Remove "Uncaught" from the beginning to avoid the inspector popping up
if (message && message.substr(0, 8) === "Uncaught") {
message = message.substr(9);
}
// Additional information, like exactly which parameter could not be processed.
var data = error.data;
if (Array.isArray(data)) {
message += "\n" + data.join("\n");
}
// Show the message, but include the error object for further information (e.g. error code)
console.error(message, error, msgData);
}
function _styleSheetAdded(event, url) {
var path = _server && _server.urlToPath(url),
exists = !!_relatedDocuments[url];
// path may be null if loading an external stylesheet.
// Also, the stylesheet may already exist and be reported as added twice
// due to Chrome reporting added/removed events after incremental changes
// are pushed to the browser
if (!path || exists) {
return;
}
var docPromise = DocumentManager.getDocumentForPath(path);
docPromise.done(function (doc) {
if ((_classForDocument(doc) === CSSDocument ||
_classForDocument(doc) === CSSPreprocessorDocument) &&
(!_liveDocument || (doc !== _liveDocument.doc))) {
// The doc may already have an editor (e.g. starting live preview from an css file),
// so pass the editor if any
var liveDoc = _createDocument(doc, doc._masterEditor);
if (liveDoc) {
_server.add(liveDoc);
_relatedDocuments[doc.url] = liveDoc;
liveDoc.on("deleted.livedev", function (event, liveDoc) {
_closeRelatedDocument(liveDoc);
});
}
}
});
}
/** Unload the agents */
function unloadAgents() {
_loadedAgentNames.forEach(function (name) {
agents[name].unload();
});
_loadedAgentNames = [];
}
/**
* @private
* Invoke a no-arg method on an inspector agent
* @param {string} name Agent name
* @param {stirng} methodName Method name to call on the agent
*/
function _invokeAgentMethod(name, methodName) {
var oneAgentPromise;
if (agents[name] && agents[name][methodName]) {
oneAgentPromise = agents[name][methodName].call();
}
if (!oneAgentPromise) {
oneAgentPromise = new $.Deferred().resolve().promise();
} else {
oneAgentPromise.fail(function () {
console.error(methodName + " failed on agent", name);
});
}
return oneAgentPromise;
}
function getEnabledAgents() {
var enabledAgents;
// Select agents to use
if (exports.config.experimental) {
// load all agents
enabledAgents = agents;
} else {
// load only enabled agents
enabledAgents = _enabledAgentNames;
}
return Object.keys(enabledAgents);
}
/**
* @private
* Setup agents that need inspector domains enabled before loading
*/
function _enableAgents() {
// enable agents in parallel
return Async.doInParallel(
getEnabledAgents(),
function (name) {
return _invokeAgentMethod(name, "enable");
},
true
);
}
/** Load the agents */
function loadAgents() {
// If we're already loading agents return same promise
if (_loadAgentsPromise) {
return _loadAgentsPromise;
}
var result = new $.Deferred(),
allAgentsPromise;
_loadAgentsPromise = result.promise();
_setStatus(STATUS_LOADING_AGENTS);
// load agents in parallel
allAgentsPromise = Async.doInParallel(
getEnabledAgents(),
function (name) {
return _invokeAgentMethod(name, "load").done(function () {
_loadedAgentNames.push(name);
});
},
true
);
// wrap agent loading with a timeout
allAgentsPromise = Async.withTimeout(allAgentsPromise, 10000);
allAgentsPromise.done(function () {
var doc = (_liveDocument) ? _liveDocument.doc : null;
if (doc) {
var status = STATUS_ACTIVE;
if (_docIsOutOfSync(doc)) {
status = STATUS_OUT_OF_SYNC;
}
_setStatus(status);
result.resolve();
} else {
result.reject();
}
});
allAgentsPromise.fail(result.reject);
_loadAgentsPromise
.fail(function () {
// show error loading live dev dialog
_setStatus(STATUS_ERROR);
Dialogs.showModalDialog(
Dialogs.DIALOG_ID_ERROR,
Strings.LIVE_DEVELOPMENT_ERROR_TITLE,
_makeTroubleshootingMessage(Strings.LIVE_DEV_LOADING_ERROR_MESSAGE)
);
})
.always(function () {
_loadAgentsPromise = null;
});
return _loadAgentsPromise;
}
/**
* @private
* Determine an index file that can be used to start Live Development.
* This function will inspect all files in a project to find the closest index file
* available for currently opened document. We are searching for these files:
* - index.html
* - index.htm
*
* If the project is configured with a custom base url for live development, then
* the list of possible index files is extended to contain these index files too:
* - index.php
* - index.php3
* - index.php4
* - index.php5
* - index.phtm
* - index.phtml
* - index.cfm
* - index.cfml
* - index.asp
* - index.aspx
* - index.jsp
* - index.jspx
* - index.shm
* - index.shml
*
* If a file was found, the promise will be resolved with the full path to this file. If no file
* was found in the whole project tree, the promise will be resolved with null.
*
* @return {jQuery.Promise} A promise that is resolved with a full path
* to a file if one could been determined, or null if there was no suitable index
* file.
*/
function _getInitialDocFromCurrent() {
var doc = _getCurrentDocument(),
refPath,
i;
// Is the currently opened document already a file we can use for Live Development?
if (doc) {
refPath = doc.file.fullPath;
if (LiveDevelopmentUtils.isStaticHtmlFileExt(refPath) || LiveDevelopmentUtils.isServerHtmlFileExt(refPath)) {
return new $.Deferred().resolve(doc);
}
}
var result = new $.Deferred();
var baseUrl = ProjectManager.getBaseUrl(),
hasOwnServerForLiveDevelopment = (baseUrl && baseUrl.length);
ProjectManager.getAllFiles().done(function (allFiles) {
var projectRoot = ProjectManager.getProjectRoot().fullPath,
containingFolder,
indexFileFound = false,
stillInProjectTree = true;
if (refPath) {
containingFolder = FileUtils.getDirectoryPath(refPath);
} else {
containingFolder = projectRoot;
}
var filteredFiltered = allFiles.filter(function (item) {
var parent = FileUtils.getParentPath(item.fullPath);
return (containingFolder.indexOf(parent) === 0);
});
var filterIndexFile = function (fileInfo) {
if (fileInfo.fullPath.indexOf(containingFolder) === 0) {
if (FileUtils.getFilenameWithoutExtension(fileInfo.name) === "index") {
if (hasOwnServerForLiveDevelopment) {
if ((LiveDevelopmentUtils.isServerHtmlFileExt(fileInfo.name)) ||
(LiveDevelopmentUtils.isStaticHtmlFileExt(fileInfo.name))) {
return true;
}
} else if (LiveDevelopmentUtils.isStaticHtmlFileExt(fileInfo.name)) {
return true;
}
} else {
return false;
}
}
};
while (!indexFileFound && stillInProjectTree) {
i = _.findIndex(filteredFiltered, filterIndexFile);
// We found no good match
if (i === -1) {
// traverse the directory tree up one level
containingFolder = FileUtils.getParentPath(containingFolder);
// Are we still inside the project?
if (containingFolder.indexOf(projectRoot) === -1) {
stillInProjectTree = false;
}
} else {
indexFileFound = true;
}
}
if (i !== -1) {
DocumentManager.getDocumentForPath(filteredFiltered[i].fullPath).then(result.resolve, result.resolve);
return;
}
result.resolve(null);
});
return result.promise();
}
/**
* If the current editor is for a CSS preprocessor file, then add it to the style sheet
* so that we can track cursor positions in the editor to show live preview highlighting.
* For normal CSS we only do highlighting from files we know for sure are referenced by the
* current live preview document, but for preprocessors we just assume that any preprocessor
* file you edit is probably related to the live preview.
*
* @param {Event} event (unused)
* @param {Editor} current Current editor
* @param {Editor} previous Previous editor
*
*/
function onActiveEditorChange(event, current, previous) {
if (previous && previous.document &&
CSSUtils.isCSSPreprocessorFile(previous.document.file.fullPath)) {
var prevDocUrl = _server && _server.pathToUrl(previous.document.file.fullPath);
if (_relatedDocuments && _relatedDocuments[prevDocUrl]) {
_closeRelatedDocument(_relatedDocuments[prevDocUrl]);
}
}
if (current && current.document &&
CSSUtils.isCSSPreprocessorFile(current.document.file.fullPath)) {
var docUrl = _server && _server.pathToUrl(current.document.file.fullPath);
_styleSheetAdded(null, docUrl);
}
}
/**
* @private
* While still connected to the Inspector, do cleanup for agents,
* documents and server.
* @param {boolean} doCloseWindow Use true to close the window/tab in the browser
* @return {jQuery.Promise} A promise that is always resolved
*/
function _doInspectorDisconnect(doCloseWindow) {
var closePromise,
deferred = new $.Deferred(),
connected = Inspector.connected();
EditorManager.off("activeEditorChange", onActiveEditorChange);
Inspector.Page.off(".livedev");
Inspector.off(".livedev");
// Wait if agents are loading
if (_loadAgentsPromise) {
_loadAgentsPromise.always(unloadAgents);
} else {
unloadAgents();
}
// Close live documents
_closeDocuments();
if (_server) {
// Stop listening for requests when disconnected
_server.stop();
// Dispose server
_server = null;
}
if (doCloseWindow && connected) {
closePromise = Inspector.Runtime.evaluate("window.open('', '_self').close();");
// Add a timeout to continue cleanup if Inspector does not respond
closePromise = Async.withTimeout(closePromise, 5000);
} else {
closePromise = new $.Deferred().resolve();
}
// Disconnect WebSocket if connected
closePromise.always(function () {
if (Inspector.connected()) {
Inspector.disconnect().always(deferred.resolve);
} else {
deferred.resolve();
}
});
return deferred.promise();
}
/**
* @private
* Close the connection and the associated window asynchronously
* @param {boolean} doCloseWindow Use true to close the window/tab in the browser
* @param {?string} reason Optional string key suffix to display to user (see LIVE_DEV_* keys)
* @return {jQuery.Promise} Always return a resolved promise once the connection is closed
*/
function _close(doCloseWindow, reason) {
WebSocketTransport.closeWebSocketServer();
if (_closeDeferred) {
return _closeDeferred;
} else {
_closeDeferred = new $.Deferred();
_closeDeferred.always(function () {
_closeDeferred = null;
});
}
var promise = _closeDeferred.promise();
/*
* Finish closing the live development connection, including setting
* the status accordingly.
*/
function cleanup() {
// Need to do this in order to trigger the corresponding CloseLiveBrowser cleanups required on
// the native Mac side
var closeDeferred = (brackets.platform === "mac") ? NativeApp.closeLiveBrowser() : $.Deferred().resolve();
closeDeferred.done(function () {
_setStatus(STATUS_INACTIVE, reason || "explicit_close");
// clean-up registered servers
_regServers.forEach(function (server) {
LiveDevServerManager.removeServer(server);
});
_regServers = [];
_closeDeferred.resolve();
}).fail(function (err) {
if (err) {
reason += " (" + err + ")";
}
_setStatus(STATUS_INACTIVE, reason || "explicit_close");
_closeDeferred.resolve();
});
}
if (_isPromisePending(_openDeferred)) {
// Reject calls to open if requests are still pending
_openDeferred.reject();
}
if (exports.status === STATUS_INACTIVE) {
// Ignore close if status is inactive
_closeDeferred.resolve();
} else {
_doInspectorDisconnect(doCloseWindow).always(cleanup);
}
return promise;
}
// WebInspector Event: Page.frameNavigated
function _onFrameNavigated(event, res) {
// res = {frame}
var url = res.frame.url,
baseUrl,
baseUrlRegExp;
// Only check domain of root frame (with undefined parentId)
if (res.frame.parentId) {
return;
}
// Any local file is OK
if (url.match(/^file:\/\//i) || !_server) {
return;
}
// Need base url to build reg exp
baseUrl = _server.getBaseUrl();
if (!baseUrl) {
return;
}
// Test that url is within site
baseUrlRegExp = new RegExp("^" + StringUtils.regexEscape(baseUrl), "i");
if (!url.match(baseUrlRegExp)) {
// No longer in site, so terminate live dev, but don't close browser window
_close(false, "navigated_away");
}
}
/**
* @private
* Triggered by unexpected Inspector disconnect event
*/
function _onDisconnect(event) {
_close(false, "closed_unknown_reason");
}
function _onDetached(event, res) {
var closeReason;
if (res && res.reason) {
// Get the explanation from res.reason, e.g. "replaced_with_devtools", "target_closed", "canceled_by_user"
// Examples taken from https://chromiumcodereview.appspot.com/10947037/patch/12001/13004
// However, the link refers to the Chrome Extension API, it may not apply 100% to the Inspector API
// Prefix with "detached_" to create a quasi-namespace for Chrome's reasons
closeReason = "detached_" + res.reason;
}
_close(false, closeReason);
}
/**
* Unload and reload agents
* @return {jQuery.Promise} Resolves once the agents are loaded
*/
function reconnect() {
if (_loadAgentsPromise) {
// Agents are already loading, so don't unload
return _loadAgentsPromise;
}
unloadAgents();
// Clear any existing related documents before we reload the agents.
// We need to recreate them for the reloaded document due to some
// desirable side-effects (see #7606). Eventually, we should simplify
// the way we get that behavior.
_.forOwn(_relatedDocuments, function (relatedDoc) {
_closeRelatedDocument(relatedDoc);
});
return loadAgents();
}
/** reload the live preview */
function reload() {
// Unload and reload agents before reloading the page
// Some agents (e.g. DOMAgent and RemoteAgent) require us to
// navigate to the page first before loading can complete.
// To accomodate this, we load all agents (in reconnect())
// and navigate in parallel.
reconnect();
// Reload HTML page