summaryrefslogtreecommitdiffstats
path: root/chrome/browser/resources/file_manager/background/js/background.js
blob: 0bad77701b7087b56a4d51f82f2fdf2812077dea (plain)
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
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

'use strict';

/**
 * Number of runtime errors catched in the background page.
 * @type {number}
 */
var JSErrorCount = 0;

/**
 * Counts runtime JavaScript errors.
 */
window.onerror = function() { JSErrorCount++; };

/**
 * Type of a Files.app's instance launch.
 * @enum {number}
 */
var LaunchType = Object.freeze({
  ALWAYS_CREATE: 0,
  FOCUS_ANY_OR_CREATE: 1,
  FOCUS_SAME_OR_CREATE: 2
});

/**
 * Root class of the background page.
 * @constructor
 */
function Background() {
  /**
   * Map of all currently open app windows. The key is an app id.
   * @type {Object.<string, AppWindow>}
   */
  this.appWindows = {};

  /**
   * Synchronous queue for asynchronous calls.
   * @type {AsyncUtil.Queue}
   */
  this.queue = new AsyncUtil.Queue();

  /**
   * Progress center of the background page.
   * @type {ProgressCenter}
   */
  this.progressCenter = new ProgressCenter();

  /**
   * File operation manager.
   * @type {FileOperationManager}
   */
  this.fileOperationManager = FileOperationManager.getInstance();

  /**
   * Event handler for progress center.
   * @type {FileOperationHandler}
   * @private
   */
  this.fileOperationHandler_ = new FileOperationHandler(this);

  /**
   * Event handler for C++ sides notifications.
   * @type {DeviceHandler}
   * @private
   */
  this.deviceHandler_ = new DeviceHandler();

  /**
   * Drive sync handler.
   * @type {DriveSyncHandler}
   * @private
   */
  this.driveSyncHandler_ = new DriveSyncHandler(this.progressCenter);
  this.driveSyncHandler_.addEventListener(
      DriveSyncHandler.COMPLETED_EVENT,
      function() { this.tryClose(); }.bind(this));

  /**
   * String assets.
   * @type {Object.<string, string>}
   */
  this.stringData = null;

  /**
   * Callback list to be invoked after initialization.
   * It turns to null after initialization.
   *
   * @type {Array.<function()>}
   * @private
   */
  this.initializeCallbacks_ = [];

  /**
   * Last time when the background page can close.
   *
   * @type {number}
   * @private
   */
  this.lastTimeCanClose_ = null;

  // Seal self.
  Object.seal(this);

  // Initialize handlers.
  chrome.fileBrowserHandler.onExecute.addListener(this.onExecute_.bind(this));
  chrome.app.runtime.onLaunched.addListener(this.onLaunched_.bind(this));
  chrome.app.runtime.onRestarted.addListener(this.onRestarted_.bind(this));
  chrome.contextMenus.onClicked.addListener(
      this.onContextMenuClicked_.bind(this));

  // Fetch strings and initialize the context menu.
  this.queue.run(function(callNextStep) {
    chrome.fileBrowserPrivate.getStrings(function(strings) {
      // Initialize string assets.
      this.stringData = strings;
      loadTimeData.data = strings;
      this.initContextMenu_();

      // Invoke initialize callbacks.
      for (var i = 0; i < this.initializeCallbacks_.length; i++) {
        this.initializeCallbacks_[i]();
      }
      this.initializeCallbacks_ = null;

      callNextStep();
    }.bind(this));
  }.bind(this));
}

/**
 * A number of delay milliseconds from the first call of tryClose to the actual
 * close action.
 * @type {number}
 * @const
 * @private
 */
Background.CLOSE_DELAY_MS_ = 5000;

/**
 * Make a key of window geometry preferences for the given initial URL.
 * @param {string} url Initialize URL that the window has.
 * @return {string} Key of window geometry preferences.
 */
Background.makeGeometryKey = function(url) {
  return 'windowGeometry' + ':' + url;
};

/**
 * Register callback to be invoked after initialization.
 * If the initialization is already done, the callback is invoked immediately.
 *
 * @param {function()} callback Initialize callback to be registered.
 */
