forked from mozilla-b2g/gaia
/
window_manager.js
1883 lines (1587 loc) · 58.1 KB
/
window_manager.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
/* -*- Mode: js; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- /
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
'use strict';
//
// This file calls getElementById without waiting for an onload event, so it
// must have a defer attribute or be included at the end of the <body>.
//
// This module is responsible for launching apps and for allowing
// the user to switch among apps and kill apps. Specifically, it handles:
// launching apps,
// killing apps
// keeping track of the set of running apps (which we call tasks here)
// keeping track of which task is displayed (the foreground task)
// changing the foreground task
// hiding all apps to display the homescreen
// displaying the app switcher to allow the user to switch and kill apps
// performing appropriate transition animations between:
// the homescreen and an app
// the homescreen and the switcher
// an app and the homescreen
// the switcher and the homescreen
// the switcher and the current foreground task
// the switcher and a different task
// Handling Home key events to switch to the homescreen and the switcher
//
// The public API of the module is small. It defines an WindowManager object
// with these methods:
//
// launch(origin): switch to the specified running app
// kill(origin, callback): stop specified app
// reload(origin): reload the given app
// getDisplayedApp(): return the origin of the currently displayed app
// setOrientationForApp(origin): set the phone to orientation to a given app
// getAppFrame(origin): returns the iframe element for the specified origin
// which is assumed to be running. This is only currently used
// for tests and chrome stuff: see the end of the file
// getRunningApps(): get the app references of the running apps.
//
// TODO
// The "origin" does not actually refer to app's origin but rather a identifier
// of the app reference that one gets from |getDisplayedApp()| or
// iterates |getRunningApps|. The string is make up of the specified
// launching entry point, origin, or the website url launched by wrapper.
// It would be ideal if the variable get correctly named and it's rule is being
// properly documented.
// See https://bugzilla.mozilla.org/show_bug.cgi?id=796629
//
var WindowManager = (function() {
// Holds the origin of the home screen, which should be the first
// app we launch through web activity during boot
var homescreen = null;
var homescreenURL = '';
var homescreenManifestURL = '';
var ftu = null;
var ftuManifestURL = '';
var ftuURL = '';
var isRunningFirstRunApp = false;
// keep the reference of inline activity frame here
var inlineActivityFrames = [];
var activityCallerOrigin = '';
// Some document elements we use
var windows = document.getElementById('windows');
var screenElement = document.getElementById('screen');
var wrapperHeader = document.querySelector('#wrapper-activity-indicator');
var wrapperFooter = document.querySelector('#wrapper-footer');
var kTransitionTimeout = 300;
// Set this to true to debugging the transitions and state change
var slowTransition = false;
if (slowTransition) {
kTransitionTimeout = 1000;
windows.classList.add('slow-transition');
}
//
// The set of running apps.
// This is a map from app origin to an object like this:
// {
// name: the app's name
// manifest: the app's manifest object
// frame: the iframe element that the app is displayed in
// launchTime: last time when app gets active
// }
//
var runningApps = {};
var numRunningApps = 0; // appendFrame() and removeFrame() maintain this count
var nextAppId = 0; // to give each app's iframe a unique id attribute
// The origin of the currently displayed app, or null if there isn't one
var displayedApp = null;
// Function to hide init starting logo
function handleInitlogo(callback) {
var initlogo = document.getElementById('initlogo');
initlogo.classList.add('hide');
initlogo.addEventListener('transitionend', function delInitlogo() {
initlogo.removeEventListener('transitionend', delInitlogo);
initlogo.parentNode.removeChild(initlogo);
if (callback) {
callback();
}
});
};
// Public function. Return the origin of the currently displayed app
// or null if there is none.
function getDisplayedApp() {
return displayedApp || null;
}
function requireFullscreen(origin) {
var app = runningApps[origin];
if (!app)
return false;
var manifest = app.manifest;
if (manifest.entry_points && manifest.type == 'certified') {
var entryPoint = manifest.entry_points[origin.split('/')[3]];
if (entryPoint)
return entryPoint.fullscreen;
return false;
} else {
return manifest.fullscreen;
}
}
// Make the specified app the displayed app.
// Public function. Pass null to make the homescreen visible
function launch(origin) {
// If the origin is indeed valid we make that app as the displayed app.
if (isRunning(origin)) {
setDisplayedApp(origin);
return;
}
// If the origin is null, make the homescreen visible.
if (origin == null) {
setDisplayedApp(homescreen);
return;
}
// At this point, we have no choice but to show the homescreen.
// We cannot launch/relaunch a given app based on the "origin" because
// we would need the manifest URL and the specific entry point.
console.warn('No running app is being identified as "' + origin + '". ' +
'Showing home screen instead.');
setDisplayedApp(homescreen);
}
function isRunning(origin) {
return runningApps.hasOwnProperty(origin);
}
function getAppFrame(origin) {
if (isRunning(origin))
return runningApps[origin].frame;
else
return null;
}
// Set the size of the app's iframe to match the size of the screen.
// We have to call this on resize events (which happen when the
// phone orientation is changed). And also when an app is launched
// and each time an app is brought to the front, since the
// orientation could have changed since it was last displayed
function setAppSize(origin, changeActivityFrame) {
var app = runningApps[origin];
if (!app)
return;
var frame = app.frame;
var manifest = app.manifest;
var cssWidth = window.innerWidth + 'px';
var cssHeight = window.innerHeight - StatusBar.height;
if ('wrapper' in frame.dataset) {
cssHeight -= 10;
}
cssHeight += 'px';
if (!screenElement.classList.contains('attention') &&
requireFullscreen(origin)) {
cssHeight = window.innerHeight + 'px';
}
frame.style.width = cssWidth;
frame.style.height = cssHeight;
// We will call setInlineActivityFrameSize()
// if changeActivityFrame is not explicitly set to false.
if (changeActivityFrame !== false)
setInlineActivityFrameSize();
}
// App's height is relevant to keyboard height
function setAppHeight(keyboardHeight) {
var app = runningApps[displayedApp];
if (!app)
return;
var frame = app.frame;
var manifest = app.manifest;
var cssHeight =
window.innerHeight - StatusBar.height - keyboardHeight + 'px';
if (!screenElement.classList.contains('attention') &&
requireFullscreen(displayedApp)) {
cssHeight = window.innerHeight - keyboardHeight + 'px';
}
frame.style.height = cssHeight;
setInlineActivityFrameSize();
}
// Copy the dimension of the currently displayed app
function setInlineActivityFrameSize() {
if (!inlineActivityFrames.length)
return;
var app = runningApps[displayedApp];
var appFrame = app.frame;
var frame = inlineActivityFrames[inlineActivityFrames.length - 1];
frame.style.width = appFrame.style.width;
if (document.mozFullScreen) {
frame.style.height = window.innerHeight + 'px';
frame.style.top = '0px';
} else {
if ('wrapper' in appFrame.dataset) {
frame.style.height = window.innerHeight - StatusBar.height + 'px';
} else {
frame.style.height = appFrame.style.height;
}
frame.style.top = appFrame.offsetTop + 'px';
}
}
function setFrameBackgroundBlob(frame, blob, transparent) {
URL.revokeObjectURL(frame.dataset.bgObjectURL);
delete frame.dataset.bgObjectURL;
var objectURL = URL.createObjectURL(blob);
frame.dataset.bgObjectURL = objectURL;
var backgroundCSS =
'-moz-linear-gradient(top, rgba(0,0,0,0.5) 0%, rgba(0,0,0,0.5) 100%),' +
'url(' + objectURL + '),' +
((transparent) ? 'transparent' : '#fff');
frame.style.background = backgroundCSS;
}
function clearFrameBackground(frame) {
if (!('bgObjectURL' in frame.dataset))
return;
URL.revokeObjectURL(frame.dataset.bgObjectURL);
delete frame.dataset.bgObjectURL;
frame.style.background = '';
}
var openFrame = null;
var closeFrame = null;
var openCallback = null;
var closeCallback = null;
var transitionOpenCallback = null;
var transitionCloseCallback = null;
// Use setOpenFrame() to reset the CSS classes set
// to the current openFrame (before overwriting the reference)
function setOpenFrame(frame) {
if (openFrame) {
removeFrameClasses(openFrame);
}
openFrame = frame;
}
// Use setCloseFrame() to reset the CSS classes set
// to the current closeFrame (before overwriting the reference)
function setCloseFrame(frame) {
if (closeFrame) {
removeFrameClasses(closeFrame);
// closeFrame should not be set to active
closeFrame.classList.remove('active');
}
closeFrame = frame;
}
// Remove these visible className from frame so we will not ended
// up having a frozen frame in the middle of the transition
function removeFrameClasses(frame) {
var classNames = ['opening', 'closing', 'opening-switching',
'opening-card', 'closing-card'];
var classList = frame.classList;
classNames.forEach(function removeClass(className) {
classList.remove(className);
});
}
windows.addEventListener('transitionend', function frameTransitionend(evt) {
var prop = evt.propertyName;
var frame = evt.target;
if (prop !== 'transform')
return;
var classList = frame.classList;
if (classList.contains('inlineActivity')) {
if (classList.contains('active')) {
if (openFrame)
openFrame.focus();
setOpenFrame(null);
} else {
windows.removeChild(frame);
}
return;
}
if (screenElement.classList.contains('switch-app')) {
if (classList.contains('closing')) {
classList.remove('closing');
classList.add('closing-card');
if (openFrame) {
openFrame.classList.remove('opening-card');
openFrame.classList.add('opening-switching');
}
} else if (classList.contains('closing-card')) {
windowClosed(frame);
setTimeout(closeCallback);
closeCallback = null;
} else if (classList.contains('opening-switching')) {
// If the opening app need to be full screen, switch to full screen
if (classList.contains('fullscreen-app')) {
screenElement.classList.add('fullscreen-app');
}
classList.remove('opening-switching');
// XXX: without this setTimeout() there will be no opening transition.
// See https://bugzilla.mozilla.org/show_bug.cgi?id=780692#c111
setTimeout(function continueTransition() {
classList.add('opening');
});
} else if (classList.contains('opening')) {
windowOpened(frame);
setTimeout(openCallback);
openCallback = null;
setCloseFrame(null);
setOpenFrame(null);
screenElement.classList.remove('switch-app');
}
return;
}
if (classList.contains('opening')) {
windowOpened(frame);
setTimeout(openCallback);
openCallback = null;
setOpenFrame(null);
} else if (classList.contains('closing')) {
windowClosed(frame);
setTimeout(closeCallback);
closeCallback = null;
setCloseFrame(null);
}
});
// Executes when the opening transition scale the app
// to full size.
function windowOpened(frame) {
frame.classList.add('active');
windows.classList.add('active');
if ('wrapper' in frame.dataset) {
wrapperFooter.classList.add('visible');
}
// Take the focus away from the currently displayed app
var app = runningApps[displayedApp];
if (app && app.frame)
app.frame.blur();
// Give the focus to the frame
frame.focus();
if (!TrustedUIManager.isVisible() && !isRunningFirstRunApp) {
// Set homescreen visibility to false
toggleHomescreen(false);
}
// Set displayedApp to the new value
displayedApp = frame.dataset.frameOrigin;
// Set orientation for the new app
setOrientationForApp(displayedApp);
// Dispatch an 'appopen' event.
var evt = document.createEvent('CustomEvent');
evt.initCustomEvent('appopen', true, false, { origin: displayedApp });
frame.dispatchEvent(evt);
}
// Executes when app closing transition finishes.
function windowClosed(frame) {
// If the FTU is closing, make sure we save this state
if (frame.src == ftuURL) {
isRunningFirstRunApp = false;
document.getElementById('screen').classList.remove('ftu');
window.asyncStorage.setItem('ftu.enabled', false);
// Done with FTU, letting everyone know
var evt = document.createEvent('CustomEvent');
evt.initCustomEvent('ftudone',
/* canBubble */ true, /* cancelable */ false, {});
window.dispatchEvent(evt);
}
frame.classList.remove('active');
windows.classList.remove('active');
// set the closed frame visibility to false
if ('setVisible' in frame)
frame.setVisible(false);
screenElement.classList.remove('fullscreen-app');
}
// The following things needs to happen when firstpaint happens.
// We centralize all that here but not all of them applies.
windows.addEventListener('mozbrowserfirstpaint', function firstpaint(evt) {
var frame = evt.target;
// remove the unpainted flag
delete frame.dataset.unpainted;
setTimeout(function firstpainted() {
// Save the screenshot
// Remove the background only until we actually got the screenshot,
// because the getScreenshot() call will be pushed back by
// painting/loading in the child process; when we got the screenshot,
// that means the app is mostly loaded.
// (as opposed to plain white firstpaint)
saveAppScreenshot(frame, function screenshotTaken() {
// Remove the default background
frame.classList.remove('default-background');
// Remove the screenshot from frame
clearFrameBackground(frame);
});
});
});
// setFrameBackground() will attach the screenshot background to
// the given frame.
// The callback could be sync or async (depend on whether we need
// the screenshot from database or not)
function setFrameBackground(frame, callback, transparent) {
// If the frame is painted, or there is already background image present
// start the transition right away.
if (!('unpainted' in frame.dataset) ||
('bgObjectURL' in frame.dataset)) {
callback();
return;
}
// Get the screenshot from the database
getAppScreenshotFromDatabase(frame.src || frame.dataset.frameOrigin,
function(screenshot) {
// If firstpaint is faster than database, we will not transition
// with screenshot.
if (!('unpainted' in frame.dataset)) {
callback();
return;
}
if (!screenshot) {
// put a default background
frame.classList.add('default-background');
callback();
return;
}
// set the screenshot as the background of the frame itself.
// we are safe to do so since there is nothing on it yet.
setFrameBackgroundBlob(frame, screenshot, transparent);
// start the transition
callback();
});
}
// On-disk database for window manager.
// It's only for app screenshots right now.
var database = null;
var DB_SCREENSHOT_OBJSTORE = 'screenshots';
(function openDatabase() {
var DB_VERSION = 2;
var DB_NAME = 'window_manager';
var req = window.indexedDB.open(DB_NAME, DB_VERSION);
req.onerror = function() {
console.error('Window Manager: opening database failed.');
};
req.onupgradeneeded = function databaseUpgradeneeded() {
database = req.result;
if (database.objectStoreNames.contains(DB_SCREENSHOT_OBJSTORE))
database.deleteObjectStore(DB_SCREENSHOT_OBJSTORE);
var store = database.createObjectStore(
DB_SCREENSHOT_OBJSTORE, { keyPath: 'url' });
};
req.onsuccess = function databaseSuccess() {
database = req.result;
};
})();
function putAppScreenshotToDatabase(url, data) {
if (!database)
return;
var txn = database.transaction(DB_SCREENSHOT_OBJSTORE, 'readwrite');
txn.onerror = function() {
console.warn(
'Window Manager: transaction error while trying to save screenshot.');
};
var store = txn.objectStore(DB_SCREENSHOT_OBJSTORE);
var req = store.put({
url: url,
screenshot: data
});
req.onerror = function(evt) {
console.warn(
'Window Manager: put error while trying to save screenshot.');
};
}
function getAppScreenshotFromDatabase(url, callback) {
if (!database) {
console.warn(
'Window Manager: Neither database nor app frame is ' +
'ready for getting screenshot.');
callback();
return;
}
var req = database.transaction(DB_SCREENSHOT_OBJSTORE)
.objectStore(DB_SCREENSHOT_OBJSTORE).get(url);
req.onsuccess = function() {
if (!req.result) {
console.log('Window Manager: No screenshot in database. ' +
'This is expected from a fresh installed app.');
callback();
return;
}
callback(req.result.screenshot, true);
}
req.onerror = function(evt) {
console.warn('Window Manager: get screenshot from database failed.');
callback();
};
}
function deleteAppScreenshotFromDatabase(url) {
var txn = database.transaction(DB_SCREENSHOT_OBJSTORE);
var store = txn.objectStore(DB_SCREENSHOT_OBJSTORE);
store.delete(url);
}
function getAppScreenshotFromFrame(frame, callback) {
if (!frame) {
callback();
return;
}
var req = frame.getScreenshot(frame.offsetWidth, frame.offsetHeight);
req.onsuccess = function gotScreenshotFromFrame(evt) {
var result = evt.target.result;
callback(result, false);
};
req.onerror = function gotScreenshotFromFrameError(evt) {
console.warn('Window Manager: getScreenshot failed.');
callback();
};
}
// Meta method for get the screenshot from the app frame,
// and save it to database.
function saveAppScreenshot(frame, callback) {
getAppScreenshotFromFrame(frame, function gotScreenshot(screenshot) {
if (callback)
callback(screenshot);
if (!screenshot)
return;
putAppScreenshotToDatabase(frame.src || frame.dataset.frameOrigin,
screenshot);
});
}
// Perform an "open" animation for the app's iframe
function openWindow(origin, callback) {
var app = runningApps[origin];
setOpenFrame(app.frame);
openCallback = callback || function() {};
// set the size of the opening app
setAppSize(origin);
if (origin === homescreen) {
// We cannot apply background screenshot to home screen app since
// the screenshot is encoded in JPEG and the alpha channel is
// not perserved. See
// https://bugzilla.mozilla.org/show_bug.cgi?id=801676#c33
// If that resolves,
// setFrameBackground(openFrame, gotBackground, true);
// will simply work here.
// Call the openCallback only once. We have to use tmp var as
// openCallback can be a method calling the callback
// (like the `removeFrame` callback in `kill()` ).
var tmpCallback = openCallback;
openCallback = null;
tmpCallback();
windows.classList.add('active');
openFrame.classList.add('homescreen');
openFrame.focus();
setOpenFrame(null);
displayedApp = origin;
return;
}
if (requireFullscreen(origin))
screenElement.classList.add('fullscreen-app');
transitionOpenCallback = function startOpeningTransition() {
// We have been canceled by another transition.
if (!openFrame || transitionOpenCallback != startOpeningTransition)
return;
// Make sure we're not called twice.
transitionOpenCallback = null;
if (!screenElement.classList.contains('switch-app')) {
openFrame.classList.add('opening');
} else {
openFrame.classList.add('opening-card');
}
};
if ('unpainted' in openFrame.dataset) {
waitForNextPaintOrBackground(openFrame, transitionOpenCallback);
} else {
waitForNextPaint(openFrame, transitionOpenCallback);
}
// Set the frame to be visible.
if ('setVisible' in openFrame)
openFrame.setVisible(true);
}
function waitForNextPaintOrBackground(frame, callback) {
var waiting = true;
function proceed() {
if (waiting) {
waiting = false;
callback();
}
}
waitForNextPaint(frame, proceed);
setFrameBackground(frame, proceed);
}
function waitForNextPaint(frame, callback) {
function onNextPaint() {
clearTimeout(timeout);
callback();
}
// Register a timeout in case we don't receive
// nextpaint in an acceptable time frame.
var timeout = setTimeout(function() {
if ('removeNextPaintListener' in frame)
frame.removeNextPaintListener(onNextPaint);
callback();
}, kTransitionTimeout);
if ('addNextPaintListener' in frame)
frame.addNextPaintListener(onNextPaint);
}
// Perform a "close" animation for the app's iframe
function closeWindow(origin, callback) {
var app = runningApps[origin];
setCloseFrame(app.frame);
closeCallback = callback || function() {};
// Animate the window close. Ensure the homescreen is in the
// foreground since it will be shown during the animation.
var homescreenFrame = ensureHomescreen();
// invoke openWindow to show homescreen here
openWindow(homescreen, null);
// Take keyboard focus away from the closing window
closeFrame.blur();
// set orientation for homescreen app
setOrientationForApp(homescreen);
// Set the size of both homescreen app and the closing app
// since the orientation had changed.
setAppSize(homescreen);
setAppSize(origin);
// Send a synthentic 'appwillclose' event.
// The keyboard uses this and the appclose event to know when to close
// See https://github.com/andreasgal/gaia/issues/832
var evt = document.createEvent('CustomEvent');
evt.initCustomEvent('appwillclose', true, false, { origin: origin });
closeFrame.dispatchEvent(evt);
if ('wrapper' in closeFrame.dataset) {
wrapperHeader.classList.remove('visible');
wrapperFooter.classList.remove('visible');
}
transitionCloseCallback = function startClosingTransition() {
// We have been canceled by another transition.
if (!closeFrame || transitionCloseCallback != startClosingTransition)
return;
// Make sure we're not called twice.
transitionCloseCallback = null;
// Start the transition
closeFrame.classList.add('closing');
closeFrame.classList.remove('active');
};
waitForNextPaint(homescreenFrame, transitionCloseCallback);
}
// Perform a "switching" animation for the closing frame and the opening frame
function switchWindow(origin, callback) {
// This will trigger different transition to both openWindow()
// and closeWindow() transition.
screenElement.classList.add('switch-app');
// Ask closeWindow() to start closing the displayedApp
closeWindow(displayedApp, callback);
// Ask openWindow() to show a card on the right waiting to be opened
openWindow(origin);
}
// Ensure the homescreen is loaded and return its frame. Restarts
// the homescreen app if it was killed in the background.
// Note: this function would not invoke openWindow(homescreen),
// which should be handled in setDisplayedApp and in closeWindow()
function ensureHomescreen(reset) {
// If the url of the homescreen is not known at this point do nothing.
if (!homescreen || !homescreenManifestURL) {
return null;
}
if (!isRunning(homescreen)) {
var app = Applications.getByManifestURL(homescreenManifestURL);
appendFrame(null, homescreen, homescreenURL,
app.manifest.name, app.manifest, app.manifestURL);
} else if (reset) {
runningApps[homescreen].frame.src = homescreenURL;
}
// need to setAppSize or for the first time, or from FTU to homescreen
// the dock position would be incorrect.
setAppSize(homescreen);
return runningApps[homescreen].frame;
}
function retrieveHomescreen(callback) {
var lock = navigator.mozSettings.createLock();
var setting = lock.get('homescreen.manifestURL');
setting.onsuccess = function() {
var app =
Applications.getByManifestURL(this.result['homescreen.manifestURL']);
// XXX This is a one-day workaround to not break everybody and make sure
// work can continue.
if (!app) {
var tmpURL = document.location.toString()
.replace('system', 'homescreen')
.replace('index.html', 'manifest.webapp');
app = Applications.getByManifestURL(tmpURL);
}
if (app) {
homescreenManifestURL = app.manifestURL;
homescreen = app.origin;
homescreenURL = app.origin + '/index.html#root';
callback(app);
}
}
}
function skipFTU() {
document.getElementById('screen').classList.remove('ftuStarting');
handleInitlogo();
setDisplayedApp(homescreen);
}
// Check if the FTU was executed or not, if not, get a
// reference to the app and launch it.
function retrieveFTU() {
window.asyncStorage.getItem('ftu.enabled', function getItem(launchFTU) {
document.getElementById('screen').classList.add('ftuStarting');
if (launchFTU === false) {
skipFTU();
return;
}
var lock = navigator.mozSettings.createLock();
var req = lock.get('ftu.manifestURL');
req.onsuccess = function() {
ftuManifestURL = this.result['ftu.manifestURL'];
if (!ftuManifestURL) {
dump('FTU manifest cannot be found skipping.\n');
skipFTU();
return;
}
ftu = Applications.getByManifestURL(ftuManifestURL);
if (!ftu) {
dump('Opps, bogus FTU manifest.\n');
skipFTU();
return;
}
ftuURL = ftu.origin + ftu.manifest.entry_points['ftu'].launch_path;
ftu.launch('ftu');
};
req.onerror = function() {
dump('Couldn\'t get the ftu manifestURL.\n');
skipFTU();
};
});
}
// Hide current app
function hideCurrentApp(callback) {
if (displayedApp == null || displayedApp == homescreen)
return;
toggleHomescreen(true);
var frame = getAppFrame(displayedApp);
frame.classList.add('back');
frame.classList.remove('restored');
if (callback) {
frame.addEventListener('transitionend', function execCallback() {
frame.style.visibility = 'hidden';
frame.removeEventListener('transitionend', execCallback);
callback();
});
}
}
function restoreCurrentApp() {
toggleHomescreen(false);
var frame = getAppFrame(displayedApp);
frame.style.visibility = 'visible';
frame.classList.remove('back');
frame.classList.add('restored');
frame.addEventListener('transitionend', function removeRestored() {
frame.removeEventListener('transitionend', removeRestored);
frame.classList.remove('restored');
});
}
function toggleHomescreen(visible) {
var homescreenFrame = ensureHomescreen();
if (homescreenFrame)
homescreenFrame.setVisible(visible);
}
// Switch to a different app
function setDisplayedApp(origin, callback) {
var currentApp = displayedApp, newApp = origin || homescreen;
var isFirstRunApplication = !currentApp && (origin == ftuURL);
var homescreenFrame = null;
if (!isFirstRunApplication) {
// Returns the frame reference of the home screen app.
// Restarts the homescreen app if it was killed in the background.
homescreenFrame = ensureHomescreen();
}
// Cancel transitions waiting to be started.
transitionOpenCallback = null;
transitionCloseCallback = null;
// Discard any existing activity
stopInlineActivity(true);
// Before starting a new transition, let's make sure current transitions
// are stopped and the state classes are cleaned up.
// visibility status should also be reset.
if (openFrame && 'setVisible' in openFrame)
openFrame.setVisible(false);
if (closeFrame && 'setVisible' in closeFrame)
closeFrame.setVisible(false);
if (!isFirstRunApplication) {
toggleHomescreen(true);
}
setOpenFrame(null);
setCloseFrame(null);
screenElement.classList.remove('switch-app');
screenElement.classList.remove('fullscreen-app');
// Dispatch an appwillopen event only when we open an app
if (newApp != currentApp) {
var evt = document.createEvent('CustomEvent');
evt.initCustomEvent('appwillopen', true, true, { origin: newApp });
// Allows listeners to cancel app opening and so stay on homescreen
if (!runningApps[newApp].frame.dispatchEvent(evt)) {
if (typeof(callback) == 'function')
callback();
return;
}
}
// Case 1: the app is already displayed
if (currentApp && currentApp == newApp) {
if (newApp == homescreen) {
// relaunch homescreen
openWindow(homescreen, callback);
} else if (callback) {
// Just run the callback right away if it is not homescreen
callback();
}
}
// Case 2: null --> app
else if (isFirstRunApplication) {
isRunningFirstRunApp = true;
openWindow(newApp, function windowOpened() {
handleInitlogo(function() {
var mainScreen = document.getElementById('screen');
mainScreen.classList.add('ftu');
mainScreen.classList.remove('ftuStarting');
});
});
}
// Case 3: null->homescreen || homescreen->app
else if ((!currentApp && newApp == homescreen) ||
(currentApp == homescreen && newApp)) {
openWindow(newApp, callback);
}
// Case 4: app->homescreen
else if (currentApp && currentApp != homescreen && newApp == homescreen) {
// For screenshot to catch current window size
closeWindow(currentApp, callback);
}
// Case 5: app-to-app transition
else {
switchWindow(newApp, callback);
}
// Set homescreen as active,