Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Power/keepawake: Split into basic/advanced and add popup to select which mode, and configurable timeout #1115

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions api-samples/power/keepAwake Advanced/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# chrome.power

This extension demonstrates the `chrome.power` API by allowing users to override their system's power management features.

## Overview

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 popup where the user can also optionally specify an automatic
timeout for the chosen state. This popup can be triggered by clicking the icon
or by selecting it from the icon's context menu.

## 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.
58 changes: 58 additions & 0 deletions api-samples/power/keepAwake Advanced/_locales/en/messages.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
{
"extensionName": {
"message": "Keep Awake",
"description": "Extension name."
},
"extensionDescription": {
"message": "Override system power-saving settings.",
"description": "Extension description."
},
"disabledTitle": {
"message": "Default power-saving settings",
"description": "Browser action title when disabled."
},
"displayTitle": {
"message": "Screen will be kept on",
"description": "Browser action title when preventing screen-off."
},
"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"
},
"autoDisableAfterText": {
"message": "Automatically disable after:",
"description": "Text labelling a slider allowing setting a timeout for disabling the power saving state."
},
"autoDisableAtText": {
"message": "Automatically disable at: ",
"description": "Prefix Text indicating the time when the state will automatically switch to disabled."
},
"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."
}
}
287 changes: 287 additions & 0 deletions api-samples/power/keepAwake Advanced/background.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,287 @@
// @ts-check

// 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.

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 };

/**
* Simple timestamped log function
* @param {string} msg
* @param {...*} args
*/
function log(msg, ...args) {
console.log(new Date().toLocaleTimeString('short') + ' ' + msg, ...args);
}

/**
* Set keep awake mode, and update icon.
*
* @param {KeepAwakeMode} mode
*/
function updateState(mode) {
let imagePrefix;
let title;

switch (mode.state) {
case StateEnum.DISABLED:
chrome.power.releaseKeepAwake();
imagePrefix = 'night';
title = chrome.i18n.getMessage('disabledTitle');
break;
case StateEnum.DISPLAY:
chrome.power.requestKeepAwake('display');
imagePrefix = 'day';
title = chrome.i18n.getMessage('displayTitle');
break;
case StateEnum.SYSTEM:
chrome.power.requestKeepAwake('system');
imagePrefix = 'sunset';
title = chrome.i18n.getMessage('systemTitle');
break;
default:
throw 'Invalid state "' + mode.state + '"';
}

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

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(undefined, { timeStyle: 'short' })}`
});
log(
`mode = ${mode.state} for the next ${hoursLeft}hrs until ${endDate.toLocaleTimeString()}`
);
} else {
// No timeout.
chrome.action.setBadgeText({ text: '' });
chrome.action.setTitle({ title: title });
log(`mode = ${mode.state}`);
}
}

/**
*
* Apply a new KeepAwake mode.
*
* @param {KeepAwakeMode} newMode
* @return {Promise<KeepAwakeMode>}
*/
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);
return 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
);

setNewMode(
verifyMode({
state: request.state,
defaultDurationHrs: request.duration,
endMillis: null
})
)
.then((newMode) => sendResponse(newMode))
.catch((e) => {
log(`failed to set new mode: ${e}`, e);
sendResponse(null);
});
return true; // sendResponse() called asynchronously
});

// 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