Background.prototype.ready = function(callback) {
  if (this.initializeCallbacks_ !== null)
    this.initializeCallbacks_.push(callback);
  else
    callback();
};

/**
 * Checks the current condition of background page and closes it if possible.
 */
Background.prototype.tryClose = function() {
  // If the file operation is going, the background page cannot close.
  if (this.fileOperationManager.hasQueuedTasks() ||
      this.driveSyncHandler_.syncing) {
    this.lastTimeCanClose_ = null;
    return;
  }

  var views = chrome.extension.getViews();
  var closing = false;
  for (var i = 0; i < views.length; i++) {
    // If the window that is not the background page itself and it is not
    // closing, the background page cannot close.
    if (views[i] !== window && !views[i].closing) {
      this.lastTimeCanClose_ = null;
      return;
    }
    closing = closing || views[i].closing;
  }

  // If some windows are closing, or the background page can close but could not
  // 5 seconds ago, We need more time for sure.
  if (closing ||
      this.lastTimeCanClose_ === null ||
      Date.now() - this.lastTimeCanClose_ < Background.CLOSE_DELAY_MS_) {
    if (this.lastTimeCanClose_ === null)
      this.lastTimeCanClose_ = Date.now();
    setTimeout(this.tryClose.bind(this), Background.CLOSE_DELAY_MS_);
    return;
  }

  // Otherwise we can close the background page.
  close();
};

/**
 * Gets similar windows, it means with the same initial url.
 * @param {string} url URL that the obtained windows have.
 * @return {Array.<AppWindow>} List of similar windows.
 */
Background.prototype.getSimilarWindows = function(url) {
  var result = [];
  for (var appID in this.appWindows) {
    if (this.appWindows[appID].contentWindow.appInitialURL === url)
      result.push(this.appWindows[appID]);
  }
  return result;
};

/**
 * Wrapper for an app window.
 *
 * Expects the following from the app scripts:
 * 1. The page load handler should initialize the app using |window.appState|
 *    and call |util.platform.saveAppState|.
 * 2. Every time the app state changes the app should update |window.appState|
 *    and call |util.platform.saveAppState| .
 * 3. The app may have |unload| function to persist the app state that does not
 *    fit into |window.appState|.
 *
 * @param {string} url App window content url.
 * @param {string} id App window id.
 * @param {Object} options Options object to create it.
 * @constructor
 */
function AppWindowWrapper(url, id, options) {
  this.url_ = url;
  this.id_ = id;
  // Do deep copy for the template of options to assign customized params later.
  this.options_ = JSON.parse(JSON.stringify(options));
  this.window_ = null;
  this.appState_ = null;
  this.openingOrOpened_ = false;
  this.queue = new AsyncUtil.Queue();
  Object.seal(this);
}

/**
 * Shift distance to avoid overlapping windows.
 * @type {number}
 * @const
 */
AppWindowWrapper.SHIFT_DISTANCE = 40;


/**
 * Opens the window.
 *
 * @param {Object} appState App state.
 * @param {function()=} opt_callback Completion callback.
 */
