Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/apps/system/js/screen_manager.js
blob: 9a69e8ceba6520ada3623ff71d7af4969c6baebb (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
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- /
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */

'use strict';

var ScreenManager = {
  /*
   * return the current screen status
   * Must not mutate directly - use toggleScreen/turnScreenOff/turnScreenOn.
   * Listen to 'screenchange' event to properly handle status changes
   * This value can be "out of sync" with real mozPower value,
   * we do this to give screen some time to flash before actual turn off.
   */
  screenEnabled: false,

  /*
   * before idle-screen-off, invoke a nice dimming to the brightness
   * to notify the user that the screen is about to be turn off.
   * The user can cancel the idle-screen-off by touching the screen
   * and by pressing a button (trigger onactive callback on Idle API)
   *
   */
  _inTransition: false,

  /*
   * Whether the wake lock is enabled or not
   */
  _screenWakeLocked: false,

  /*
   * Whether the device light is enabled or not
   * sync with setting 'screen.automatic-brightness'
   */
  _deviceLightEnabled: true,

  /*
   * Preferred brightness without considering device light nor dimming
   * sync with setting 'screen.brightness'
  */
  _userBrightness: 1,
  _savedBrightness: 1,

  /*
   * The auto-brightness algorithm will never set the screen brightness
   * to a value smaller than this. 0.1 seems like a good screen brightness
   * in a completely dark room on a Unagi.
   */
  AUTO_BRIGHTNESS_MINIMUM: 0.1,

  /*
   * This constant is used in the auto brightness algorithm. We take
   * the base 10 logarithm of the incoming lux value from the light
   * sensor and multiplied it by this constant. That value is used to
   * compute a weighted average with the current brightness and
   * finally that average brightess is and then clamped to the range
   * [AUTO_BRIGHTNESS_MINIMUM, 1.0].
   *
   * Making this value larger will increase the brightness for a given
   * ambient light level. At a value of about .25, the screen will be
   * at full brightness in sunlight or in a well-lighted work area.
   * At a value of about .3, the screen will typically be at maximum
   * brightness in outdoor daylight conditions, even when overcast.
   */
  AUTO_BRIGHTNESS_CONSTANT: .27,

  /*
   * When we change brightness we animate it smoothly.
   * This constant is the number of milliseconds between adjustments
   */
  BRIGHTNESS_ADJUST_INTERVAL: 20,

  /*
   * When brightening or dimming the screen, this is how much we adjust
   * the brightness value at a time.
   */
  BRIGHTNESS_ADJUST_STEP: 0.04,

  /*
   * Wait for _dimNotice milliseconds during idle-screen-off
   */
  _dimNotice: 10 * 1000,

  /*
   * We track the value of the idle timeout pref in this variable.
   */
  _idleTimeout: 0,
  _idleTimerId: 0,

  /*
   * If the screen off is triggered by promixity during phon call then
   * we need wake it up while phone is ended.
   */
  _screenOffByProximity: false,

  /*
   * Request wakelock during in_call state.
   * To ensure turnScreenOff by proximity event is protected by wakelock for
   * early suspend only.
   */
  _cpuWakeLock: null,

  init: function scm_init() {
    window.addEventListener('sleep', this);
    window.addEventListener('wake', this);

    this.screen = document.getElementById('screen');

    var self = this;
    var power = navigator.mozPower;

    if (power) {
      power.addWakeLockListener(function scm_handleWakeLock(topic, state) {
        switch (topic) {
          case 'screen':
            self._screenWakeLocked = (state == 'locked-foreground');

            if (self._screenWakeLocked)
              // Turn screen on if wake lock is acquire
              self.turnScreenOn();
            self._reconfigScreenTimeout();
            break;

          case 'cpu':
            power.cpuSleepAllowed = (state != 'locked-foreground' &&
                                     state != 'locked-background');
            break;
        }
      });
    }

    this._firstOn = false;
    SettingsListener.observe('screen.timeout', 60,
    function screenTimeoutChanged(value) {
      if (typeof value !== 'number')
        value = parseInt(value);
      self._idleTimeout = value;
      self._setIdleTimeout(self._idleTimeout);

      if (!self._firstOn) {
        self._firstOn = true;

        // During boot up, the brightness was set by bootloader as 0.5,
        // Let's set the API value to that so setScreenBrightness() can
        // dim nicely to value set by user.
        power.screenBrightness = 0.5;

        // Turn screen on with dim.
        self.turnScreenOn(false);
      }
    });

    SettingsListener.observe('screen.automatic-brightness', true,
    function deviceLightSettingChanged(value) {
      self.setDeviceLightEnabled(value);
    });

    SettingsListener.observe('screen.brightness', 1,
    function brightnessSettingChanged(value) {
      self._userBrightness = value;
      self.setScreenBrightness(value, false);
    });

    var telephony = window.navigator.mozTelephony;
    if (telephony) {
      telephony.addEventListener('callschanged', this);
    }
  },

  //
  // Automatically adjust the screen brightness based on the ambient
  // light (in lux) measured by the device light sensor
  //
  autoAdjustBrightness: function scm_adjustBrightness(lux) {
    var currentBrightness = this._targetBrightness;

    if (lux < 1)  // Can't take the log of 0 or negative numbers
      lux = 1;

    var computedBrightness =
      Math.log(lux) / Math.LN10 * this.AUTO_BRIGHTNESS_CONSTANT;

    var clampedBrightness = Math.max(this.AUTO_BRIGHTNESS_MINIMUM,
                                     Math.min(1.0, computedBrightness));

    // If nothing changed, we're done.
    if (clampedBrightness === currentBrightness)
      return;

    this.setScreenBrightness(clampedBrightness, false);
  },

  handleEvent: function scm_handleEvent(evt) {
    switch (evt.type) {
      case 'devicelight':
        if (!this._deviceLightEnabled || !this.screenEnabled ||
            this._inTransition)
          return;
        this.autoAdjustBrightness(evt.value);
        break;

      case 'sleep':
        this.turnScreenOff(true);
        break;

      case 'wake':
        this.turnScreenOn();
        break;

      case 'userproximity':
        this._screenOffByProximity = evt.near;
        if (evt.near) {
          this.turnScreenOff(true);
        } else {
          this.turnScreenOn();
        }
        break;

      case 'callschanged':
        var telephony = window.navigator.mozTelephony;
        if (!telephony.calls.length) {
          if (this._screenOffByProximity) {
            this.turnScreenOn();
          }

          window.removeEventListener('userproximity', this);
          this._screenOffByProximity = false;

          if (this._cpuWakeLock) {
           this._cpuWakeLock.unlock();
           this._cpuWakeLock = null;
          }
          break;
        }

        // If the _cpuWakeLock is already set we are in a multiple
        // call setup, turning the screen on to let user see the
        // notification.
        if (this._cpuWakeLock) {
          this.turnScreenOn();

          break;
        }

        // Enable the user proximity sensor once the call is connected.
        var call = telephony.calls[0];
        call.addEventListener('statechange', this);

        break;

      case 'statechange':
        var call = evt.target;
        if (call.state !== 'connected') {
          break;
        }

        // The call is connected. Remove the statechange listener
        // and enable the user proximity sensor.
        call.removeEventListener('statechange', this);

        this._cpuWakeLock = navigator.requestWakeLock('cpu');
        window.addEventListener('userproximity', this);
        break;
    }
  },

  toggleScreen: function scm_toggleScreen() {
    if (this.screenEnabled) {
      this.turnScreenOff();
    } else {
      this.turnScreenOn();
    }
  },

  turnScreenOff: function scm_turnScreenOff(instant) {
    if (!this.screenEnabled)
      return false;

    var self = this;

    // Remember the current screen brightness. We will restore it when
    // we turn the screen back on.
    self._savedBrightness = navigator.mozPower.screenBrightness;

    // Remove the cpuWakeLock if screen is not turned off by
    // userproximity event.
    if (!this._screenOffByProximity && this._cpuWakeLock) {
      window.removeEventListener('userproximity', this);
      this._cpuWakeLock.unlock();
      this._cpuWakeLock = null;
    }

    var screenOff = function scm_screenOff() {
      self._setIdleTimeout(0);

      window.removeEventListener('devicelight', self);

      self.screenEnabled = false;
      self._inTransition = false;
      self.screen.classList.add('screenoff');
      setTimeout(function realScreenOff() {
        self.setScreenBrightness(0, true);
        // Sometimes the ScreenManager.screenEnabled and mozPower.screenEnabled
        // values are out of sync. Since the rest of the world relies only on
        // the value of ScreenManager.screenEnabled it can be some situations
        // where the screen is off but ScreenManager think it is on... (see
        // bug 822463). Ideally a callback should have been used, like
        // ScreenManager.getScreenState(function(value) { ...} ); but there
        // are too many places to change that for now.
        self.screenEnabled = false;
        navigator.mozPower.screenEnabled = false;
      }, 20);

      self.fireScreenChangeEvent();
    };

    if (instant) {
      if (!WindowManager.isFtuRunning()) {
        screenOff();
      }
      return true;
    }

    this.setScreenBrightness(0.1, false);
    this._inTransition = true;
    setTimeout(function noticeTimeout() {
      if (!self._inTransition)
        return;

      screenOff();
    }, self._dimNotice);

    return true;
  },

  turnScreenOn: function scm_turnScreenOn(instant) {
    if (this.screenEnabled) {
      if (this._inTransition) {
        // Cancel the dim out
        this._inTransition = false;
        this.setScreenBrightness(this._savedBrightness, true);
        this._reconfigScreenTimeout();
      }
      return false;
    }

    // Set the brightness before the screen is on.
    this.setScreenBrightness(this._savedBrightness, instant);

    // If we are in a call and there is no cpuWakeLock,
    // we would have to get one here.
    var telephony = window.navigator.mozTelephony;
    if (!this._cpuWakeLock && telephony && telephony.calls.length) {
      telephony.calls.some(function checkCallConnection(call) {
        if (call.state == 'connected') {
          this._cpuWakeLock = navigator.requestWakeLock('cpu');
          window.addEventListener('userproximity', this);
          return true;
        }
        return false;
      }, this);
    }

    // Actually turn the screen on.
    var power = navigator.mozPower;
    if (power)
      power.screenEnabled = true;
    this.screenEnabled = true;
    this.screen.classList.remove('screenoff');

    // Attaching the event listener effectively turn on the hardware
    // device light sensor, which _must be_ done after power.screenEnabled.
    if (this._deviceLightEnabled)
      window.addEventListener('devicelight', this);

    this._reconfigScreenTimeout();
    this.fireScreenChangeEvent();

    return true;
  },

  _reconfigScreenTimeout: function scm_reconfigScreenTimeout() {
    // Remove idle timer if screen wake lock is acquired.
    if (this._screenWakeLocked) {
      this._setIdleTimeout(0);
    // The screen should be turn off with shorter timeout if
    // it was never unlocked.
    } else if (LockScreen.locked) {
      this._setIdleTimeout(10, true);
      var self = this;
      var stopShortIdleTimeout = function scm_stopShortIdleTimeout() {
        window.removeEventListener('unlock', stopShortIdleTimeout);
        window.removeEventListener('lockpanelchange', stopShortIdleTimeout);
        self._setIdleTimeout(self._idleTimeout, false);
      };

      window.addEventListener('unlock', stopShortIdleTimeout);
      window.addEventListener('lockpanelchange', stopShortIdleTimeout);
    } else {
      this._setIdleTimeout(this._idleTimeout, false);
    }
  },

  setScreenBrightness: function scm_setScreenBrightness(brightness, instant) {
    this._targetBrightness = brightness;
    var power = navigator.mozPower;
    if (!power)
      return;

    // Make sure we don't have another brightness change scheduled
    if (this._transitionBrightnessTimer) {
      clearTimeout(this._transitionBrightnessTimer);
      this._transitionBrightnessTimer = null;
    }

    if (typeof instant !== 'boolean')
      instant = true;

    if (instant) {
      power.screenBrightness = brightness;
      return;
    }

    // transitionBrightness() is a looping function that will
    // gracefully tune the brightness to _targetBrightness for us.
    this.transitionBrightness();
  },

  transitionBrightness: function scm_transitionBrightness() {
    var self = this;
    var power = navigator.mozPower;
    var screenBrightness = power.screenBrightness;
    var delta = this.BRIGHTNESS_ADJUST_STEP;

    // Is this the last time adjustment we need to make?
    if (Math.abs(this._targetBrightness - screenBrightness) <= delta) {
      power.screenBrightness = this._targetBrightness;
      this._transitionBrightnessTimer = null;
      return;
    }

    if (screenBrightness > this._targetBrightness)
      delta *= -1;

    screenBrightness += delta;
    power.screenBrightness = screenBrightness;

    this._transitionBrightnessTimer =
      setTimeout(function transitionBrightnessTimeout() {
        self.transitionBrightness();
      }, this.BRIGHTNESS_ADJUST_INTERVAL);
  },

  setDeviceLightEnabled: function scm_setDeviceLightEnabled(enabled) {
    if (!enabled && this._deviceLightEnabled) {
      // Disabled -- set the brightness back to preferred brightness
      this.setScreenBrightness(this._userBrightness, false);
    }
    this._deviceLightEnabled = enabled;

    if (!this.screenEnabled)
      return;

    // Disable/enable device light sensor accordingly.
    // This will also toggle the actual hardware, which
    // must be done while the screen is on.
    if (enabled) {
      window.addEventListener('devicelight', this);
    } else {
      window.removeEventListener('devicelight', this);
    }
  },

  _setIdleTimeout: function scm_setIdleTimeout(time, instant) {
    window.clearIdleTimeout(this._idleTimerId);

    // Reset the idled state back to false.
    this._idled = false;

    // 0 is the value used to disable idle timer by user and by us.
    if (time === 0)
      return;

    var self = this;
    var idleCallback = function idle_proxy() {
      self.turnScreenOff(instant);
    };
    var activeCallback = function active_proxy() {
      self.turnScreenOn(true);
    };

    this._idleTimerId = window.setIdleTimeout(idleCallback,
                                              activeCallback, time * 1000);
  },

  fireScreenChangeEvent: function scm_fireScreenChangeEvent() {
    var evt = new CustomEvent('screenchange',
      { bubbles: true, cancelable: false,
        detail: { screenEnabled: this.screenEnabled } });
    window.dispatchEvent(evt);
  }
};

ScreenManager.init();