forked from jsantell/firefox-patches
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1077464-console-profile.patch
3412 lines (3109 loc) · 131 KB
/
1077464-console-profile.patch
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
From: Jordan Santell <[email protected]>
Date: Tue, 14 Apr 2015 08:58:58 -0700
Subject: Bug 1077464 - Wire console.profile/profileEnd to the new performance tool. Move most of the recording-model logic from the front end into the PerformanceFront and PerformanceActorConnection so it can manage recordings without the front end being viewed. r=vp,jryans,pbrosset
diff --git a/browser/devtools/animationinspector/test/head.js b/browser/devtools/animationinspector/test/head.js
index b37b1c0..519463d 100644
--- a/browser/devtools/animationinspector/test/head.js
+++ b/browser/devtools/animationinspector/test/head.js
@@ -115,37 +115,61 @@ let selectNode = Task.async(function*(data, inspector, reason="test") {
nodeFront = yield getNodeFront(data, inspector);
}
let updated = inspector.once("inspector-updated");
inspector.selection.setNodeFront(nodeFront, reason);
yield updated;
});
/**
+ * Takes an Inspector panel that was just created, and waits
+ * for a "inspector-updated" event as well as the animation inspector
+ * sidebar to be ready. Returns a promise once these are completed.
+ *
+ * @param {InspectorPanel} inspector
+ * @return {Promise}
+ */
+let waitForAnimationInspectorReady = Task.async(function*(inspector) {
+ let win = inspector.sidebar.getWindowForTab("animationinspector");
+ let updated = inspector.once("inspector-updated");
+
+ // In e10s, if we wait for underlying toolbox actors to
+ // load (by setting gDevTools.testing to true), we miss the "animationinspector-ready"
+ // event on the sidebar, so check to see if the iframe
+ // is already loaded.
+ let tabReady = win.document.readyState === "complete" ?
+ promise.resolve() :
+ inspector.sidebar.once("animationinspector-ready");
+
+ return promise.all([updated, tabReady]);
+});
+
+/**
* Open the toolbox, with the inspector tool visible and the animationinspector
* sidebar selected.
* @return a promise that resolves when the inspector is ready
*/
let openAnimationInspector = Task.async(function*() {
let target = TargetFactory.forTab(gBrowser.selectedTab);
info("Opening the toolbox with the inspector selected");
let toolbox = yield gDevTools.showToolbox(target, "inspector");
- yield waitForToolboxFrameFocus(toolbox);
info("Switching to the animationinspector");
let inspector = toolbox.getPanel("inspector");
- let initPromises = [
- inspector.once("inspector-updated"),
- inspector.sidebar.once("animationinspector-ready")
- ];
+
+ let panelReady = waitForAnimationInspectorReady(inspector);
+
+ info("Waiting for toolbox focus");
+ yield waitForToolboxFrameFocus(toolbox);
+
inspector.sidebar.select("animationinspector");
info("Waiting for the inspector and sidebar to be ready");
- yield promise.all(initPromises);
+ yield panelReady;
let win = inspector.sidebar.getWindowForTab("animationinspector");
let {AnimationsController, AnimationsPanel} = win;
info("Waiting for the animation controller and panel to be ready");
if (AnimationsPanel.initialized) {
yield AnimationsPanel.initialized;
} else {
diff --git a/browser/devtools/framework/gDevTools.jsm b/browser/devtools/framework/gDevTools.jsm
index 413a995..1ef53f5 100644
--- a/browser/devtools/framework/gDevTools.jsm
+++ b/browser/devtools/framework/gDevTools.jsm
@@ -9,25 +9,22 @@ this.EXPORTED_SYMBOLS = [ "gDevTools", "DevTools", "gDevToolsBrowser" ];
const { classes: Cc, interfaces: Ci, utils: Cu } = Components;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/devtools/Loader.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "promise",
"resource://gre/modules/Promise.jsm", "Promise");
-
XPCOMUtils.defineLazyModuleGetter(this, "console",
"resource://gre/modules/devtools/Console.jsm");
-
XPCOMUtils.defineLazyModuleGetter(this, "CustomizableUI",
"resource:///modules/CustomizableUI.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "DebuggerServer",
"resource://gre/modules/devtools/dbg-server.jsm");
-
XPCOMUtils.defineLazyModuleGetter(this, "DebuggerClient",
"resource://gre/modules/devtools/dbg-client.jsm");
const EventEmitter = devtools.require("devtools/toolkit/event-emitter");
const Telemetry = devtools.require("devtools/shared/telemetry");
const TABS_OPEN_PEAK_HISTOGRAM = "DEVTOOLS_TABS_OPEN_PEAK_LINEAR";
const TABS_OPEN_AVG_HISTOGRAM = "DEVTOOLS_TABS_OPEN_AVERAGE_LINEAR";
@@ -1208,26 +1205,16 @@ let gDevToolsBrowser = {
broadcaster.setAttribute("checked", "true");
} else {
broadcaster.removeAttribute("checked");
}
}
},
/**
- * Connects to the SPS profiler when the developer tools are open. This is
- * necessary because of the WebConsole's `profile` and `profileEnd` methods.
- */
- _connectToProfiler: function DT_connectToProfiler(event, toolbox) {
- let SharedPerformanceUtils = devtools.require("devtools/performance/front");
- let connection = SharedPerformanceUtils.getPerformanceActorsConnection(toolbox.target);
- connection.open();
- },
-
- /**
* Remove the menuitem for a tool to all open browser windows.
*
* @param {string} toolId
* id of the tool to remove
*/
_removeToolFromWindows: function DT_removeToolFromWindows(toolId) {
for (let win of gDevToolsBrowser._trackedBrowserWindows) {
gDevToolsBrowser._removeToolFromMenu(toolId, win.document);
@@ -1325,17 +1312,16 @@ let gDevToolsBrowser = {
gDevToolsBrowser._updateMenuCheckbox();
}
},
/**
* All browser windows have been closed, tidy up remaining objects.
*/
destroy: function() {
- gDevTools.off("toolbox-ready", gDevToolsBrowser._connectToProfiler);
Services.prefs.removeObserver("devtools.", gDevToolsBrowser);
Services.obs.removeObserver(gDevToolsBrowser.destroy, "quit-application");
},
}
this.gDevToolsBrowser = gDevToolsBrowser;
gDevTools.on("tool-registered", function(ev, toolId) {
@@ -1346,15 +1332,14 @@ gDevTools.on("tool-registered", function(ev, toolId) {
gDevTools.on("tool-unregistered", function(ev, toolId) {
if (typeof toolId != "string") {
toolId = toolId.id;
}
gDevToolsBrowser._removeToolFromWindows(toolId);
});
gDevTools.on("toolbox-ready", gDevToolsBrowser._updateMenuCheckbox);
-gDevTools.on("toolbox-ready", gDevToolsBrowser._connectToProfiler);
gDevTools.on("toolbox-destroyed", gDevToolsBrowser._updateMenuCheckbox);
Services.obs.addObserver(gDevToolsBrowser.destroy, "quit-application", false);
// Load the browser devtools main module as the loader's main module.
devtools.main("main");
diff --git a/browser/devtools/framework/toolbox.js b/browser/devtools/framework/toolbox.js
index f74471e..94dceea 100644
--- a/browser/devtools/framework/toolbox.js
+++ b/browser/devtools/framework/toolbox.js
@@ -46,16 +46,17 @@ loader.lazyGetter(this, "toolboxStrings", () => {
return null;
}
};
});
loader.lazyGetter(this, "Selection", () => require("devtools/framework/selection").Selection);
loader.lazyGetter(this, "InspectorFront", () => require("devtools/server/actors/inspector").InspectorFront);
loader.lazyRequireGetter(this, "DevToolsUtils", "devtools/toolkit/DevToolsUtils");
+loader.lazyRequireGetter(this, "getPerformanceActorsConnection", "devtools/performance/front", true);
XPCOMUtils.defineLazyGetter(this, "screenManager", () => {
return Cc["@mozilla.org/gfx/screenmanager;1"].getService(Ci.nsIScreenManager);
});
XPCOMUtils.defineLazyGetter(this, "oscpu", () => {
return Cc["@mozilla.org/network/protocol;1?name=http"]
.getService(Ci.nsIHttpProtocolHandler).oscpu;
@@ -305,90 +306,90 @@ Toolbox.prototype = {
*/
get splitConsole() {
return this._splitConsole;
},
/**
* Open the toolbox
*/
- open: function() {
- let deferred = promise.defer();
+ open: function () {
+ return Task.spawn(function*() {
+ let iframe = yield this._host.create();
+ let domReady = promise.defer();
- return this._host.create().then(iframe => {
- let deferred = promise.defer();
+ // Load the toolbox-level actor fronts and utilities now
+ yield this._target.makeRemote();
+ iframe.setAttribute("src", this._URL);
+ iframe.setAttribute("aria-label", toolboxStrings("toolbox.label"));
+ let domHelper = new DOMHelpers(iframe.contentWindow);
+ domHelper.onceDOMReady(() => domReady.resolve());
- let domReady = () => {
- this.isReady = true;
+ yield domReady.promise;
- let framesPromise = this._listFrames();
+ this.isReady = true;
+ let framesPromise = this._listFrames();
- this.closeButton = this.doc.getElementById("toolbox-close");
- this.closeButton.addEventListener("command", this.destroy, true);
+ this.closeButton = this.doc.getElementById("toolbox-close");
+ this.closeButton.addEventListener("command", this.destroy, true);
- gDevTools.on("pref-changed", this._prefChanged);
+ gDevTools.on("pref-changed", this._prefChanged);
- let framesMenu = this.doc.getElementById("command-button-frames");
- framesMenu.addEventListener("command", this.selectFrame, true);
+ let framesMenu = this.doc.getElementById("command-button-frames");
+ framesMenu.addEventListener("command", this.selectFrame, true);
- this._buildDockButtons();
- this._buildOptions();
- this._buildTabs();
- this._applyCacheSettings();
- this._applyServiceWorkersTestingSettings();
- this._addKeysToWindow();
- this._addReloadKeys();
- this._addHostListeners();
- if (this._hostOptions && this._hostOptions.zoom === false) {
- this._disableZoomKeys();
- } else {
- this._addZoomKeys();
- this._loadInitialZoom();
- }
+ this._buildDockButtons();
+ this._buildOptions();
+ this._buildTabs();
+ this._applyCacheSettings();
+ this._applyServiceWorkersTestingSettings();
+ this._addKeysToWindow();
+ this._addReloadKeys();
+ this._addHostListeners();
+ if (this._hostOptions && this._hostOptions.zoom === false) {
+ this._disableZoomKeys();
+ } else {
+ this._addZoomKeys();
+ this._loadInitialZoom();
+ }
- this.webconsolePanel = this.doc.querySelector("#toolbox-panel-webconsole");
- this.webconsolePanel.height =
- Services.prefs.getIntPref(SPLITCONSOLE_HEIGHT_PREF);
- this.webconsolePanel.addEventListener("resize",
- this._saveSplitConsoleHeight);
+ this.webconsolePanel = this.doc.querySelector("#toolbox-panel-webconsole");
+ this.webconsolePanel.height = Services.prefs.getIntPref(SPLITCONSOLE_HEIGHT_PREF);
+ this.webconsolePanel.addEventListener("resize", this._saveSplitConsoleHeight);
- let buttonsPromise = this._buildButtons();
+ let buttonsPromise = this._buildButtons();
- this._pingTelemetry();
+ this._pingTelemetry();
- this.selectTool(this._defaultToolId).then(panel => {
+ let panel = yield this.selectTool(this._defaultToolId);
- // Wait until the original tool is selected so that the split
- // console input will receive focus.
- let splitConsolePromise = promise.resolve();
- if (Services.prefs.getBoolPref(SPLITCONSOLE_ENABLED_PREF)) {
- splitConsolePromise = this.openSplitConsole();
- }
+ // Wait until the original tool is selected so that the split
+ // console input will receive focus.
+ let splitConsolePromise = promise.resolve();
+ if (Services.prefs.getBoolPref(SPLITCONSOLE_ENABLED_PREF)) {
+ splitConsolePromise = this.openSplitConsole();
+ }
- promise.all([
- splitConsolePromise,
- buttonsPromise,
- framesPromise
- ]).then(() => {
- this.emit("ready");
- deferred.resolve();
- }, deferred.reject);
- });
- };
+ yield promise.all([
+ splitConsolePromise,
+ buttonsPromise,
+ framesPromise
+ ]);
- // Load the toolbox-level actor fronts and utilities now
- this._target.makeRemote().then(() => {
- iframe.setAttribute("src", this._URL);
- iframe.setAttribute("aria-label", toolboxStrings("toolbox.label"));
- let domHelper = new DOMHelpers(iframe.contentWindow);
- domHelper.onceDOMReady(domReady);
- });
+ let profilerReady = this._connectProfiler();
- return deferred.promise;
- }).then(null, console.error.bind(console));
+ // Only wait for the profiler initialization during tests. Otherwise,
+ // lazily load this. This is to intercept console.profile calls; the performance
+ // tools will explicitly wait for the connection opening when opened.
+ if (gDevTools.testing) {
+ yield profilerReady;
+ }
+
+ this.emit("ready");
+ }.bind(this)).then(null, console.error.bind(console));
},
_pingTelemetry: function() {
this._telemetry.toolOpened("toolbox");
this._telemetry.logOncePerBrowserVersion(OS_HISTOGRAM,
this._getOsCpu());
this._telemetry.logOncePerBrowserVersion(OS_IS_64_BITS, is64Bit ? 1 : 0);
@@ -1685,16 +1686,17 @@ Toolbox.prototype = {
}
this.emit("destroy");
this._target.off("navigate", this._refreshHostTitle);
this._target.off("frame-update", this._updateFrames);
this.off("select", this._refreshHostTitle);
this.off("host-changed", this._refreshHostTitle);
+ this.off("ready", this._showDevEditionPromo);
gDevTools.off("tool-registered", this._toolRegistered);
gDevTools.off("tool-unregistered", this._toolUnregistered);
gDevTools.off("pref-changed", this._prefChanged);
this._lastFocusedElement = null;
if (this.webconsolePanel) {
@@ -1730,16 +1732,19 @@ Toolbox.prototype = {
outstanding.push(this.destroyInspector().then(() => {
// Removing buttons
if (this._pickerButton) {
this._pickerButton.removeEventListener("command", this._togglePicker, false);
this._pickerButton = null;
}
}));
+ // Destroy the profiler connection
+ outstanding.push(this._disconnectProfiler());
+
// We need to grab a reference to win before this._host is destroyed.
let win = this.frame.ownerGlobal;
if (this._requisition) {
this._requisition.destroy();
}
this._telemetry.toolClosed("toolbox");
this._telemetry.destroy();
@@ -1810,10 +1815,44 @@ Toolbox.prototype = {
*/
_showDevEditionPromo: function() {
// Do not display in browser toolbox
if (this.target.chrome) {
return;
}
let window = this.frame.contentWindow;
showDoorhanger({ window, type: "deveditionpromo" });
- }
+ },
+
+ getPerformanceActorsConnection: function() {
+ if (!this._performanceConnection) {
+ this._performanceConnection = getPerformanceActorsConnection(this.target);
+ }
+ return this._performanceConnection;
+ },
+
+ /**
+ * Connects to the SPS profiler when the developer tools are open. This is
+ * necessary because of the WebConsole's `profile` and `profileEnd` methods.
+ */
+ _connectProfiler: Task.async(function*() {
+ // If target does not have profiler actor (addons), do not
+ // even register the shared performance connection.
+ if (!this.target.hasActor("profiler")) {
+ return;
+ }
+
+ yield this.getPerformanceActorsConnection().open();
+ // Emit an event when connected, but don't wait on startup for this.
+ this.emit("profiler-connected");
+ }),
+
+ /**
+ * Disconnects the underlying Performance Actor Connection.
+ */
+ _disconnectProfiler: Task.async(function*() {
+ if (!this._performanceConnection) {
+ return;
+ }
+ yield this._performanceConnection.destroy();
+ this._performanceConnection = null;
+ }),
};
diff --git a/browser/devtools/performance/modules/front.js b/browser/devtools/performance/modules/front.js
index 221a05f..6cf302f 100644
--- a/browser/devtools/performance/modules/front.js
+++ b/browser/devtools/performance/modules/front.js
@@ -1,16 +1,17 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
const { Cc, Ci, Cu, Cr } = require("chrome");
const { Task } = require("resource://gre/modules/Task.jsm");
const { extend } = require("sdk/util/object");
+const { RecordingModel } = require("devtools/performance/recording-model");
loader.lazyRequireGetter(this, "Services");
loader.lazyRequireGetter(this, "promise");
loader.lazyRequireGetter(this, "EventEmitter",
"devtools/toolkit/event-emitter");
loader.lazyRequireGetter(this, "TimelineFront",
"devtools/server/actors/timeline", true);
loader.lazyRequireGetter(this, "MemoryFront",
@@ -21,20 +22,32 @@ loader.lazyRequireGetter(this, "compatibility",
"devtools/performance/compatibility");
loader.lazyImporter(this, "gDevTools",
"resource:///modules/devtools/gDevTools.jsm");
loader.lazyImporter(this, "setTimeout",
"resource://gre/modules/Timer.jsm");
loader.lazyImporter(this, "clearTimeout",
"resource://gre/modules/Timer.jsm");
+loader.lazyImporter(this, "Promise",
+ "resource://gre/modules/Promise.jsm");
+
// How often do we pull allocation sites from the memory actor.
const DEFAULT_ALLOCATION_SITES_PULL_TIMEOUT = 200; // ms
+// Events to pipe from PerformanceActorsConnection to the PerformanceFront
+const CONNECTION_PIPE_EVENTS = [
+ "console-profile-start", "console-profile-ending", "console-profile-end",
+ "timeline-data", "profiler-already-active", "profiler-activated"
+];
+
+// Events to listen to from the profiler actor
+const PROFILER_EVENTS = ["console-api-profiler", "profiler-stopped"];
+
/**
* A cache of all PerformanceActorsConnection instances.
* The keys are Target objects.
*/
let SharedPerformanceActors = new WeakMap();
/**
* Instantiates a shared PerformanceActorsConnection for the specified target.
@@ -66,16 +79,26 @@ SharedPerformanceActors.forTarget = function(target) {
* The target owning this connection.
*/
function PerformanceActorsConnection(target) {
EventEmitter.decorate(this);
this._target = target;
this._client = this._target.client;
this._request = this._request.bind(this);
+ this._pendingConsoleRecordings = [];
+ this._sitesPullTimeout = 0;
+ this._recordings = [];
+
+ this._onTimelineMarkers = this._onTimelineMarkers.bind(this);
+ this._onTimelineFrames = this._onTimelineFrames.bind(this);
+ this._onTimelineMemory = this._onTimelineMemory.bind(this);
+ this._onTimelineTicks = this._onTimelineTicks.bind(this);
+ this._onProfilerEvent = this._onProfilerEvent.bind(this);
+ this._pullAllocationSites = this._pullAllocationSites.bind(this);
Services.obs.notifyObservers(null, "performance-actors-connection-created", null);
}
PerformanceActorsConnection.prototype = {
// Properties set when mocks are being used
_usingMockMemory: false,
@@ -84,41 +107,55 @@ PerformanceActorsConnection.prototype = {
/**
* Initializes a connection to the profiler and other miscellaneous actors.
* If in the process of opening, or already open, nothing happens.
*
* @return object
* A promise that is resolved once the connection is established.
*/
open: Task.async(function*() {
- if (this._connected) {
- return;
+ if (this._connecting) {
+ return this._connecting.promise;
}
+ // Create a promise that gets resolved upon connecting, so that
+ // other attempts to open the connection use the same resolution promise
+ this._connecting = Promise.defer();
+
// Local debugging needs to make the target remote.
yield this._target.makeRemote();
// Sets `this._profiler`, `this._timeline` and `this._memory`.
// Only initialize the timeline and memory fronts if the respective actors
// are available. Older Gecko versions don't have existing implementations,
// in which case all the methods we need can be easily mocked.
yield this._connectProfilerActor();
yield this._connectTimelineActor();
yield this._connectMemoryActor();
+ yield this._registerListeners();
+
this._connected = true;
+ this._connecting.resolve();
Services.obs.notifyObservers(null, "performance-actors-connection-opened", null);
}),
/**
* Destroys this connection.
*/
destroy: Task.async(function*() {
+ if (this._connecting && !this._connected) {
+ console.warn("Attempting to destroy SharedPerformanceActorsConnection before initialization completion. If testing, ensure `gDevTools.testing` is set.");
+ }
+
+ yield this._unregisterListeners();
yield this._disconnectActors();
+
+ this._memory = this._timeline = this._profiler = this._target = this._client = null;
this._connected = false;
}),
/**
* Initializes a connection to the profiler actor.
*/
_connectProfilerActor: Task.async(function*() {
// Chrome and content process targets already have obtained a reference
@@ -159,16 +196,45 @@ PerformanceActorsConnection.prototype = {
this._memory = new MemoryFront(this._target.client, this._target.form);
} else {
this._usingMockMemory = true;
this._memory = new compatibility.MockMemoryFront();
}
}),
/**
+ * Registers listeners on events from the underlying
+ * actors, so the connection can handle them.
+ */
+ _registerListeners: Task.async(function*() {
+ // Pipe events from TimelineActor to the PerformanceFront
+ this._timeline.on("markers", this._onTimelineMarkers);
+ this._timeline.on("frames", this._onTimelineFrames);
+ this._timeline.on("memory", this._onTimelineMemory);
+ this._timeline.on("ticks", this._onTimelineTicks);
+
+ // Register events on the profiler actor to hook into `console.profile*` calls.
+ yield this._request("profiler", "registerEventNotifications", { events: PROFILER_EVENTS });
+ this._client.addListener("eventNotification", this._onProfilerEvent);
+ }),
+
+ /**
+ * Unregisters listeners on events on the underlying actors.
+ */
+ _unregisterListeners: Task.async(function*() {
+ this._timeline.off("markers", this._onTimelineMarkers);
+ this._timeline.off("frames", this._onTimelineFrames);
+ this._timeline.off("memory", this._onTimelineMemory);
+ this._timeline.off("ticks", this._onTimelineTicks);
+
+ yield this._request("profiler", "unregisterEventNotifications", { events: PROFILER_EVENTS });
+ this._client.removeListener("eventNotification", this._onProfilerEvent);
+ }),
+
+ /**
* Closes the connections to non-profiler actors.
*/
_disconnectActors: Task.async(function* () {
yield this._timeline.destroy();
yield this._memory.destroy();
}),
/**
@@ -199,96 +265,229 @@ PerformanceActorsConnection.prototype = {
if (actor == "timeline") {
return this._timeline[method].apply(this._timeline, args);
}
// Handle requests to the memory actor.
if (actor == "memory") {
return this._memory[method].apply(this._memory, args);
}
- }
-};
+ },
-/**
- * A thin wrapper around a shared PerformanceActorsConnection for the parent target.
- * Handles manually starting and stopping a recording.
- *
- * @param PerformanceActorsConnection connection
- * The shared instance for the parent target.
- */
-function PerformanceFront(connection) {
- EventEmitter.decorate(this);
+ /**
+ * Invoked whenever a registered event was emitted by the profiler actor.
+ *
+ * @param object response
+ * The data received from the backend.
+ */
+ _onProfilerEvent: function (_, { topic, subject, details }) {
+ if (topic === "console-api-profiler") {
+ if (subject.action === "profile") {
+ this._onConsoleProfileStart(details);
+ } else if (subject.action === "profileEnd") {
+ this._onConsoleProfileEnd(details);
+ }
+ } else if (topic === "profiler-stopped") {
+ this._onProfilerUnexpectedlyStopped();
+ }
+ },
- this._request = connection._request;
+ /**
+ * TODO handle bug 1144438
+ */
+ _onProfilerUnexpectedlyStopped: function () {
- // Pipe events from TimelineActor to the PerformanceFront
- connection._timeline.on("markers", markers => this.emit("markers", markers));
- connection._timeline.on("frames", (delta, frames) => this.emit("frames", delta, frames));
- connection._timeline.on("memory", (delta, measurement) => this.emit("memory", delta, measurement));
- connection._timeline.on("ticks", (delta, timestamps) => this.emit("ticks", delta, timestamps));
+ },
- // Set when mocks are being used
- this._usingMockMemory = connection._usingMockMemory;
- this._usingMockTimeline = connection._usingMockTimeline;
+ /**
+ * Invoked whenever `console.profile` is called.
+ *
+ * @param string profileLabel
+ * The provided string argument if available; undefined otherwise.
+ * @param number currentTime
+ * The time (in milliseconds) when the call was made, relative to when
+ * the nsIProfiler module was started.
+ */
+ _onConsoleProfileStart: Task.async(function *({ profileLabel, currentTime: startTime }) {
+ let recordings = this._recordings;
- this._pullAllocationSites = this._pullAllocationSites.bind(this);
- this._sitesPullTimeout = 0;
-}
+ // Abort if a profile with this label already exists.
+ if (recordings.find(e => e.getLabel() === profileLabel)) {
+ return;
+ }
-PerformanceFront.prototype = {
+ // Ensure the performance front is set up and ready.
+ // Slight performance overhead for this, should research some more.
+ // This is to ensure that there is a front to receive the events for
+ // the console profiles.
+ yield gDevTools.getToolbox(this._target).loadTool("performance");
+
+ let model = yield this.startRecording(extend(getRecordingModelPrefs(), {
+ console: true,
+ label: profileLabel
+ }));
+
+ this.emit("console-profile-start", model);
+ }),
/**
- * Manually begins a recording session.
+ * Invoked whenever `console.profileEnd` is called.
+ *
+ * @param object profilerData
+ * The dump of data from the profiler triggered by this console.profileEnd call.
+ */
+ _onConsoleProfileEnd: Task.async(function *(profilerData) {
+ let pending = this._recordings.filter(r => r.isConsole() && r.isRecording());
+ if (pending.length === 0) {
+ return;
+ }
+
+ let model;
+ // Try to find the corresponding `console.profile` call if
+ // a label was used in profileEnd(). If no matches, abort.
+ if (profilerData.profileLabel) {
+ model = pending.find(e => e.getLabel() === profilerData.profileLabel);
+ }
+ // If no label supplied, pop off the most recent pending console recording
+ else {
+ model = pending[pending.length - 1];
+ }
+
+ // If `profileEnd()` was called with a label, and there are no matching
+ // sessions, abort.
+ if (!model) {
+ Cu.reportError("console.profileEnd() called with label that does not match a recording.");
+ return;
+ }
+
+ this.emit("console-profile-ending", model);
+ yield this.stopRecording(model);
+ this.emit("console-profile-end", model);
+ }),
+
+ /**
+ * Handlers for TimelineActor events. All pipe to `_onTimelineData`
+ * with the appropriate event name.
+ */
+ _onTimelineMarkers: function (markers) { this._onTimelineData("markers", markers); },
+ _onTimelineFrames: function (delta, frames) { this._onTimelineData("frames", delta, frames); },
+ _onTimelineMemory: function (delta, measurement) { this._onTimelineData("memory", delta, measurement); },
+ _onTimelineTicks: function (delta, timestamps) { this._onTimelineData("ticks", delta, timestamps); },
+
+ /**
+ * Called whenever there is timeline data of any of the following types:
+ * - markers
+ * - frames
+ * - memory
+ * - ticks
+ * - allocations
+ *
+ * Populate our internal store of recordings for all currently recording sessions.
+ */
+
+ _onTimelineData: function (...data) {
+ this._recordings.forEach(e => e.addTimelineData.apply(e, data));
+ this.emit("timeline-data", ...data);
+ },
+
+ /**
+ * Begins a recording session
*
* @param object options
* An options object to pass to the actors. Supported properties are
- * `withTicks`, `withMemory` and `withAllocations`.
+ * `withTicks`, `withMemory` and `withAllocations`, `probability`, and `maxLogLength`.
* @return object
* A promise that is resolved once recording has started.
*/
startRecording: Task.async(function*(options = {}) {
+ let model = new RecordingModel(options);
// All actors are started asynchronously over the remote debugging protocol.
// Get the corresponding start times from each one of them.
let profilerStartTime = yield this._startProfiler();
let timelineStartTime = yield this._startTimeline(options);
let memoryStartTime = yield this._startMemory(options);
- return {
+ let data = {
profilerStartTime,
timelineStartTime,
memoryStartTime
};
+
+ // Signify to the model that the recording has started,
+ // populate with data and store the recording model here.
+ model.populate(data);
+ this._recordings.push(model);
+
+ return model;
}),
/**
- * Manually ends the current recording session.
+ * Manually ends the recording session for the corresponding RecordingModel.
*
- * @param object options
- * @see PerformanceFront.prototype.startRecording
- * @return object
- * A promise that is resolved once recording has stopped,
- * with the profiler and memory data, along with all the end times.
+ * @param RecordingModel model
+ * The corresponding RecordingModel that belongs to the recording session wished to stop.
+ * @return RecordingModel
+ * Returns the same model, populated with the profiling data.
*/
- stopRecording: Task.async(function*(options = {}) {
- let memoryEndTime = yield this._stopMemory(options);
- let timelineEndTime = yield this._stopTimeline(options);
+ stopRecording: Task.async(function*(model) {
+ // If model isn't in the PerformanceActorsConnections internal store,
+ // then do nothing.
+ if (!this._recordings.includes(model)) {
+ return;
+ }
+
+ // Currently there are two ways profiles stop recording. Either manually in the
+ // performance tool, or via console.profileEnd. Once a recording is done,
+ // we want to deliver the model to the performance tool (either as a return
+ // from the PerformanceFront or via `console-profile-end` event) and then
+ // remove it from the internal store.
+ //
+ // In the case where a console.profile is generated via the console (so the tools are
+ // open), we initialize the Performance tool so it can listen to those events.
+ this._recordings.splice(this._recordings.indexOf(model), 1);
+
+ let config = model.getConfiguration();
let profilerData = yield this._request("profiler", "getProfile");
+ let memoryEndTime = Date.now();
+ let timelineEndTime = Date.now();
+
+ // Only if there are no more sessions recording do we stop
+ // the underlying memory and timeline actors. If we're still recording,
+ // juse use Date.now() for the memory and timeline end times, as those
+ // are only used in tests.
+ if (!this.isRecording()) {
+ memoryEndTime = yield this._stopMemory(config);
+ timelineEndTime = yield this._stopTimeline(config);
+ }
- return {
+ // Set the results on the RecordingModel itself.
+ model._onStopRecording({
// Data available only at the end of a recording.
profile: profilerData.profile,
// End times for all the actors.
profilerEndTime: profilerData.currentTime,
timelineEndTime: timelineEndTime,
memoryEndTime: memoryEndTime
- };
+ });
+
+ return model;
}),
/**
+ * Checks all currently stored recording models and returns a boolean
+ * if there is a session currently being recorded.
+ *
+ * @return Boolean
+ */
+ isRecording: function () {
+ return this._recordings.some(recording => recording.isRecording());
+ },
+
+ /**
* Starts the profiler actor, if necessary.
*/
_startProfiler: Task.async(function *() {
// Start the profiler only if it wasn't already active. The built-in
// nsIPerformance module will be kept recording, because it's the same instance
// for all targets and interacts with the whole platform, so we don't want
// to affect other clients by stopping (or restarting) it.
let profilerStatus = yield this._request("profiler", "isActive");
@@ -384,29 +583,84 @@ PerformanceFront.prototype = {
let isDetached = (yield this._request("memory", "getState")) !== "attached";
if (isDetached) {
deferred.resolve();
return;
}
let memoryData = yield this._request("memory", "getAllocations");
- this.emit("allocations", {
+
+ this._onTimelineData("allocations", {
sites: memoryData.allocations,
timestamps: memoryData.allocationsTimestamps,
frames: memoryData.frames,
counts: memoryData.counts
});
let delay = DEFAULT_ALLOCATION_SITES_PULL_TIMEOUT;
this._sitesPullTimeout = setTimeout(this._pullAllocationSites, delay);
deferred.resolve();
}),
+ toString: () => "[object PerformanceActorsConnection]"
+};
+
+/**
+ * A thin wrapper around a shared PerformanceActorsConnection for the parent target.
+ * Handles manually starting and stopping a recording.
+ *
+ * @param PerformanceActorsConnection connection
+ * The shared instance for the parent target.
+ */
+function PerformanceFront(connection) {
+ EventEmitter.decorate(this);
+
+ this._connection = connection;
+ this._request = connection._request;
+
+ // Set when mocks are being used
+ this._usingMockMemory = connection._usingMockMemory;
+ this._usingMockTimeline = connection._usingMockTimeline;
+
+ // Pipe the console profile events from the connection
+ // to the front so that the UI can listen.
+ CONNECTION_PIPE_EVENTS.forEach(eventName => this._connection.on(eventName, () => this.emit.apply(this, arguments)));
+}
+
+PerformanceFront.prototype = {
+
+ /**
+ * Manually begins a recording session and creates a RecordingModel.
+ * Calls the underlying PerformanceActorsConnection's startRecording method.
+ *
+ * @param object options
+ * An options object to pass to the actors. Supported properties are
+ * `withTicks`, `withMemory` and `withAllocations`, `probability` and `maxLogLength`.
+ * @return object
+ * A promise that is resolved once recording has started.
+ */
+ startRecording: function (options) {
+ return this._connection.startRecording(options);
+ },
+
+ /**
+ * Manually ends the recording session for the corresponding RecordingModel.
+ * Calls the underlying PerformanceActorsConnection's
+ *
+ * @param RecordingModel model
+ * The corresponding RecordingModel that belongs to the recording session wished to stop.
+ * @return RecordingModel
+ * Returns the same model, populated with the profiling data.
+ */
+ stopRecording: function (model) {
+ return this._connection.stopRecording(model);
+ },
+
/**
* Returns an object indicating if mock actors are being used or not.
*/
getMocksInUse: function () {
return {
memory: this._usingMockMemory,
timeline: this._usingMockTimeline
};
@@ -418,10 +672,23 @@ PerformanceFront.prototype = {
* provided thread client.
*/
function listTabs(client) {
let deferred = promise.defer();
client.listTabs(deferred.resolve);
return deferred.promise;
}
+/**
+ * Creates an object of configurations based off of preferences for a RecordingModel.
+ */
+function getRecordingModelPrefs () {
+ return {
+ withMemory: Services.prefs.getBoolPref("devtools.performance.ui.enable-memory"),
+ withTicks: Services.prefs.getBoolPref("devtools.performance.ui.enable-framerate"),
+ withAllocations: Services.prefs.getBoolPref("devtools.performance.ui.enable-memory"),
+ allocationsSampleProbability: +Services.prefs.getCharPref("devtools.performance.memory.sample-probability"),
+ allocationsMaxLogLength: Services.prefs.getIntPref("devtools.performance.memory.max-log-length")
+ };
+}
+
exports.getPerformanceActorsConnection = target => SharedPerformanceActors.forTarget(target);
exports.PerformanceFront = PerformanceFront;
diff --git a/browser/devtools/performance/modules/recording-model.js b/browser/devtools/performance/modules/recording-model.js
index 9aa9002..2d5292b 100644
--- a/browser/devtools/performance/modules/recording-model.js
+++ b/browser/devtools/performance/modules/recording-model.js
@@ -1,42 +1,43 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
const { Cc, Ci, Cu, Cr } = require("chrome");
+const { Task } = require("resource://gre/modules/Task.jsm");