AppWindowWrapper.prototype.launch = function(appState, opt_callback) {
  // Check if the window is opened or not.
  if (this.openingOrOpened_) {
    console.error('The window is already opened.');
    if (opt_callback)
      opt_callback();
    return;
  }
  this.openingOrOpened_ = true;

  // Save application state.
  this.appState_ = appState;

  // Get similar windows, it means with the same initial url, eg. different
  // main windows of Files.app.
  var similarWindows = background.getSimilarWindows(this.url_);

  // Restore maximized windows, to avoid hiding them to tray, which can be
  // confusing for users.
  this.queue.run(function(callback) {
    for (var index = 0; index < similarWindows.length; index++) {
      if (similarWindows[index].isMaximized()) {
        var createWindowAndRemoveListener = function() {
          similarWindows[index].onRestored.removeListener(
              createWindowAndRemoveListener);
          callback();
        };
        similarWindows[index].onRestored.addListener(
            createWindowAndRemoveListener);
        similarWindows[index].restore();
        return;
      }
    }
    // If no maximized windows, then create the window immediately.
    callback();
  });

  // Obtains the last geometry.
  var lastBounds;
  this.queue.run(function(callback) {
    var key = Background.makeGeometryKey(this.url_);
    chrome.storage.local.get(key, function(preferences) {
      if (!chrome.runtime.lastError)
        lastBounds = preferences[key];
      callback();
    });
  }.bind(this));

  // Closure creating the window, once all preprocessing tasks are finished.
  this.queue.run(function(callback) {
    // Apply the last bounds.
    if (lastBounds)
      this.options_.bounds = lastBounds;

    // Create a window.
    chrome.app.window.create(this.url_, this.options_, function(appWindow) {
      this.window_ = appWindow;
      callback();
    }.bind(this));
  }.bind(this));

  // After creating.
  this.queue.run(function(callback) {
    // If there is another window in the same position, shift the window.
    var makeBoundsKey = function(bounds) {
      return bounds.left + '/' + bounds.top;
    };
    var notAvailablePositions = {};
    for (var i = 0; i < similarWindows.length; i++) {
      var key = makeBoundsKey(similarWindows[i].getBounds());
      notAvailablePositions[key] = true;
    }
    var candidateBounds = this.window_.getBounds();
    while (true) {
      var key = makeBoundsKey(candidateBounds);
      if (!notAvailablePositions[key])
        break;
      // Make the position available to avoid an infinite loop.
      notAvailablePositions[key] = false;
      var nextLeft = candidateBounds.left + AppWindowWrapper.SHIFT_DISTANCE;
      var nextRight = nextLeft + candidateBounds.width;
      candidateBounds.left = nextRight >= screen.availWidth ?
          nextRight % screen.availWidth : nextLeft;
      var nextTop = candidateBounds.top + AppWindowWrapper.SHIFT_DISTANCE;
      var nextBottom = nextTop + candidateBounds.height;
      candidateBounds.top = nextBottom >= screen.availHeight ?
          nextBottom % screen.availHeight : nextTop;
    }
    this.window_.moveTo(candidateBounds.left, candidateBounds.top);

    // Save the properties.
    var appWindow = this.window_;
    background.appWindows[this.id_] = appWindow;
    var contentWindow = appWindow.contentWindow;
    contentWindow.appID = this.id_;
    contentWindow.appState = this.appState_;
    contentWindow.appInitialURL = this.url_;
    if (window.IN_TEST)
      contentWindow.IN_TEST = true;

    // Register event listners.
    appWindow.onBoundsChanged.addListener(this.onBoundsChanged_.bind(this));
    appWindow.onClosed.addListener(this.onClosed_.bind(this));

    // Callback.
    if (opt_callback)
      opt_callback();
    callback();
  }.bind(this));
};

/**
 * Handles the onClosed extension API event.
 * @private
 */
AppWindowWrapper.prototype.onClosed_ = function() {
  // Unload the window.
  var appWindow = this.window_;
  var contentWindow = this.window_.contentWindow;
  if (contentWindow.unload)
    contentWindow.unload();
  this.window_ = null;
  this.openingOrOpened_ = false;

  // Updates preferences.
  if (contentWindow.saveOnExit) {
    contentWindow.saveOnExit.forEach(function(entry) {
      util.AppCache.update(entry.key, entry.value);
    });
  }
  chrome.storage.local.remove(this.id_);  // Forget the persisted state.

  // Remove the window from the set.
  delete background.appWindows[this.id_];

  // If there is no application window, reset window ID.
  if (!Object.keys(background.appWindows).length)
    nextFileManagerWindowID = 0;
  background.tryClose();
};

/**
 * Handles onBoundsChanged extension API event.
 * @private
 */
AppWindowWrapper.prototype.onBoundsChanged_ = function() {
  var preferences = {};
  preferences[Background.makeGeometryKey(this.url_)] =
      this.window_.getBounds();
  chrome.storage.local.set(preferences);
};

