Skip to content

Commit

Permalink
Add popup to select which mode, and configurable timeout
Browse files Browse the repository at this point in the history
Keep backward compatible behavior, and add a context menu option
to show the popup.
  • Loading branch information
nielm committed Mar 1, 2024
1 parent e4d5661 commit c697327
Show file tree
Hide file tree
Showing 10 changed files with 821 additions and 2,590 deletions.
14 changes: 13 additions & 1 deletion api-samples/power/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,22 @@ This extension demonstrates the `chrome.power` API by allowing users to override

## Overview

The extension adds a popup that cycles different states when clicked. It will go though a mode that prevents the display from dimming or going to sleep, a mode that keeps the system awake but allows the screen to dim/go to sleep, and a mode that uses the system's default.
The extension adds an icon that allows the user to choose different power management states when clicked:

- System Default
- Screen stays awake
- System stays awake, but screen can sleep

There is also a context menu popup where the user can also optionally specify an automatic timeout for the chosen state.

## Running this extension

Either install it from the Chrome Web Store:

- [Keep Awake Extension](https://chrome.google.com/webstore/detail/keep-awake/bijihlabcfdnabacffofojgmehjdielb)

Or load it as an upacked extension:

1. Clone this repository.
2. Load this directory in Chrome as an [unpacked extension](https://developer.chrome.com/docs/extensions/mv3/getstarted/development-basics/#load-unpacked).
3. Pin the extension and click the action button.
32 changes: 32 additions & 0 deletions api-samples/power/_locales/en/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,37 @@
"systemTitle": {
"message": "System will stay awake",
"description": "Browser action title when preventing system sleep."
},
"untilText": {
"message": " until: ",
"description": "Suffix to append to above Titles to append an end time"
},
"autoDisableText": {
"message": "Automatically disable after:",
"description": "Text labelling a slider allowing setting a timeout for disabling the power saving state."
},
"autoDisableHoursSuffix": {
"message": "h",
"description": "Text to append after a number indicating a quantity of hours"
},
"disabledLabel": {
"message": "Disabled",
"description": "Button label to indicated keep awake is disabled."
},
"displayLabel": {
"message": "Screen on",
"description": "Button label to indicated keep awake is preventing screen-off."
},
"systemLabel": {
"message": "System on",
"description": "Button label to indicated keep awake is preventing system sleep."
},
"usePopupMenuTitle": {
"message": "Always show State Popup",
"description": "Checkbox item indicating that the popup menu should always be shown."
},
"openStateWindowMenuTitle": {
"message": "Change State...",
"description": "Menu item opening a popup window to change the state."
}
}
298 changes: 239 additions & 59 deletions api-samples/power/background.js
Original file line number Diff line number Diff line change
@@ -1,47 +1,45 @@
// Copyright (c) 2013 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.
// @ts-check

/**
* States that the extension can be in.
*/
let StateEnum = {
DISABLED: 'disabled',
DISPLAY: 'display',
SYSTEM: 'system'
};
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
* Key used for storing the current state in {localStorage}.
*/
let STATE_KEY = 'state';
import { StateEnum, getSavedMode, verifyMode } from './common.js';
/** @typedef {import('./common.js').KeepAwakeMode} KeepAwakeMode */

const ALARM_NAME = 'keepAwakeTimeout';
const HOUR_TO_MILLIS = 60 * 60 * 1000;
const USE_POPUP_DEFAULT = { usePopup: true };

/**
* Loads the locally-saved state asynchronously.
* @param {function} callback Callback invoked with the loaded {StateEnum}.
* Simple timestamped log function
* @param {string} msg
* @param {...*} args
*/
function loadSavedState(callback) {
chrome.storage.local.get(STATE_KEY, function (items) {
let savedState = items[STATE_KEY];
for (let key in StateEnum) {
if (savedState == StateEnum[key]) {
callback(savedState);
return;
}
}
callback(StateEnum.DISABLED);
});
function log(msg, ...args) {
console.log(new Date().toLocaleTimeString('short') + ' ' + msg, ...args);
}

/**
* Switches to a new state.
* @param {string} newState New {StateEnum} to use.
* Set keep awake mode, and update icon.
*
* @param {KeepAwakeMode} mode
*/
function setState(newState) {
let imagePrefix = 'night';
let title = '';
function updateState(mode) {
let imagePrefix;
let title;

switch (newState) {
switch (mode.state) {
case StateEnum.DISABLED:
chrome.power.releaseKeepAwake();
imagePrefix = 'night';
Expand All @@ -58,42 +56,224 @@ function setState(newState) {
title = chrome.i18n.getMessage('systemTitle');
break;
default:
throw 'Invalid state "' + newState + '"';
throw 'Invalid state "' + mode.state + '"';
}

let items = {};
items[STATE_KEY] = newState;
chrome.storage.local.set(items);

chrome.action.setIcon({
path: {
19: 'images/' + imagePrefix + '-19.png',
38: 'images/' + imagePrefix + '-38.png'
}
});
chrome.action.setTitle({ title: title });

if (mode.endMillis && mode.state != StateEnum.DISABLED) {
// a timeout is specified, update the badge and the title text
let hoursLeft = Math.ceil((mode.endMillis - Date.now()) / HOUR_TO_MILLIS);
chrome.action.setBadgeText({ text: `${hoursLeft}h` });
const endDate = new Date(mode.endMillis);
chrome.action.setTitle({
title: `${title}${chrome.i18n.getMessage('untilText')} ${endDate.toLocaleTimeString('short')}`
});
log(
`mode = ${mode.state} for the next ${hoursLeft}hrs until ${endDate.toLocaleTimeString('short')}`
);
} else {
// No timeout.
chrome.action.setBadgeText({ text: '' });
chrome.action.setTitle({ title: title });
log(`mode = ${mode.state}`);
}
}

chrome.action.onClicked.addListener(function () {
loadSavedState(function (state) {
switch (state) {
case StateEnum.DISABLED:
setState(StateEnum.DISPLAY);
break;
case StateEnum.DISPLAY:
setState(StateEnum.SYSTEM);
break;
case StateEnum.SYSTEM:
setState(StateEnum.DISABLED);
break;
default:
throw 'Invalid state "' + state + '"';
}
/**
* Apply a new KeepAwake mode.
*
* @param {KeepAwakeMode} newMode
*/
async function setNewMode(newMode) {
// Clear any old alarms
await chrome.alarms.clearAll();

// is a timeout required?
if (newMode.defaultDurationHrs && newMode.state !== StateEnum.DISABLED) {
// Set an alarm every 60 mins.
chrome.alarms.create(ALARM_NAME, {
delayInMinutes: 60,
periodInMinutes: 60
});
newMode.endMillis =
Date.now() + newMode.defaultDurationHrs * HOUR_TO_MILLIS;
} else {
newMode.endMillis = null;
}

// Store the new mode.
chrome.storage.local.set(newMode);
updateState(newMode);
}

/**
* Check to see if any set timeout has expired, and if so, reset the mode.
*/
async function checkTimeoutAndUpdateDisplay() {
const mode = await getSavedMode();
if (mode.endMillis && mode.endMillis < Date.now()) {
log(`timer expired`);
// reset state to disabled
mode.state = StateEnum.DISABLED;
mode.endMillis = null;
setNewMode(mode);
} else {
updateState(mode);
}
}

async function recreateAlarms() {
const mode = await getSavedMode();
await chrome.alarms.clearAll();
if (
mode.state !== StateEnum.DISABLED &&
mode.endMillis &&
mode.endMillis > Date.now()
) {
// previous timeout has not yet expired...
// restart alarm to be triggered at the next 1hr of the timeout
const remainingMillis = mode.endMillis - Date.now();
const millisToNextHour = remainingMillis % HOUR_TO_MILLIS;

log(
`recreating alarm, next = ${new Date(Date.now() + millisToNextHour).toLocaleTimeString()}`
);
chrome.alarms.create(ALARM_NAME, {
delayInMinutes: millisToNextHour / 60_000,
periodInMinutes: 60
});
}
}

/**
* Creates the context menu buttons on the action icon.
*/
async function reCreateContextMenus() {
chrome.contextMenus.removeAll();

chrome.contextMenus.create({
type: 'normal',
id: 'openStateMenu',
title: chrome.i18n.getMessage('openStateWindowMenuTitle'),
contexts: ['action']
});
chrome.contextMenus.create({
type: 'checkbox',
checked: USE_POPUP_DEFAULT.usePopup,
id: 'usePopupMenu',
title: chrome.i18n.getMessage('usePopupMenuTitle'),
contexts: ['action']
});

updateUsePopupMenu(
(await chrome.storage.sync.get(USE_POPUP_DEFAULT)).usePopup
);
}

/**
* Sets whether or not to use the popup menu when clicking on the action icon.
*
* @param {boolean} usePopup
*/
function updateUsePopupMenu(usePopup) {
chrome.contextMenus.update('usePopupMenu', { checked: usePopup });
if (usePopup) {
chrome.action.setPopup({ popup: 'popup.html' });
} else {
chrome.action.setPopup({ popup: '' });
}
}

// Handle messages received from the popup.
chrome.runtime.onMessage.addListener(function (request, _, sendResponse) {
log(
`Got message from popup: state: %s, duration: %d`,
request.state,
request.duration
);
sendResponse({});

setNewMode(
verifyMode({
state: request.state,
defaultDurationHrs: request.duration,
endMillis: null
})
);
});

chrome.runtime.onStartup.addListener(function () {
loadSavedState(function (state) {
setState(state);
});
// Handle action clicks - rotates the mode to the next mode.
chrome.action.onClicked.addListener(async () => {
log(`Action clicked`);

const mode = await getSavedMode();
switch (mode.state) {
case StateEnum.DISABLED:
mode.state = StateEnum.DISPLAY;
break;
case StateEnum.DISPLAY:
mode.state = StateEnum.SYSTEM;
break;
case StateEnum.SYSTEM:
mode.state = StateEnum.DISABLED;
break;
default:
throw 'Invalid state "' + mode.state + '"';
}
setNewMode(mode);
});

// Handle context menu clicks
chrome.contextMenus.onClicked.addListener(async (e) => {
switch (e.menuItemId) {
case 'openStateMenu':
chrome.windows.create({
focused: true,
height: 220,
width: 240,
type: 'popup',
url: './popup.html'
});
break;

case 'usePopupMenu':
// e.checked is new state, after being clicked.
chrome.storage.sync.set({ usePopup: !!e.checked });
updateUsePopupMenu(!!e.checked);
break;
}
});

// Whenever the alarm is triggered check the timeout and update the icon.
chrome.alarms.onAlarm.addListener(() => {
log('alarm!');
checkTimeoutAndUpdateDisplay();
});

chrome.runtime.onStartup.addListener(async () => {
log('onStartup');
recreateAlarms();
reCreateContextMenus();
});

chrome.runtime.onInstalled.addListener(async () => {
log('onInstalled');
recreateAlarms();
reCreateContextMenus();
});

chrome.storage.sync.onChanged.addListener((changes) => {
if (changes.usePopup != null) {
log('usePopup changed to %s', changes.usePopup.newValue);
updateUsePopupMenu(!!changes.usePopup.newValue);
}
});

// Whenever the service worker starts up, check the timeout and update the state
checkTimeoutAndUpdateDisplay();
Loading

0 comments on commit c697327

Please sign in to comment.