/**
 * Wrapper for a singleton app window.
 *
 * In addition to the AppWindowWrapper requirements the app scripts should
 * have |reload| method that re-initializes the app based on a changed
 * |window.appState|.
 *
 * @param {string} url App window content url.
 * @param {Object|function()} options Options object or a function to return it.
 * @constructor
 */
function SingletonAppWindowWrapper(url, options) {
  AppWindowWrapper.call(this, url, url, options);
}

/**
 * Inherits from AppWindowWrapper.
 */
SingletonAppWindowWrapper.prototype = {__proto__: AppWindowWrapper.prototype};

/**
 * Open the window.
 *
 * Activates an existing window or creates a new one.
 *
 * @param {Object} appState App state.
 * @param {function()=} opt_callback Completion callback.
 */
SingletonAppWindowWrapper.prototype.launch = function(appState, opt_callback) {
  // If the window is not opened yet, just call the parent method.
  if (!this.openingOrOpened_) {
    AppWindowWrapper.prototype.launch.call(this, appState, opt_callback);
    return;
  }

  // If the window is already opened, reload the window.
  // The queue is used to wait until the window is opened.
  this.queue.run(function(nextStep) {
    this.window_.contentWindow.appState = appState;
    this.window_.contentWindow.reload();
    this.window_.focus();
    if (opt_callback)
      opt_callback();
    nextStep();
  }.bind(this));
};

/**
 * Reopen a window if its state is saved in the local storage.
 */
SingletonAppWindowWrapper.prototype.reopen = function() {
  chrome.storage.local.get(this.id_, function(items) {
    var value = items[this.id_];
    if (!value)
      return;  // No app state persisted.

    try {
      var appState = JSON.parse(value);
    } catch (e) {
      console.error('Corrupt launch data for ' + this.id_, value);
      return;
    }
    this.launch(appState);
  }.bind(this));
};

/**
 * Prefix for the file manager window ID.
 */
var FILES_ID_PREFIX = 'files#';

/**
 * Regexp matching a file manager window ID.
 */
var FILES_ID_PATTERN = new RegExp('^' + FILES_ID_PREFIX + '(\\d*)$');

/**
 * Value of the next file manager window ID.
 */
var nextFileManagerWindowID = 0;

/**
 * File manager window create options.
 * @type {Object}
 * @const
 */
var FILE_MANAGER_WINDOW_CREATE_OPTIONS = Object.freeze({
  bounds: Object.freeze({
    left: Math.round(window.screen.availWidth * 0.1),
    top: Math.round(window.screen.availHeight * 0.1),
    width: Math.round(window.screen.availWidth * 0.8),
    height: Math.round(window.screen.availHeight * 0.8)
  }),
  minWidth: 320,
  minHeight: 240,
  frame: 'none',
  hidden: true,
  transparentBackground: true
});

/**
 * @param {Object=} opt_appState App state.
 * @param {number=} opt_id Window id.
 * @param {LaunchType=} opt_type Launch type. Default: ALWAYS_CREATE.
 * @param {function(string)=} opt_callback Completion callback with the App ID.
 */
function launchFileManager(opt_appState, opt_id, opt_type, opt_callback) {
  var type = opt_type || LaunchType.ALWAYS_CREATE;

  // Wait until all windows are created.
  background.queue.run(function(onTaskCompleted) {
    // Check if there is already a window with the same URL. If so, then
    // reuse it instead of opening a new one.
    if (type == LaunchType.FOCUS_SAME_OR_CREATE ||
        type == LaunchType.FOCUS_ANY_OR_CREATE) {
      if (opt_appState) {
        for (var key in background.appWindows) {
          if (!key.match(FILES_ID_PATTERN))
            continue;

          var contentWindow = background.appWindows[key].contentWindow;
          if (!contentWindow.appState)
            continue;

          // Different current directories.
          if (opt_appState.currentDirectoryURL !==
                  contentWindow.appState.currentDirectoryURL) {
            continue;
          }

          // Selection URL specified, and it is different.
          if (opt_appState.selectionURL &&
                  opt_appState.selectionURL !==
                  contentWindow.appState.selectionURL) {
            continue;
          }

          background.appWindows[key].focus();
          if (opt_callback)
            opt_callback(key);
          onTaskCompleted();
          return;
        }
      }
    }

    // Focus any window if none is focused. Try restored first.
    if (type == LaunchType.FOCUS_ANY_OR_CREATE) {
      // If there is already a focused window, then finish.
      for (var key in background.appWindows) {
        if (!key.match(FILES_ID_PATTERN))
          continue;

        // The isFocused() method should always be available, but in case
        // Files.app's failed on some error, wrap it with try catch.
        try {
          if (background.appWindows[key].contentWindow.isFocused()) {
            if (opt_callback)
              opt_callback(key);
            onTaskCompleted();
            return;
          }
        } catch (e) {
          console.error(e.message);
        }
      }
      // Try to focus the first non-minimized window.
      for (var key in background.appWindows) {
        if (!key.match(FILES_ID_PATTERN))
          continue;

        if (!background.appWindows[key].isMinimized()) {
          background.appWindows[key].focus();
          if (opt_callback)
            opt_callback(key);
          onTaskCompleted();
          return;
        }
      }
      // Restore and focus any window.
      for (var key in background.appWindows) {
        if (!key.match(FILES_ID_PATTERN))
          continue;

        background.appWindows[key].focus();
        if (opt_callback)
          opt_callback(key);
        onTaskCompleted();
        return;
      }
    }

    // Create a new instance in case of ALWAYS_CREATE type, or as a fallback
    // for other types.

    var id = opt_id || nextFileManagerWindowID;
    nextFileManagerWindowID = Math.max(nextFileManagerWindowID, id + 1);
    var appId = FILES_ID_PREFIX + id;

    var appWindow = new AppWindowWrapper(
        'main.html',
        appId,
        FILE_MANAGER_WINDOW_CREATE_OPTIONS);
    appWindow.launch(opt_appState || {}, function() {
      if (opt_callback)
        opt_callback(appId);
      onTaskCompleted();
    });
  });
}

/**
 * Executes a file browser task.
 *
 * @param {string} action Task id.
 * @param {Object} details Details object.
 * @private
 */
Background.prototype.onExecute_ = function(action, details) {
  var urls = details.entries.map(function(e) { return e.toURL(); });

  switch (action) {
    case 'play':
      launchAudioPlayer({items: urls, position: 0});
      break;

    case 'watch':
      launchVideoPlayer(urls[0]);
      break;

    default:
      var launchEnable = null;
      var queue = new AsyncUtil.Queue();
      queue.run(function(nextStep) {
        // If it is not auto-open (triggered by mounting external devices), we
        // always launch Files.app.
        if (action != 'auto-open') {
          launchEnable = true;
          nextStep();
          return;
        }
        // If the disable-default-apps flag is on, Files.app is not opened
        // automatically on device mount because it obstculs the manual test.
        chrome.commandLinePrivate.hasSwitch('disable-default-apps',
                                            function(flag) {
          launchEnable = !flag;
          nextStep();
        });
      });
      queue.run(function(nextStep) {
        if (!launchEnable) {
          nextStep();
          return;
        }

        // Every other action opens a Files app window.
        var appState = {
          params: {
            action: action
          },
          // It is not allowed to call getParent() here, since there may be
          // no permissions to access it at this stage. Therefore we are passing
          // the selectionURL only, and the currentDirectory will be resolved
          // later.
          selectionURL: details.entries[0].toURL()
        };
        // For mounted devices just focus any Files.app window. The mounted
        // volume will appear on the navigation list.
        var type = action == 'auto-open' ? LaunchType.FOCUS_ANY_OR_CREATE :
            LaunchType.FOCUS_SAME_OR_CREATE;
        launchFileManager(appState, /* App ID */ undefined, type, nextStep);
      });
      break;
  }
};

// The instance of audio player. Until it's ready, this is null.
var audioPlayer = null;

// Queue to serializes the initialization, launching and reloading of the audio
// player, so races won't happen.
var audioPlayerInitializationQueue = new AsyncUtil.Queue();

audioPlayerInitializationQueue.run(function(callback) {
  chrome.commandLinePrivate.hasSwitch(
      'file-manager-enable-new-audio-player',
      function(newAudioPlayerEnabled) {
        var audioPlayerHTML =
            newAudioPlayerEnabled ? 'audio_player.html' : 'mediaplayer.html';

        /**
         * Audio player window create options.
         * @type {Object}
         */
        var audioPlayerCreateOptions = Object.freeze({
          type: 'panel',
          hidden: true,
          minHeight: newAudioPlayerEnabled ? 116 : (35 + 58),
          minWidth: newAudioPlayerEnabled ? 292 : 280,
          height: newAudioPlayerEnabled ? 356 : (35 + 58),
          width: newAudioPlayerEnabled ? 292 : 280,
        });

        audioPlayer = new SingletonAppWindowWrapper(audioPlayerHTML,
                                                    audioPlayerCreateOptions);
        callback();
      });
});

/**
 * Launch the audio player.
 * @param {Object} playlist Playlist.
 */
function launchAudioPlayer(playlist) {
  audioPlayerInitializationQueue.run(function(callback) {
    audioPlayer.launch(playlist);
    callback();
  });
}

var videoPlayer = new SingletonAppWindowWrapper('video_player.html',
                                                {hidden: true});

/**
 * Launch the video player.
 * @param {string} url Video url.
 */
function launchVideoPlayer(url) {
  videoPlayer.launch({url: url});
}

/**
 * Launches the app.
 * @private
 */
Background.prototype.onLaunched_ = function() {
  if (nextFileManagerWindowID == 0) {
    // The app just launched. Remove window state records that are not needed
    // any more.
    chrome.storage.local.get(function(items) {
      for (var key in items) {
        if (items.hasOwnProperty(key)) {
          if (key.match(FILES_ID_PATTERN))
            chrome.storage.local.remove(key);
        }
      }
    });
  }
  launchFileManager(null, null, LaunchType.FOCUS_ANY_OR_CREATE);
};

/**
 * Restarted the app, restore windows.
 * @private
 */
Background.prototype.onRestarted_ = function() {
  // Reopen file manager windows.
  chrome.storage.local.get(function(items) {
    for (var key in items) {
      if (items.hasOwnProperty(key)) {
        var match = key.match(FILES_ID_PATTERN);
        if (match) {
          var id = Number(match[1]);
          try {
            var appState = JSON.parse(items[key]);
            launchFileManager(appState, id);
          } catch (e) {
            console.error('Corrupt launch data for ' + id);
          }
        }
      }
    }
  });

  // Reopen audio player.
  audioPlayerInitializationQueue.run(function(callback) {
    audioPlayer.reopen();
    callback();
  });

  // Reopen video player.
  videoPlayer.reopen();
};

/**
 * Handles clicks on a custom item on the launcher context menu.
 * @param {OnClickData} info Event details.
 * @private
 */
Background.prototype.onContextMenuClicked_ = function(info) {
  if (info.menuItemId == 'new-window') {
    // Find the focused window (if any) and use it's current url for the
    // new window. If not found, then launch with the default url.
    for (var key in background.appWindows) {
      try {
        if (background.appWindows[key].contentWindow.isFocused()) {
          var appState = {
            // Do not clone the selection url, only the current directory.
            currentDirectoryURL: background.appWindows[key].contentWindow.
                appState.currentDirectoryURL
          };
          launchFileManager(appState);
          return;
        }
      } catch (ignore) {
        // The isFocused method may not be defined during initialization.
        // Therefore, wrapped with a try-catch block.
      }
    }

    // Launch with the default URL.
    launchFileManager();
  }
};

/**
 * Initializes the context menu. Recreates if already exists.
 * @private
 */
Background.prototype.initContextMenu_ = function() {
  try {
    chrome.contextMenus.remove('new-window');
  } catch (ignore) {
    // There is no way to detect if the context menu is already added, therefore
    // try to recreate it every time.
  }
  chrome.contextMenus.create({
    id: 'new-window',
    contexts: ['launcher'],
    title: str('NEW_WINDOW_BUTTON_LABEL')
  });
};

/**
 * Singleton instance of Background.
 * @type {Background}
 */
window.background = new Background();