diff --git a/.Rhistory b/.Rhistory new file mode 100644 index 00000000..e69de29b diff --git a/.gitignore b/.gitignore index 614ef7eb..cd68e6dc 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ *~ +*.log .pgen .last-settings mko.cpupower.policy diff --git a/.tern-project b/.tern-project new file mode 100644 index 00000000..30771939 --- /dev/null +++ b/.tern-project @@ -0,0 +1,13 @@ +{ + "libs": [ + "browser" + ], + "loadEagerly": [], + "dontLoad": [], + "plugins": { + "modules": {}, + "es_modules": {}, + "requirejs": {}, + "commonjs": {} + } +} diff --git a/README.md b/README.md index d81be67d..c550ab0f 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -

CPU Power Manager for Gnome Shell

+

CPU Power Manager for Gnome Shell - GNOME 45

Screenshot - + diff --git a/deploy.sh b/deploy.sh new file mode 100755 index 00000000..284dc38e --- /dev/null +++ b/deploy.sh @@ -0,0 +1,5 @@ +#!/bin/bash + +#echo /home/$USER/.local + +make install PREFIX=/home/$USER/.local \ No newline at end of file diff --git a/dist/rpm/SPECS/gnome-shell-extension-cpupower.spec b/dist/rpm/SPECS/gnome-shell-extension-cpupower.spec index ec2fc565..b4a4b5a7 100644 --- a/dist/rpm/SPECS/gnome-shell-extension-cpupower.spec +++ b/dist/rpm/SPECS/gnome-shell-extension-cpupower.spec @@ -74,18 +74,14 @@ rm -rf $RPM_BUILD_ROOT /usr/share/gnome-shell/extensions/cpupower@mko-sl.de/prefs.js /usr/share/gnome-shell/extensions/cpupower@mko-sl.de/schemas/gschemas.compiled /usr/share/gnome-shell/extensions/cpupower@mko-sl.de/schemas/io.github.martin31821.cpupower.dbus.xml -/usr/share/gnome-shell/extensions/cpupower@mko-sl.de/src/barLevel2.js /usr/share/gnome-shell/extensions/cpupower@mko-sl.de/src/baseindicator.js /usr/share/gnome-shell/extensions/cpupower@mko-sl.de/src/config.js /usr/share/gnome-shell/extensions/cpupower@mko-sl.de/src/convenience.js /usr/share/gnome-shell/extensions/cpupower@mko-sl.de/src/indicator.js /usr/share/gnome-shell/extensions/cpupower@mko-sl.de/src/notinstalled.js /usr/share/gnome-shell/extensions/cpupower@mko-sl.de/src/preferences.js -/usr/share/gnome-shell/extensions/cpupower@mko-sl.de/src/prefs40/main.js -/usr/share/gnome-shell/extensions/cpupower@mko-sl.de/src/prefs40/misc.js /usr/share/gnome-shell/extensions/cpupower@mko-sl.de/src/profile.js /usr/share/gnome-shell/extensions/cpupower@mko-sl.de/src/profilebutton.js -/usr/share/gnome-shell/extensions/cpupower@mko-sl.de/src/slider2.js /usr/share/gnome-shell/extensions/cpupower@mko-sl.de/src/update.js /usr/share/gnome-shell/extensions/cpupower@mko-sl.de/src/utils.js /usr/share/gnome-shell/extensions/cpupower@mko-sl.de/tool/cpufreqctl diff --git a/extension.js b/extension.js index 7dbb12fe..500d9598 100644 --- a/extension.js +++ b/extension.js @@ -25,111 +25,106 @@ * */ -const ExtensionUtils = imports.misc.extensionUtils; -const Me = ExtensionUtils.getCurrentExtension(); -const EXTENSIONDIR = Me.dir.get_path(); -const Convenience = Me.imports.src.convenience; -const Main = imports.ui.main; -const Config = imports.misc.config; -const ByteArray = imports.byteArray; +import * as Main from 'resource:///org/gnome/shell/ui/main.js'; +import * as Config from 'resource:///org/gnome/shell/misc/config.js'; +import {Extension} from 'resource:///org/gnome/shell/extensions/extension.js'; -const utils = Me.imports.src.utils; -const checkInstalled = Me.imports.src.utils.checkInstalled; -const notinstalled = Me.imports.src.notinstalled; -const update = Me.imports.src.update; -const indicator = Me.imports.src.indicator; +import * as utils from './src/utils.js'; +import {checkInstalled} from './src/utils.js'; +import * as notinstalled from './src/notinstalled.js'; +import * as update from './src/update.js'; +import * as indicator from './src/indicator.js'; -const Gio = imports.gi.Gio; -const GLib = imports.gi.GLib; +import Gio from 'gi://Gio'; +import GLib from 'gi://GLib'; -let indicatorInstance; -/* exported init */ -function init(_meta) { - Convenience.initTranslations("gnome-shell-extension-cpupower"); -} +const EXTENSIONDIR = import.meta.url.substr('file://'.length, import.meta.url.lastIndexOf('/') - 'file://'.length); -function enableIndicator(instance) { - Main.panel.addToStatusArea("cpupower", instance.mainButton); - instance.enable(); -} +export default class CPUPowerExtension extends Extension { + constructor(...args) { + super(...args); + this.indicatorInstance = null; + this.cpupowerProxy = null; + this.extensionReloadSignalHandler = null; + } -let cpupowerProxy; -let extensionReloadSignalHandler; -/* exported enable */ -function enable() { - const interfaceBinary = GLib.file_get_contents(`${EXTENSIONDIR}/schemas/io.github.martin31821.cpupower.dbus.xml`)[1]; - let interfaceXml; - if (parseFloat(Config.PACKAGE_VERSION.substring(0, 4)) > 3.28) { - interfaceXml = ByteArray.toString(interfaceBinary); - } else { - interfaceXml = interfaceBinary.toString(); + enableIndicator(instance) { + Main.panel.addToStatusArea("cpupower", instance.mainButton); + instance.enable(); } - const CpupowerProxy = Gio.DBusProxy.makeProxyWrapper(interfaceXml); - cpupowerProxy = new CpupowerProxy( - Gio.DBus.session, - "io.github.martin31821.cpupower", - "/io/github/martin31821/cpupower", - ); + /* exported enable */ + enable() { + const interfaceBinary = GLib.file_get_contents(`${EXTENSIONDIR}/schemas/io.github.martin31821.cpupower.dbus.xml`)[1]; + let decoder = new TextDecoder('utf-8'); + let interfaceXml = decoder.decode(interfaceBinary); + const CpupowerProxy = Gio.DBusProxy.makeProxyWrapper(interfaceXml); - extensionReloadSignalHandler = cpupowerProxy.connectSignal("ExtensionReloadRequired", () => { - log("Reloading cpupower"); - disable(); - enable(); - }); + this.cpupowerProxy = new CpupowerProxy( + Gio.DBus.session, + "io.github.martin31821.cpupower", + "/io/github/martin31821/cpupower", + ); - try { - checkInstalled((installed, exitCode) => { - if (!installed) { - switch (exitCode) { - case utils.INSTALLER_NEEDS_UPDATE: - indicatorInstance = new update.UpdateIndicator(update.UPDATE, function (success) { - if (success) { - // reenable the extension to allow immediate operation. - disable(); - enable(); - } - }, (inst) => enableIndicator(inst)); - break; - case utils.INSTALLER_NEEDS_SECURITY_UPDATE: - indicatorInstance = new update.UpdateIndicator(update.SECURITY_UPDATE, function (success) { - if (success) { - // reenable the extension to allow immediate operation. - disable(); - enable(); - } - }, (inst) => enableIndicator(inst)); - break; - default: - indicatorInstance = new notinstalled.NotInstalledIndicator(exitCode, function (success) { - if (success) { - // reenable the extension to allow immediate operation. - disable(); - enable(); - } - }, (inst) => enableIndicator(inst)); - break; - } - } else { - indicatorInstance = new indicator.CPUFreqIndicator((inst) => enableIndicator(inst)); - } + this.extensionReloadSignalHandler = this.cpupowerProxy.connectSignal("ExtensionReloadRequired", () => { + log("Reloading cpupower"); + this.disable(); + this.enable(); }); - } catch (e) { - logError(e.message); - } -} -/* exported disable */ -function disable() { - if (indicatorInstance) { - indicatorInstance.disable(); - indicatorInstance.destroy(); + try { + checkInstalled((installed, exitCode) => { + if (!installed) { + switch (exitCode) { + case utils.INSTALLER_NEEDS_UPDATE: + this.indicatorInstance = new update.UpdateIndicator(update.UPDATE, function (success) { + if (success) { + // reenable the extension to allow immediate operation. + disable(); + enable(); + } + }, (inst) => this.enableIndicator(inst)); + break; + case utils.INSTALLER_NEEDS_SECURITY_UPDATE: + this.indicatorInstance = new update.UpdateIndicator(update.SECURITY_UPDATE, function (success) { + if (success) { + // reenable the extension to allow immediate operation. + disable(); + enable(); + } + }, (inst) => this.enableIndicator(inst)); + break; + default: + this.indicatorInstance = new notinstalled.NotInstalledIndicator(exitCode, function (success) { + if (success) { + // reenable the extension to allow immediate operation. + disable(); + enable(); + } + }, (inst) => this.enableIndicator(inst)); + break; + } + } else { + this.indicatorInstance = new indicator.CPUFreqIndicator((inst) => this.enableIndicator(inst)); + } + }); + } catch (e) { + logError(e); + } } - if (cpupowerProxy && extensionReloadSignalHandler) { - cpupowerProxy.disconnectSignal(extensionReloadSignalHandler); + /* exported disable */ + disable() { + if (this.indicatorInstance) { + this.indicatorInstance.disable(); + this.indicatorInstance.destroy(); + } + + if (this.cpupowerProxy && this.extensionReloadSignalHandler) { + this.cpupowerProxy.disconnectSignal(this.extensionReloadSignalHandler); - cpupowerProxy = null; - extensionReloadSignalHandler = null; + this.cpupowerProxy = null; + this.extensionReloadSignalHandler = null; + } } } diff --git a/metadata.json b/metadata.json index a5f4ee8f..15df44bf 100644 --- a/metadata.json +++ b/metadata.json @@ -1,11 +1,10 @@ { - "localedir": "/usr/local/share/locale", - "shell-version": [ - "3.28", "3.30", "3.36", "3.38", "40", "41", "42" - ], - "uuid": "cpupower@mko-sl.de", - "name": "CPU Power Manager", - "url": "https://github.com/deinstapel/cpupower", - "description": "Manage your CPU's frequency scaling driver", - "schema": "org.gnome.shell.extensions.cpupower" + "localedir": "/usr/local/share/locale", + "shell-version": ["45", "45.1", "45.2", "45.3", "46", "47"], + "uuid": "cpupower@mko-sl.de", + "name": "CPU Power Manager", + "url": "https://github.com/deinstapel/cpupower", + "description": "Manage your CPU's frequency scaling driver", + "settings-schema": "org.gnome.shell.extensions.cpupower", + "gettext-domain": "cpupower" } diff --git a/prefs.js b/prefs.js index 9d0344f7..1d91263d 100644 --- a/prefs.js +++ b/prefs.js @@ -26,41 +26,22 @@ * */ -const ExtensionUtils = imports.misc.extensionUtils; -const Me = ExtensionUtils.getCurrentExtension(); -const EXTENSIONDIR = Me.dir.get_path(); -const Convenience = Me.imports.src.convenience; -const CPUPowerPreferences = Me.imports.src.preferences.CPUPowerPreferences; -const GLib = imports.gi.GLib; -const Gtk = imports.gi.Gtk; +import {ExtensionPreferences} from 'resource:///org/gnome/Shell/Extensions/js/extensions/prefs.js'; +import {CPUPowerPreferencesContent} from './src/preferences.js'; +import Gtk from 'gi://Gtk'; -/* exported init */ -function init() { - Convenience.initTranslations("gnome-shell-extension-cpupower"); -} - -/* exported buildPrefsWidget */ -function buildPrefsWidget() { - if (Gtk.get_major_version() === 4) { - let dummy = new Gtk.Label(); - GLib.timeout_add(GLib.PRIORITY_DEFAULT, 0, () => { - let window = dummy.get_root(); - window.close(); - - GLib.spawn_sync( - null, - [`${EXTENSIONDIR}/src/prefs40/main.js`], - null, - null, - null, - ); - - return GLib.SOURCE_REMOVE; +export default class CPUPowerPreferences extends ExtensionPreferences { + fillPreferencesWindow(win) { + win._settings = this.getSettings(); + win.connect("delete-event", () => { + Gtk.main_quit(); }); - return dummy; - } else { - let preferences = new CPUPowerPreferences(); - - return preferences.show(); + let headerbar = new Gtk.HeaderBar(); + headerbar.set_show_close_button(true); + headerbar.title = "CPU Power Manager"; + let preferences = new CPUPowerPreferencesContent(); + let mainWidget = preferences.show(); + win.set_titlebar(headerbar); + win.add(mainWidget); } } diff --git a/src/barLevel2.js b/src/barLevel2.js index a8f5dabd..2dcf2c42 100644 --- a/src/barLevel2.js +++ b/src/barLevel2.js @@ -8,384 +8,552 @@ * See for details. */ -const {Atk, Clutter, GObject, St} = imports.gi; -const Config = imports.misc.config; +import Clutter from "gi://Clutter"; +import Atk from "gi://Atk"; +import St from "gi://St"; +import GObject from "gi://GObject"; + +import * as Config from "resource:///org/gnome/shell/misc/config.js"; /* exported BarLevel2 */ -var BarLevel2 = GObject.registerClass({ - GTypeName: "BarLevel2", - Properties: { - "value": GObject.ParamSpec.double( - "value", "value", "value", - GObject.ParamFlags.READWRITE, - 0, Number.MAX_SAFE_INTEGER, 0), - "maximum-value": GObject.ParamSpec.double( - "maximum-value", "maximum-value", "maximum-value", - GObject.ParamFlags.READWRITE, - 1, Number.MAX_SAFE_INTEGER, 1), - "overdrive-start": GObject.ParamSpec.double( - "overdrive-start", "overdrive-start", "overdrive-start", - GObject.ParamFlags.READWRITE, - 1, Number.MAX_SAFE_INTEGER, 1), - "limit-minimum": GObject.ParamSpec.double( - "limit-minimum", "limit-minimum", "limit-minimum", - GObject.ParamFlags.READWRITE, - 0, Number.MAX_SAFE_INTEGER, 0), - "limit-maximum": GObject.ParamSpec.double( - "limit-maximum", "limit-maximum", "limit-maximum", - GObject.ParamFlags.READWRITE, - 0, Number.MAX_SAFE_INTEGER, 1), +var BarLevel2 = GObject.registerClass( + { + GTypeName: "BarLevel2", + Properties: { + value: GObject.ParamSpec.double( + "value", + "value", + "value", + GObject.ParamFlags.READWRITE, + 0, + Number.MAX_SAFE_INTEGER, + 0 + ), + "maximum-value": GObject.ParamSpec.double( + "maximum-value", + "maximum-value", + "maximum-value", + GObject.ParamFlags.READWRITE, + 1, + Number.MAX_SAFE_INTEGER, + 1 + ), + "overdrive-start": GObject.ParamSpec.double( + "overdrive-start", + "overdrive-start", + "overdrive-start", + GObject.ParamFlags.READWRITE, + 1, + Number.MAX_SAFE_INTEGER, + 1 + ), + "limit-minimum": GObject.ParamSpec.double( + "limit-minimum", + "limit-minimum", + "limit-minimum", + GObject.ParamFlags.READWRITE, + 0, + Number.MAX_SAFE_INTEGER, + 0 + ), + "limit-maximum": GObject.ParamSpec.double( + "limit-maximum", + "limit-maximum", + "limit-maximum", + GObject.ParamFlags.READWRITE, + 0, + Number.MAX_SAFE_INTEGER, + 1 + ), + }, }, -}, class BarLevel2 extends St.DrawingArea { - _init(params) { - this._maxValue = 1; - this._value = 0; - this._overdriveStart = 1; - this._barLevelWidth = 0; - this._limitMin = 0; - this._limitMax = this._maxValue; - - let defaultParams = { - style_class: "barlevel", - accessible_role: Atk.Role.LEVEL_BAR, - }; - super._init(Object.assign(defaultParams, params)); - this.connect("notify::allocation", () => { - this._barLevelWidth = this.allocation.get_width(); - }); - - this._customAccessible = St.GenericAccessible.new_for_actor(this); - this.set_accessible(this._customAccessible); - - this._customAccessible.connect("get-current-value", this._getCurrentValue.bind(this)); - this._customAccessible.connect("get-minimum-value", this._getMinimumValue.bind(this)); - this._customAccessible.connect("get-maximum-value", this._getMaximumValue.bind(this)); - this._customAccessible.connect("set-current-value", this._setCurrentValue.bind(this)); - - this.connect("notify::value", this._valueChanged.bind(this)); - } - - get value() { - return this._value; - } - - set value(value) { - value = Math.max(Math.min(value, this._maxValue), 0); - - if (this._value === value) { - return; + class BarLevel2 extends St.DrawingArea { + _init(params) { + this._maxValue = 1; + this._value = 0; + this._overdriveStart = 1; + this._barLevelWidth = 0; + this._limitMin = 0; + this._limitMax = this._maxValue; + + let defaultParams = { + style_class: "barlevel", + accessible_role: Atk.Role.LEVEL_BAR, + }; + super._init(Object.assign(defaultParams, params)); + this.connect("notify::allocation", () => { + this._barLevelWidth = this.allocation.get_width(); + }); + + this._customAccessible = St.GenericAccessible.new_for_actor(this); + this.set_accessible(this._customAccessible); + + this._customAccessible.connect( + "get-current-value", + this._getCurrentValue.bind(this) + ); + this._customAccessible.connect( + "get-minimum-value", + this._getMinimumValue.bind(this) + ); + this._customAccessible.connect( + "get-maximum-value", + this._getMaximumValue.bind(this) + ); + this._customAccessible.connect( + "set-current-value", + this._setCurrentValue.bind(this) + ); + + this.connect("notify::value", this._valueChanged.bind(this)); } - this._value = value; - this.notify("value"); - this.queue_repaint(); - } - - get limit_minimum() { - return this._limitMin; - } - - set limit_minimum(value) { - value = Math.max(Math.min(value, this.limit_maximum), 0); - - if (this._limitMin === value) { - return; + get value() { + return this._value; } - this._limitMin = value; - this.notify("limit-minimum"); - this.queue_repaint(); - } + set value(value) { + value = Math.max(Math.min(value, this._maxValue), 0); - get limit_maximum() { - return this._limitMax; - } + if (this._value === value) { + return; + } - set limit_maximum(value) { - value = Math.max(Math.min(value, this._maxValue), this.limit_minimum); + this._value = value; + this.notify("value"); + this.queue_repaint(); + } - if (this._limitMax === value) { - return; + get limit_minimum() { + return this._limitMin; } - this._limitMax = value; - this.notify("limit-maximum"); - this.queue_repaint(); - } + set limit_minimum(value) { + value = Math.max(Math.min(value, this.limit_maximum), 0); - // eslint-disable-next-line camelcase - get maximum_value() { - return this._maxValue; - } + if (this._limitMin === value) { + return; + } - // eslint-disable-next-line camelcase - set maximum_value(value) { - value = Math.max(value, 1); + this._limitMin = value; + this.notify("limit-minimum"); + this.queue_repaint(); + } - if (this._maxValue === value) { - return; + get limit_maximum() { + return this._limitMax; } - this._maxValue = value; - this._overdriveStart = Math.min(this._overdriveStart, this._maxValue); - this.notify("maximum-value"); - this.queue_repaint(); - } + set limit_maximum(value) { + value = Math.max( + Math.min(value, this._maxValue), + this.limit_minimum + ); - // eslint-disable-next-line camelcase - get overdrive_start() { - return this._overdriveStart; - } + if (this._limitMax === value) { + return; + } - // eslint-disable-next-line camelcase - set overdrive_start(value) { - if (this._overdriveStart === value) { - return; + this._limitMax = value; + this.notify("limit-maximum"); + this.queue_repaint(); } - if (value > this._maxValue) { - throw new Error(`Tried to set overdrive value to ${value}, ` + - `which is a number greater than the maximum allowed value ${this._maxValue}`); + // eslint-disable-next-line camelcase + get maximum_value() { + return this._maxValue; } - this._overdriveStart = value; - this.notify("overdrive-start"); - this.queue_repaint(); - } - - vfunc_repaint() { - let cr = this.get_context(); - let themeNode = this.get_theme_node(); - let [width, height] = this.get_surface_size(); - - // fix for old Gnome releases - let prefix = parseFloat(Config.PACKAGE_VERSION.substring(0, 4)) > 3.29 ? "-barlevel" : "-slider"; + // eslint-disable-next-line camelcase + set maximum_value(value) { + value = Math.max(value, 1); - let barLevelHeight = themeNode.get_length(`${prefix}-height`); - let barLevelBorderRadius = Math.min(width, barLevelHeight) / 2; - let fgColor = themeNode.get_foreground_color(); + if (this._maxValue === value) { + return; + } - let barLevelColor = themeNode.get_color(`${prefix}-background-color`); - let barLevelActiveColor = themeNode.get_color(`${prefix}-active-background-color`); - let barLevelOverdriveColor; - if (parseFloat(Config.PACKAGE_VERSION.substring(0, 4)) > 3.29) { - barLevelOverdriveColor = themeNode.get_color("-barlevel-overdrive-color"); + this._maxValue = value; + this._overdriveStart = Math.min( + this._overdriveStart, + this._maxValue + ); + this.notify("maximum-value"); + this.queue_repaint(); } - let barLevelBorderWidth = Math.min(themeNode.get_length(`${prefix}-border-width`), 1); - let [hasBorderColor, barLevelBorderColor] = - themeNode.lookup_color(`${prefix}-border-color`, false); - if (!hasBorderColor) { - barLevelBorderColor = barLevelColor; - } - let [hasActiveBorderColor, barLevelActiveBorderColor] = - themeNode.lookup_color(`${prefix}-active-border-color`, false); - if (!hasActiveBorderColor) { - barLevelActiveBorderColor = barLevelActiveColor; + // eslint-disable-next-line camelcase + get overdrive_start() { + return this._overdriveStart; } - let hasOverdriveBorderColor, barLevelOverdriveBorderColor; - if (parseFloat(Config.PACKAGE_VERSION.substring(0, 4)) > 3.29) { - [hasOverdriveBorderColor, barLevelOverdriveBorderColor] = - themeNode.lookup_color("-barlevel-overdrive-border-color", false); - if (!hasOverdriveBorderColor) { - barLevelOverdriveBorderColor = barLevelOverdriveColor; + // eslint-disable-next-line camelcase + set overdrive_start(value) { + if (this._overdriveStart === value) { + return; } - } - const TAU = Math.PI * 2; + if (value > this._maxValue) { + throw new Error( + `Tried to set overdrive value to ${value}, ` + + `which is a number greater than the maximum allowed value ${this._maxValue}` + ); + } - let endX = 0; - if (this._maxValue > 0) { - endX = barLevelBorderRadius + (width - 2 * barLevelBorderRadius) * this._value / this._maxValue; + this._overdriveStart = value; + this.notify("overdrive-start"); + this.queue_repaint(); } - let overdriveSeparatorX = barLevelBorderRadius + (width - 2 * barLevelBorderRadius) * this._overdriveStart / this._maxValue; - let overdriveActive = this._overdriveStart !== this._maxValue && parseFloat(Config.PACKAGE_VERSION.substring(0, 4)) > 3.29; - let overdriveSeparatorWidth = 0; - if (overdriveActive) { - overdriveSeparatorWidth = themeNode.get_length("-barlevel-overdrive-separator-width"); - } + vfunc_repaint() { + let cr = this.get_context(); + let themeNode = this.get_theme_node(); + let [width, height] = this.get_surface_size(); + + // fix for old Gnome releases + let prefix = + parseFloat(Config.PACKAGE_VERSION.substring(0, 4)) > 3.29 + ? "-barlevel" + : "-slider"; + + let barLevelHeight = themeNode.get_length(`${prefix}-height`); + let barLevelBorderRadius = Math.min(width, barLevelHeight) / 2; + let fgColor = themeNode.get_foreground_color(); + + let barLevelColor = themeNode.get_color( + `${prefix}-background-color` + ); + let barLevelActiveColor = themeNode.get_color( + `${prefix}-active-background-color` + ); + let barLevelOverdriveColor; + if (parseFloat(Config.PACKAGE_VERSION.substring(0, 4)) > 3.29) { + barLevelOverdriveColor = themeNode.get_color( + "-barlevel-overdrive-color" + ); + } - let deadBarColor = barLevelColor; - let deadBarBorderColor = barLevelBorderColor; + let barLevelBorderWidth = Math.min( + themeNode.get_length(`${prefix}-border-width`), + 1 + ); + let [hasBorderColor, barLevelBorderColor] = themeNode.lookup_color( + `${prefix}-border-color`, + false + ); + if (!hasBorderColor) { + barLevelBorderColor = barLevelColor; + } + let [hasActiveBorderColor, barLevelActiveBorderColor] = + themeNode.lookup_color(`${prefix}-active-border-color`, false); + if (!hasActiveBorderColor) { + barLevelActiveBorderColor = barLevelActiveColor; + } - // performance optimization - let barLevelTop = (height - barLevelHeight) / 2; - let barLevelBottom = (height + barLevelHeight) / 2; + let hasOverdriveBorderColor, barLevelOverdriveBorderColor; + if (parseFloat(Config.PACKAGE_VERSION.substring(0, 4)) > 3.29) { + [hasOverdriveBorderColor, barLevelOverdriveBorderColor] = + themeNode.lookup_color( + "-barlevel-overdrive-border-color", + false + ); + if (!hasOverdriveBorderColor) { + barLevelOverdriveBorderColor = barLevelOverdriveColor; + } + } - /* background bar */ - let bx = (barLevelBorderRadius + (width - 2 * barLevelBorderRadius) * this._limitMax / this._maxValue) + barLevelBorderRadius; - let startLimitMax = this._limitMax < this._maxValue ? bx : width - barLevelBorderRadius - barLevelBorderWidth; - if (this._limitMax < this._maxValue) { - cr.lineTo(startLimitMax, barLevelBottom); - } else { - cr.arc(startLimitMax, height / 2, barLevelBorderRadius, TAU * (3 / 4), TAU * (1 / 4)); - } - cr.lineTo(endX, barLevelBottom); - cr.lineTo(endX, barLevelTop); - cr.lineTo(startLimitMax, barLevelTop); - Clutter.cairo_set_source_color(cr, barLevelColor); - cr.fillPreserve(); - Clutter.cairo_set_source_color(cr, barLevelBorderColor); - cr.setLineWidth(barLevelBorderWidth); - cr.stroke(); - - // limit minimum - bx = 0; - if (this._limitMin > 0) { - bx = barLevelBorderRadius + (width - 2 * barLevelBorderRadius) * this._limitMin / this._maxValue; - cr.arc(barLevelBorderRadius + barLevelBorderWidth, height / 2, barLevelBorderRadius, TAU * (1 / 4), TAU * (3 / 4)); - cr.lineTo(bx, barLevelTop); - cr.lineTo(bx, barLevelBottom); - cr.lineTo(barLevelBorderRadius + barLevelBorderWidth, barLevelBottom); - if (this._value > 0) { - Clutter.cairo_set_source_color(cr, deadBarColor); + const TAU = Math.PI * 2; + + let endX = 0; + if (this._maxValue > 0) { + endX = + barLevelBorderRadius + + ((width - 2 * barLevelBorderRadius) * this._value) / + this._maxValue; } - cr.fillPreserve(); - Clutter.cairo_set_source_color(cr, deadBarBorderColor); - cr.setLineWidth(barLevelBorderWidth); - cr.stroke(); - } - /* normal progress bar */ - let x = Math.min(endX, overdriveSeparatorX - overdriveSeparatorWidth / 2); - let startX = this._limitMin > 0 ? bx : barLevelBorderRadius + barLevelBorderWidth + bx; - if (this._limitMin > 0) { - cr.lineTo(startX, barLevelTop); - } else { - cr.arc(startX, height / 2, barLevelBorderRadius, TAU * (1 / 4), TAU * (3 / 4)); - } - cr.lineTo(x, barLevelTop); - cr.lineTo(x, barLevelBottom); - cr.lineTo(startX, barLevelBottom); - if (this._value > 0) { - Clutter.cairo_set_source_color(cr, barLevelActiveColor); - } - cr.fillPreserve(); - Clutter.cairo_set_source_color(cr, barLevelActiveBorderColor); - cr.setLineWidth(barLevelBorderWidth); - cr.stroke(); - - /* overdrive progress barLevel */ - x = Math.min(endX, overdriveSeparatorX) + overdriveSeparatorWidth / 2; - if (this._value > this._overdriveStart) { - cr.moveTo(x, barLevelTop); - cr.lineTo(endX, barLevelTop); - cr.lineTo(endX, barLevelBottom); - cr.lineTo(x, barLevelBottom); - cr.lineTo(x, barLevelTop); - Clutter.cairo_set_source_color(cr, barLevelOverdriveColor); - cr.fillPreserve(); - Clutter.cairo_set_source_color(cr, barLevelOverdriveBorderColor); - cr.setLineWidth(barLevelBorderWidth); - cr.stroke(); - } + let overdriveSeparatorX = + barLevelBorderRadius + + ((width - 2 * barLevelBorderRadius) * this._overdriveStart) / + this._maxValue; + let overdriveActive = + this._overdriveStart !== this._maxValue && + parseFloat(Config.PACKAGE_VERSION.substring(0, 4)) > 3.29; + let overdriveSeparatorWidth = 0; + if (overdriveActive) { + overdriveSeparatorWidth = themeNode.get_length( + "-barlevel-overdrive-separator-width" + ); + } - /* end progress bar arc */ - if (this._value > 0) { - if (this._value <= this._overdriveStart) { - Clutter.cairo_set_source_color(cr, barLevelActiveColor); + let deadBarColor = barLevelColor; + let deadBarBorderColor = barLevelBorderColor; + + // performance optimization + let barLevelTop = (height - barLevelHeight) / 2; + let barLevelBottom = (height + barLevelHeight) / 2; + + /* background bar */ + let bx = + barLevelBorderRadius + + ((width - 2 * barLevelBorderRadius) * this._limitMax) / + this._maxValue + + barLevelBorderRadius; + let startLimitMax = + this._limitMax < this._maxValue + ? bx + : width - barLevelBorderRadius - barLevelBorderWidth; + if (this._limitMax < this._maxValue) { + cr.lineTo(startLimitMax, barLevelBottom); } else { - Clutter.cairo_set_source_color(cr, barLevelOverdriveColor); + cr.arc( + startLimitMax, + height / 2, + barLevelBorderRadius, + TAU * (3 / 4), + TAU * (1 / 4) + ); } - cr.arc(endX, height / 2, barLevelBorderRadius, TAU * (3 / 4), TAU * (1 / 4)); - cr.lineTo(Math.floor(endX), barLevelBottom); - cr.lineTo(Math.floor(endX), barLevelTop); + cr.lineTo(endX, barLevelBottom); cr.lineTo(endX, barLevelTop); + cr.lineTo(startLimitMax, barLevelTop); + Clutter.cairo_set_source_color(cr, barLevelColor); cr.fillPreserve(); + Clutter.cairo_set_source_color(cr, barLevelBorderColor); cr.setLineWidth(barLevelBorderWidth); cr.stroke(); - } - // limit maximum - if (this._limitMax < this._maxValue) { - bx = (barLevelBorderRadius + (width - 2 * barLevelBorderRadius) * this._limitMax / this._maxValue) + barLevelBorderRadius; - cr.arc(width - barLevelBorderRadius - barLevelBorderWidth, height / 2, barLevelBorderRadius, TAU * (3 / 4), TAU * (1 / 4)); - cr.lineTo(bx, barLevelBottom); - cr.lineTo(bx, barLevelTop); - cr.lineTo(width - barLevelBorderRadius - barLevelBorderWidth, barLevelTop); - Clutter.cairo_set_source_color(cr, deadBarColor); - cr.fillPreserve(); - Clutter.cairo_set_source_color(cr, deadBarBorderColor); - cr.setLineWidth(barLevelBorderWidth); - cr.stroke(); - } + // limit minimum + bx = 0; + if (this._limitMin > 0) { + bx = + barLevelBorderRadius + + ((width - 2 * barLevelBorderRadius) * this._limitMin) / + this._maxValue; + cr.arc( + barLevelBorderRadius + barLevelBorderWidth, + height / 2, + barLevelBorderRadius, + TAU * (1 / 4), + TAU * (3 / 4) + ); + cr.lineTo(bx, barLevelTop); + cr.lineTo(bx, barLevelBottom); + cr.lineTo( + barLevelBorderRadius + barLevelBorderWidth, + barLevelBottom + ); + if (this._value > 0) { + Clutter.cairo_set_source_color(cr, deadBarColor); + } + cr.fillPreserve(); + Clutter.cairo_set_source_color(cr, deadBarBorderColor); + cr.setLineWidth(barLevelBorderWidth); + cr.stroke(); + } - /* draw overdrive separator */ - if (overdriveActive) { - cr.moveTo(overdriveSeparatorX - overdriveSeparatorWidth / 2, barLevelTop); - cr.lineTo(overdriveSeparatorX + overdriveSeparatorWidth / 2, barLevelTop); - cr.lineTo(overdriveSeparatorX + overdriveSeparatorWidth / 2, barLevelBottom); - cr.lineTo(overdriveSeparatorX - overdriveSeparatorWidth / 2, barLevelBottom); - cr.lineTo(overdriveSeparatorX - overdriveSeparatorWidth / 2, barLevelTop); - if (this._value <= this._overdriveStart) { - Clutter.cairo_set_source_color(cr, fgColor); + /* normal progress bar */ + let x = Math.min( + endX, + overdriveSeparatorX - overdriveSeparatorWidth / 2 + ); + let startX = + this._limitMin > 0 + ? bx + : barLevelBorderRadius + barLevelBorderWidth + bx; + if (this._limitMin > 0) { + cr.lineTo(startX, barLevelTop); } else { - Clutter.cairo_set_source_color(cr, barLevelColor); + cr.arc( + startX, + height / 2, + barLevelBorderRadius, + TAU * (1 / 4), + TAU * (3 / 4) + ); + } + cr.lineTo(x, barLevelTop); + cr.lineTo(x, barLevelBottom); + cr.lineTo(startX, barLevelBottom); + if (this._value > 0) { + Clutter.cairo_set_source_color(cr, barLevelActiveColor); } - cr.fill(); - } - - let limit_sep_height = height / 4; - let limit_sep_width = Math.max(2, barLevelHeight / 2); - - // draw blocked minimum region seperator - if (this._limitMin > 0) { - bx = barLevelBorderRadius + (width - 2 * barLevelBorderRadius) * this._limitMin / this._maxValue; - bx = Math.round(bx); - cr.moveTo(bx, barLevelTop - limit_sep_height); - cr.lineTo(bx, barLevelBottom + limit_sep_height); - cr.lineTo(bx - limit_sep_width, barLevelBottom + limit_sep_height); - cr.lineTo(bx - limit_sep_width, barLevelTop - limit_sep_height); - cr.lineTo(bx, barLevelTop - limit_sep_height); - Clutter.cairo_set_source_color(cr, barLevelActiveColor); cr.fillPreserve(); Clutter.cairo_set_source_color(cr, barLevelActiveBorderColor); cr.setLineWidth(barLevelBorderWidth); cr.stroke(); - } - // draw blocked maximum region seperator - if (this._limitMax < this._maxValue) { - bx = (barLevelBorderRadius + (width - 2 * barLevelBorderRadius) * this._limitMax / this._maxValue) + barLevelBorderRadius; - bx = Math.round(bx); - cr.moveTo(bx, barLevelTop - limit_sep_height); - cr.lineTo(bx, barLevelBottom + limit_sep_height); - cr.lineTo(bx + limit_sep_width, barLevelBottom + limit_sep_height); - cr.lineTo(bx + limit_sep_width, barLevelTop - limit_sep_height); - cr.lineTo(bx, barLevelTop - limit_sep_height); - Clutter.cairo_set_source_color(cr, barLevelActiveColor); - cr.fillPreserve(); - Clutter.cairo_set_source_color(cr, barLevelActiveBorderColor); - cr.setLineWidth(barLevelBorderWidth); - cr.stroke(); - } + /* overdrive progress barLevel */ + x = + Math.min(endX, overdriveSeparatorX) + + overdriveSeparatorWidth / 2; + if (this._value > this._overdriveStart) { + cr.moveTo(x, barLevelTop); + cr.lineTo(endX, barLevelTop); + cr.lineTo(endX, barLevelBottom); + cr.lineTo(x, barLevelBottom); + cr.lineTo(x, barLevelTop); + Clutter.cairo_set_source_color(cr, barLevelOverdriveColor); + cr.fillPreserve(); + Clutter.cairo_set_source_color( + cr, + barLevelOverdriveBorderColor + ); + cr.setLineWidth(barLevelBorderWidth); + cr.stroke(); + } - cr.$dispose(); - } + /* end progress bar arc */ + if (this._value > 0) { + if (this._value <= this._overdriveStart) { + Clutter.cairo_set_source_color(cr, barLevelActiveColor); + } else { + Clutter.cairo_set_source_color(cr, barLevelOverdriveColor); + } + cr.arc( + endX, + height / 2, + barLevelBorderRadius, + TAU * (3 / 4), + TAU * (1 / 4) + ); + cr.lineTo(Math.floor(endX), barLevelBottom); + cr.lineTo(Math.floor(endX), barLevelTop); + cr.lineTo(endX, barLevelTop); + cr.fillPreserve(); + cr.setLineWidth(barLevelBorderWidth); + cr.stroke(); + } - _getCurrentValue() { - return this._value; - } + // limit maximum + if (this._limitMax < this._maxValue) { + bx = + barLevelBorderRadius + + ((width - 2 * barLevelBorderRadius) * this._limitMax) / + this._maxValue + + barLevelBorderRadius; + cr.arc( + width - barLevelBorderRadius - barLevelBorderWidth, + height / 2, + barLevelBorderRadius, + TAU * (3 / 4), + TAU * (1 / 4) + ); + cr.lineTo(bx, barLevelBottom); + cr.lineTo(bx, barLevelTop); + cr.lineTo( + width - barLevelBorderRadius - barLevelBorderWidth, + barLevelTop + ); + Clutter.cairo_set_source_color(cr, deadBarColor); + cr.fillPreserve(); + Clutter.cairo_set_source_color(cr, deadBarBorderColor); + cr.setLineWidth(barLevelBorderWidth); + cr.stroke(); + } - _getOverdriveStart() { - return this._overdriveStart; - } + /* draw overdrive separator */ + if (overdriveActive) { + cr.moveTo( + overdriveSeparatorX - overdriveSeparatorWidth / 2, + barLevelTop + ); + cr.lineTo( + overdriveSeparatorX + overdriveSeparatorWidth / 2, + barLevelTop + ); + cr.lineTo( + overdriveSeparatorX + overdriveSeparatorWidth / 2, + barLevelBottom + ); + cr.lineTo( + overdriveSeparatorX - overdriveSeparatorWidth / 2, + barLevelBottom + ); + cr.lineTo( + overdriveSeparatorX - overdriveSeparatorWidth / 2, + barLevelTop + ); + if (this._value <= this._overdriveStart) { + Clutter.cairo_set_source_color(cr, fgColor); + } else { + Clutter.cairo_set_source_color(cr, barLevelColor); + } + cr.fill(); + } - _getMinimumValue() { - return 0; - } + let limit_sep_height = height / 4; + let limit_sep_width = Math.max(2, barLevelHeight / 2); + + // draw blocked minimum region seperator + if (this._limitMin > 0) { + bx = + barLevelBorderRadius + + ((width - 2 * barLevelBorderRadius) * this._limitMin) / + this._maxValue; + bx = Math.round(bx); + cr.moveTo(bx, barLevelTop - limit_sep_height); + cr.lineTo(bx, barLevelBottom + limit_sep_height); + cr.lineTo( + bx - limit_sep_width, + barLevelBottom + limit_sep_height + ); + cr.lineTo(bx - limit_sep_width, barLevelTop - limit_sep_height); + cr.lineTo(bx, barLevelTop - limit_sep_height); + Clutter.cairo_set_source_color(cr, barLevelActiveColor); + cr.fillPreserve(); + Clutter.cairo_set_source_color(cr, barLevelActiveBorderColor); + cr.setLineWidth(barLevelBorderWidth); + cr.stroke(); + } - _getMaximumValue() { - return this._maxValue; - } + // draw blocked maximum region seperator + if (this._limitMax < this._maxValue) { + bx = + barLevelBorderRadius + + ((width - 2 * barLevelBorderRadius) * this._limitMax) / + this._maxValue + + barLevelBorderRadius; + bx = Math.round(bx); + cr.moveTo(bx, barLevelTop - limit_sep_height); + cr.lineTo(bx, barLevelBottom + limit_sep_height); + cr.lineTo( + bx + limit_sep_width, + barLevelBottom + limit_sep_height + ); + cr.lineTo(bx + limit_sep_width, barLevelTop - limit_sep_height); + cr.lineTo(bx, barLevelTop - limit_sep_height); + Clutter.cairo_set_source_color(cr, barLevelActiveColor); + cr.fillPreserve(); + Clutter.cairo_set_source_color(cr, barLevelActiveBorderColor); + cr.setLineWidth(barLevelBorderWidth); + cr.stroke(); + } - _setCurrentValue(_actor, value) { - this._value = value; - } + cr.$dispose(); + } + + _getCurrentValue() { + return this._value; + } - _valueChanged() { - this._customAccessible.notify("accessible-value"); + _getOverdriveStart() { + return this._overdriveStart; + } + + _getMinimumValue() { + return 0; + } + + _getMaximumValue() { + return this._maxValue; + } + + _setCurrentValue(_actor, value) { + this._value = value; + } + + _valueChanged() { + this._customAccessible.notify("accessible-value"); + } } -}); +); diff --git a/src/baseindicator.js b/src/baseindicator.js index 1f9f1863..52a5c6ec 100644 --- a/src/baseindicator.js +++ b/src/baseindicator.js @@ -27,22 +27,21 @@ */ // Gnome imports -const PanelMenu = imports.ui.panelMenu; -const St = imports.gi.St; -const Gio = imports.gi.Gio; -const PopupMenu = imports.ui.popupMenu; -const Main = imports.ui.main; -const Clutter = imports.gi.Clutter; -const Config = imports.misc.config; +import * as PanelMenu from 'resource:///org/gnome/shell/ui/panelMenu.js'; +import * as PopupMenu from 'resource:///org/gnome/shell/ui/popupMenu.js'; +import St from 'gi://St'; +import Gio from 'gi://Gio'; +import Clutter from 'gi://Clutter'; +import * as Main from 'resource:///org/gnome/shell/ui/main.js'; +import * as Config from 'resource:///org/gnome/shell/misc/config.js'; // Relative and misc imports and definitions -const ExtensionUtils = imports.misc.extensionUtils; -const Me = ExtensionUtils.getCurrentExtension(); -const Convenience = Me.imports.src.convenience; +import * as Convenience from './convenience.js'; const SETTINGS_ID = "org.gnome.shell.extensions.cpupower"; +const EXTENSIONDIR = import.meta.url.substr('file://'.length, import.meta.url.lastIndexOf('/') - 'file://'.length) + '/..'; /* exported CPUFreqBaseIndicator */ -var CPUFreqBaseIndicator = class CPUFreqBaseIndicator { +export class CPUFreqBaseIndicator { constructor() { this.mainButton = new PanelMenu.Button(null, "cpupower"); this.menu = this.mainButton.menu; @@ -57,7 +56,7 @@ var CPUFreqBaseIndicator = class CPUFreqBaseIndicator { Main.panel.menuManager.addMenu(this.menu); this.hbox = new St.BoxLayout({style_class: "panel-status-menu-box"}); - let gicon = Gio.icon_new_for_string(`${Me.path}/data/icons/cpu-symbolic.svg`); + let gicon = Gio.icon_new_for_string(EXTENSIONDIR + '/data/icons/cpu-symbolic.svg'); this.icon = new St.Icon({ gicon, style_class: "system-status-icon", diff --git a/src/config.js b/src/config.js index 09419ba2..6586f1ee 100644 --- a/src/config.js +++ b/src/config.js @@ -26,23 +26,21 @@ * */ -const GLib = imports.gi.GLib; -const ExtensionUtils = imports.misc.extensionUtils; -const Me = ExtensionUtils.getCurrentExtension(); +import GLib from 'gi://GLib'; /* exported PREFIX */ -var PREFIX = "/usr"; +export var PREFIX = "/usr"; /* exported TOOL_SUFFIX */ -var TOOL_SUFFIX = ""; +export var TOOL_SUFFIX = ""; /* exported IS_USER_INSTALL */ -var IS_USER_INSTALL = false; +export var IS_USER_INSTALL = false; /* exported CPUFREQCTL */ -var CPUFREQCTL = `${PREFIX}/bin/cpufreqctl`; +export var CPUFREQCTL = `${PREFIX}/bin/cpufreqctl`; /* exported POLKIT */ -var POLKIT = `${PREFIX}/share/polkit-1/actions/mko.cpupower.setcpufreq.policy`; +export var POLKIT = `${PREFIX}/share/polkit-1/actions/mko.cpupower.setcpufreq.policy`; -if (Me.dir.get_path().includes("/home")) { +if (import.meta.url.includes("/home")) { // we are installed in the /home directory, let"s handle tool installation TOOL_SUFFIX = GLib.get_user_name(); CPUFREQCTL = `${PREFIX}/local/bin/cpufreqctl-${TOOL_SUFFIX}`; diff --git a/src/convenience.js b/src/convenience.js index e4b260d9..11080503 100644 --- a/src/convenience.js +++ b/src/convenience.js @@ -24,36 +24,9 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -const Gettext = imports.gettext; -const Gio = imports.gi.Gio; - -const Config = imports.misc.config; -const ExtensionUtils = imports.misc.extensionUtils; - -/* exported initTranslations */ -/** - * initTranslations: - * @domain: (optional): the gettext domain to use - * - * Initialize Gettext to load translations from extensionsdir/locale. - * If @domain is not provided, it will be taken from metadata["gettext-domain"] - */ -function initTranslations(domain) { - let extension = ExtensionUtils.getCurrentExtension(); - - domain = domain || extension.metadata["gettext-domain"]; - - // check if this extension was built with "make zip-file", and thus - // has the locale files in a subfolder - // otherwise assume that extension has been installed in the - // same prefix as gnome-shell - let localeDir = extension.dir.get_child("locale"); - if (localeDir.query_exists(null)) { - Gettext.bindtextdomain(domain, localeDir.get_path()); - } else { - Gettext.bindtextdomain(domain, Config.LOCALEDIR); - } -} +import Gio from 'gi://Gio'; +import {Extension} from 'resource:///org/gnome/shell/extensions/extension.js'; +import * as Config from 'resource:///org/gnome/shell/misc/config.js'; /* exported getSettings */ /** @@ -64,8 +37,8 @@ function initTranslations(domain) { * in extensionsdir/schemas. If @schema is not provided, it is taken from * metadata["settings-schema"]. */ -function getSettings(schema) { - let extension = ExtensionUtils.getCurrentExtension(); +export function getSettings(schema) { + let extension = Extension.lookupByUUID('cpupower@mko-sl.de'); schema = schema || extension.metadata["settings-schema"]; diff --git a/src/indicator.js b/src/indicator.js index 573796f5..3502fa16 100644 --- a/src/indicator.js +++ b/src/indicator.js @@ -25,35 +25,37 @@ * */ -const St = imports.gi.St; -const Main = imports.ui.main; -const PopupMenu = imports.ui.popupMenu; -const GLib = imports.gi.GLib; -const Gio = imports.gi.Gio; -const Util = imports.misc.util; -const Mainloop = imports.mainloop; -const Shell = imports.gi.Shell; -const UPower = imports.gi.UPowerGlib; -const Config = imports.misc.config; - -const Gettext = imports.gettext.domain("gnome-shell-extension-cpupower"); -const _ = Gettext.gettext; - -const ExtensionUtils = imports.misc.extensionUtils; -const Me = ExtensionUtils.getCurrentExtension(); -const EXTENSIONDIR = Me.dir.get_path(); -const utils = Me.imports.src.utils; -const Cpufreqctl = Me.imports.src.utils.Cpufreqctl; - -const Slider = Me.imports.src.slider2; -const CPUFreqProfile = Me.imports.src.profile.CPUFreqProfile; -const baseindicator = Me.imports.src.baseindicator; -const CPUFreqProfileButton = Me.imports.src.profilebutton.CPUFreqProfileButton; - +import St from "gi://St"; +import Gio from "gi://Gio"; +import GLib from "gi://GLib"; +import Gtk from "gi://Gtk"; +import Shell from "gi://Shell"; +import UPower from "gi://UPowerGlib"; + +import * as Main from "resource:///org/gnome/shell/ui/main.js"; +import * as Slider from "resource:///org/gnome/shell/ui/slider.js"; +import * as PopupMenu from "resource:///org/gnome/shell/ui/popupMenu.js"; +import * as Util from "resource:///org/gnome/shell/misc/util.js"; +import * as Config from "resource:///org/gnome/shell/misc/config.js"; +import { + Extension, + gettext as _, +} from "resource:///org/gnome/shell/extensions/extension.js"; + +import * as utils from "./utils.js"; +import * as baseindicator from "./baseindicator.js"; +import { CPUFreqProfile } from "./profile.js"; +import { CPUFreqProfileButton } from "./profilebutton.js"; + +const EXTENSIONDIR = + import.meta.url.substr( + "file://".length, + import.meta.url.lastIndexOf("/") - "file://".length + ) + "/.."; const LASTSETTINGS = `${GLib.get_user_cache_dir()}/cpupower.last-settings`; /* exported CPUFreqIndicator */ -var CPUFreqIndicator = class CPUFreqIndicator extends baseindicator.CPUFreqBaseIndicator { +export class CPUFreqIndicator extends baseindicator.CPUFreqBaseIndicator { constructor(onConstructed) { super(); this.cpufreq = 800; @@ -65,14 +67,17 @@ var CPUFreqIndicator = class CPUFreqIndicator extends baseindicator.CPUFreqBaseI // read the cached settings file. if (GLib.file_test(LASTSETTINGS, GLib.FileTest.EXISTS)) { - let lines = Shell.get_file_contents_utf8_sync(LASTSETTINGS).split("\n"); + let lines = + Shell.get_file_contents_utf8_sync(LASTSETTINGS).split("\n"); if (lines.length > 3) { this.minVal = parseInt(lines[0]); this.maxVal = parseInt(lines[1]); this.isTurboBoostActive = lines[2].indexOf("true") > -1; this.isAutoSwitchActive = lines[3].indexOf("true") > -1; - log(`Loaded old settings: { minVal: ${this.minVal}, maxVal: ${this.maxVal}, isTurboBoostActive: ${this.isTurboBoostActive}, isAutoSwitchActive: ${this.isAutoSwitchActive} }`); + log( + `Loaded old settings: { minVal: ${this.minVal}, maxVal: ${this.maxVal}, isTurboBoostActive: ${this.isTurboBoostActive}, isAutoSwitchActive: ${this.isAutoSwitchActive} }` + ); this.updateMin(); this.updateMax(); @@ -108,19 +113,26 @@ var CPUFreqIndicator = class CPUFreqIndicator extends baseindicator.CPUFreqBaseI } enable() { - this.power = Main.panel.statusArea["aggregateMenu"]._power; + this.power = + Main.panel.statusArea.quickSettings._system._systemItem._powerToggle; this.powerState = this.power._proxy.State; this.powerConnectSignalId = this.power._proxy.connect( "g-properties-changed", - this.onPowerChanged.bind(this), + this.onPowerChanged.bind(this) ); // select the right profile at login this.powerActions(this.powerState, null); super.enable(); - this.timeout = Mainloop.timeout_add_seconds(1, () => this.updateFreq()); - this.timeoutMinMax = Mainloop.timeout_add_seconds(1, () => this.updateFreqMinMax(false)); + this.timeout = GLib.timeout_add_seconds(GLib.PRIORITY_DEFAULT, 1, () => + this.updateFreq() + ); + this.timeoutMinMax = GLib.timeout_add_seconds( + GLib.PRIORITY_DEFAULT, + 1, + () => this.updateFreqMinMax(false) + ); } onPowerChanged() { @@ -140,8 +152,14 @@ var CPUFreqIndicator = class CPUFreqIndicator extends baseindicator.CPUFreqBaseI log("Power state changed: discharging"); // switch to battery profile if auto switching is enabled if (this.isAutoSwitchActive) { - let defaultBatProfileID = this.settings.get_string("default-battery-profile"); - for (let i = 0; i < this.profiles.length && defaultBatProfileID !== ""; i++) { + let defaultBatProfileID = this.settings.get_string( + "default-battery-profile" + ); + for ( + let i = 0; + i < this.profiles.length && defaultBatProfileID !== ""; + i++ + ) { if (this.profiles[i].Profile.UUID === defaultBatProfileID) { doneScheduled = true; this.applyProfile(this.profiles[i].Profile, done); @@ -149,8 +167,10 @@ var CPUFreqIndicator = class CPUFreqIndicator extends baseindicator.CPUFreqBaseI } } } - } else if (powerState === UPower.DeviceState.CHARGING || - powerState === UPower.DeviceState.FULLY_CHARGED) { + } else if ( + powerState === UPower.DeviceState.CHARGING || + powerState === UPower.DeviceState.FULLY_CHARGED + ) { if (powerState === UPower.DeviceState.CHARGING) { log("Power state changed: charging"); } else { @@ -158,8 +178,13 @@ var CPUFreqIndicator = class CPUFreqIndicator extends baseindicator.CPUFreqBaseI } // switch to AC profile if auto switching is enabled if (this.isAutoSwitchActive) { - let defaultACProfileID = this.settings.get_string("default-ac-profile"); - for (var i = 0; i < this.profiles.length && defaultACProfileID !== ""; i++) { + let defaultACProfileID = + this.settings.get_string("default-ac-profile"); + for ( + var i = 0; + i < this.profiles.length && defaultACProfileID !== ""; + i++ + ) { if (this.profiles[i].Profile.UUID === defaultACProfileID) { doneScheduled = true; this.applyProfile(this.profiles[i].Profile, done); @@ -178,23 +203,33 @@ var CPUFreqIndicator = class CPUFreqIndicator extends baseindicator.CPUFreqBaseI this.hasError = true; this.lbl.set_text(""); this.mainSection.removeAll(); - this.mainSection.addMenuItem(new PopupMenu.PopupMenuItem(msg, {reactive: false})); + this.mainSection.addMenuItem( + new PopupMenu.PopupMenuItem(msg, { reactive: false }) + ); if (report) { let reportLabel = new PopupMenu.PopupMenuItem( - _("Please consider reporting this to the developers\n" + - "of this extension by submitting an issue on Github."), - {reactive: true}, + _( + "Please consider reporting this to the developers\n" + + "of this extension by submitting an issue on Github." + ), + { reactive: true } ); reportLabel.connect("activate", function () { - Gio.AppInfo.launch_default_for_uri("https://github.com/deinstapel/cpupower/issues/new", null); + Gio.AppInfo.launch_default_for_uri( + "https://github.com/deinstapel/cpupower/issues/new", + null + ); }); this.mainSection.addMenuItem(reportLabel); } this.mainSection.addMenuItem(new PopupMenu.PopupSeparatorMenuItem()); this.imPrefsBtn = new PopupMenu.PopupMenuItem(_("Preferences")); - this.imPrefsBtn.connect("activate", this.onPreferencesActivate.bind(this)); + this.imPrefsBtn.connect( + "activate", + this.onPreferencesActivate.bind(this) + ); this.mainSection.addMenuItem(this.imPrefsBtn); } @@ -218,30 +253,42 @@ var CPUFreqIndicator = class CPUFreqIndicator extends baseindicator.CPUFreqBaseI } this.profiles.reverse(); - this.imMinTitle = new PopupMenu.PopupMenuItem(`${_("Minimum Frequency")}:`, {reactive: false}); - this.imMinLabel = new St.Label({text: this.getMinText()}); + this.imMinTitle = new PopupMenu.PopupMenuItem( + `${_("Minimum Frequency")}:`, + { reactive: false } + ); + this.imMinLabel = new St.Label({ text: this.getMinText() }); this.imMinLabel.set_style("width: 3.5em; text-align: right"); this.imMinTitle.actor.add_child(this.imMinLabel); - this.imMaxTitle = new PopupMenu.PopupMenuItem(`${_("Maximum Frequency")}:`, {reactive: false}); - this.imMaxLabel = new St.Label({text: this.getMaxText()}); + this.imMaxTitle = new PopupMenu.PopupMenuItem( + `${_("Maximum Frequency")}:`, + { reactive: false } + ); + this.imMaxLabel = new St.Label({ text: this.getMaxText() }); this.imMaxLabel.set_style("width: 3.5em; text-align: right"); this.imMaxTitle.actor.add_child(this.imMaxLabel); - this.imTurboSwitch = new PopupMenu.PopupSwitchMenuItem(`${_("Turbo Boost")}:`, this.isTurboBoostActive); + this.imTurboSwitch = new PopupMenu.PopupSwitchMenuItem( + `${_("Turbo Boost")}:`, + this.isTurboBoostActive + ); this.imTurboSwitch.connect("toggled", (item) => { this.isTurboBoostActive = item.state; this.updateTurbo(); }); - this.imAutoSwitch = new PopupMenu.PopupSwitchMenuItem(`${_("Auto Switch")}:`, this.isAutoSwitchActive); + this.imAutoSwitch = new PopupMenu.PopupSwitchMenuItem( + `${_("Auto Switch")}:`, + this.isAutoSwitchActive + ); this.imAutoSwitch.connect("toggled", (item) => { this.isAutoSwitchActive = item.state; this.updateAutoSwitch(); }); - this.imSliderMin = new PopupMenu.PopupBaseMenuItem({activate: false}); - this.minSlider = new Slider.Slider2(this.minVal); + this.imSliderMin = new PopupMenu.PopupBaseMenuItem({ activate: false }); + this.minSlider = new Slider.Slider(this.minVal); this.minSlider.x_expand = true; this.minSlider.maximum_value = 100; this.minSlider.overdrive_start = 100; @@ -258,14 +305,9 @@ var CPUFreqIndicator = class CPUFreqIndicator extends baseindicator.CPUFreqBaseI this.updateMin(); }); - if (parseFloat(Config.PACKAGE_VERSION.substring(0, 4)) > 3.32) { - this.imSliderMin.add_child(this.minSlider); - } else { - this.imSliderMin.actor.add(this.minSlider, {expand: true}); - } - - this.imSliderMax = new PopupMenu.PopupBaseMenuItem({activate: false}); - this.maxSlider = new Slider.Slider2(this.maxVal); + this.imSliderMin.add_child(this.minSlider); + this.imSliderMax = new PopupMenu.PopupBaseMenuItem({ activate: false }); + this.maxSlider = new Slider.Slider(this.maxVal); this.maxSlider.x_expand = true; this.maxSlider.maximum_value = 100; this.maxSlider.overdrive_start = 100; @@ -282,14 +324,12 @@ var CPUFreqIndicator = class CPUFreqIndicator extends baseindicator.CPUFreqBaseI this.updateMax(); }); - if (parseFloat(Config.PACKAGE_VERSION.substring(0, 4)) > 3.32) { - this.imSliderMax.add_child(this.maxSlider); - } else { - this.imSliderMax.actor.add(this.maxSlider, {expand: true}); - } - - this.imCurrentTitle = new PopupMenu.PopupMenuItem(`${_("Current Frequency")}:`, {reactive: false}); - this.imCurrentLabel = new St.Label({text: this.getCurFreq()}); + this.imSliderMax.add_child(this.maxSlider); + this.imCurrentTitle = new PopupMenu.PopupMenuItem( + `${_("Current Frequency")}:`, + { reactive: false } + ); + this.imCurrentLabel = new St.Label({ text: this.getCurFreq() }); this.imCurrentLabel.set_style("width: 4.5em; text-align: right"); this.imCurrentTitle.actor.add_child(this.imCurrentLabel); @@ -305,7 +345,9 @@ var CPUFreqIndicator = class CPUFreqIndicator extends baseindicator.CPUFreqBaseI this.mainSection.addMenuItem(new PopupMenu.PopupSeparatorMenuItem()); for (var i = 0; i < this.profiles.length; i++) { - this.profiles[i].connect("activate", (item) => this.applyProfile(item.Profile, null)); + this.profiles[i].connect("activate", (item) => + this.applyProfile(item.Profile, null) + ); this.mainSection.addMenuItem(this.profiles[i]); } @@ -313,28 +355,37 @@ var CPUFreqIndicator = class CPUFreqIndicator extends baseindicator.CPUFreqBaseI this.mainSection.addMenuItem(this.imAutoSwitch); this.imPrefsBtn = new PopupMenu.PopupMenuItem(_("Preferences")); - this.imPrefsBtn.connect("activate", this.onPreferencesActivate.bind(this)); + this.imPrefsBtn.connect( + "activate", + this.onPreferencesActivate.bind(this) + ); this.mainSection.addMenuItem(new PopupMenu.PopupSeparatorMenuItem()); this.mainSection.addMenuItem(this.imPrefsBtn); this.hasError = false; let backend = this.settings.get_string("cpufreqctl-backend"); - Cpufreqctl.backends.current(backend, (result) => { + utils.Cpufreqctl.backends.current(backend, (result) => { if (!result.ok) { switch (result.exitCode) { - case utils.CPUFREQCTL_NOT_SUPPORTED: - this.showError( - `${_("Oh no! Something went wrong.")}\n` + - `${_("The currently selected frequency scaling driver is not supported on your CPU!")}`, - false, - ); - break; - default: - this.showError( - `${_("Oh no! Something went wrong.")}\n` + - `${_("An internal error occurred:")} ${Cpufreqctl.exitCodeToString(result.exitCode)}`, - true, - ); + case utils.CPUFREQCTL_NOT_SUPPORTED: + this.showError( + `${_("Oh no! Something went wrong.")}\n` + + `${_( + "The currently selected frequency scaling driver is not supported on your CPU!" + )}`, + false + ); + break; + default: + this.showError( + `${_("Oh no! Something went wrong.")}\n` + + `${_( + "An internal error occurred:" + )} ${utils.Cpufreqctl.exitCodeToString( + result.exitCode + )}`, + true + ); } } else { this.clearError(); @@ -362,8 +413,8 @@ var CPUFreqIndicator = class CPUFreqIndicator extends baseindicator.CPUFreqBaseI disable() { this.power._proxy.disconnect(this.powerConnectSignalId); super.disable(); - Mainloop.source_remove(this.timeout); - Mainloop.source_remove(this.timeoutMinMax); + //GLib.SOURCE_REMOVE(this.timeout); + //GLib.SOURCE_REMOVE(this.timeoutMinMax); } getMinText() { @@ -375,7 +426,8 @@ var CPUFreqIndicator = class CPUFreqIndicator extends baseindicator.CPUFreqBaseI } updateFile() { - let cmd = `${Math.floor(this.minVal)}\n` + + let cmd = + `${Math.floor(this.minVal)}\n` + `${Math.floor(this.maxVal)}\n` + `${this.isTurboBoostActive ? "true" : "false"}\n` + `${this.isAutoSwitchActive ? "true" : "false"}\n`; @@ -385,35 +437,47 @@ var CPUFreqIndicator = class CPUFreqIndicator extends baseindicator.CPUFreqBaseI updateMax(done) { let backend = this.settings.get_string("cpufreqctl-backend"); - Cpufreqctl.max.set(backend, Math.floor(this.maxVal).toString(), (_result) => { - this.updateFile(); + utils.Cpufreqctl.max.set( + backend, + Math.floor(this.maxVal).toString(), + (_result) => { + this.updateFile(); - if (done) { - done(); + if (done) { + done(); + } } - }); + ); } updateMin(done) { let backend = this.settings.get_string("cpufreqctl-backend"); - Cpufreqctl.min.set(backend, Math.floor(this.minVal).toString(), (_result) => { - this.updateFile(); + utils.Cpufreqctl.min.set( + backend, + Math.floor(this.minVal).toString(), + (_result) => { + this.updateFile(); - if (done) { - done(); + if (done) { + done(); + } } - }); + ); } updateTurbo(done) { let backend = this.settings.get_string("cpufreqctl-backend"); - Cpufreqctl.turbo.set(backend, this.isTurboBoostActive ? "on" : "off", (_result) => { - this.updateFile(); + utils.Cpufreqctl.turbo.set( + backend, + this.isTurboBoostActive ? "on" : "off", + (_result) => { + this.updateFile(); - if (done) { - done(); + if (done) { + done(); + } } - }); + ); } updateAutoSwitch() { @@ -442,38 +506,44 @@ var CPUFreqIndicator = class CPUFreqIndicator extends baseindicator.CPUFreqBaseI this.minVal === p.Profile.MinimumFrequency && this.maxVal === p.Profile.MaximumFrequency && this.isTurboBoostActive === p.Profile.TurboBoost - ? PopupMenu.Ornament.DOT : PopupMenu.Ornament.NONE, + ? PopupMenu.Ornament.DOT + : PopupMenu.Ornament.NONE ); } } updateFreq() { // Only update current frequency if it is shown next to the indicator or the menu is open - if (this.hasError || !(this.lblActive || this.menu && this.menu.isOpen)) { + if ( + this.hasError || + !(this.lblActive || (this.menu && this.menu.isOpen)) + ) { return true; } const backend = this.settings.get_string("cpufreqctl-backend"); - Cpufreqctl.info.current(backend, (result) => { + utils.Cpufreqctl.info.current(backend, (result) => { if (result.ok && result.exitCode === 0) { let value; switch (this.settings.get_string("frequency-sampling-mode")) { - case "average": - value = result.response.avg; - break; - case "minimum": - value = result.response.min; - break; - case "maximum": - value = result.response.max; - break; - case "random": - value = result.response.rnd; - break; - default: - log("invalid frequency-sampling-mode provided, defaulting to 'average'..."); - value = result.response.avg; - break; + case "average": + value = result.response.avg; + break; + case "minimum": + value = result.response.min; + break; + case "maximum": + value = result.response.max; + break; + case "random": + value = result.response.rnd; + break; + default: + log( + "invalid frequency-sampling-mode provided, defaulting to 'average'..." + ); + value = result.response.avg; + break; } this.cpufreq = value / 1000; if (this.menu && this.menu.isOpen) { @@ -502,21 +572,21 @@ var CPUFreqIndicator = class CPUFreqIndicator extends baseindicator.CPUFreqBaseI }; const backend = this.settings.get_string("cpufreqctl-backend"); - Cpufreqctl.turbo.get(backend, (result) => { + utils.Cpufreqctl.turbo.get(backend, (result) => { if (result.ok && result.exitCode === 0) { this.isTurboBoostActive = result.response === "on"; } updateUi(); }); - Cpufreqctl.min.get(backend, (result) => { + utils.Cpufreqctl.min.get(backend, (result) => { if (result.ok && result.exitCode === 0) { this.minVal = result.response; } updateUi(); }); - Cpufreqctl.max.get(backend, (result) => { + utils.Cpufreqctl.max.get(backend, (result) => { if (result.ok && result.exitCode === 0) { this.maxVal = result.response; } @@ -527,30 +597,39 @@ var CPUFreqIndicator = class CPUFreqIndicator extends baseindicator.CPUFreqBaseI } checkFrequencies(cb) { - Cpufreqctl.info.frequencies(this.settings.get_string("cpufreqctl-backend"), (result) => { - if (!result.ok || result.exitCode !== 0) { - let exitReason = Cpufreqctl.exitCodeToString(result.exitCode); - log(`Failed to query supported frequency ranges from cpufreqctl, reason ${exitReason}! ` + - "Assuming full range..."); - log(result.response); - cb({ - min: 0, - max: 100, - }); - } else if (result.response.mode === "continuous") { - cb({ - min: result.response.min, - max: result.response.max, - }); - } else { - log(`Cpufreqctl signaled unsupported frequency mode ${result.response.mode}! ` + - "Assuming full range..."); - cb({ - min: 0, - max: 100, - }); + utils.Cpufreqctl.info.frequencies( + this.settings.get_string("cpufreqctl-backend"), + (result) => { + if (!result.ok || result.exitCode !== 0) { + let exitReason = utils.Cpufreqctl.exitCodeToString( + result.exitCode + ); + log( + `Failed to query supported frequency ranges from cpufreqctl, reason ${exitReason}! ` + + "Assuming full range..." + ); + log(result.response); + cb({ + min: 0, + max: 100, + }); + } else if (result.response.mode === "continuous") { + cb({ + min: result.response.min, + max: result.response.max, + }); + } else { + log( + `Cpufreqctl signaled unsupported frequency mode ${result.response.mode}! ` + + "Assuming full range..." + ); + cb({ + min: 0, + max: 100, + }); + } } - }); + ); } getCurFreq() { @@ -562,13 +641,7 @@ var CPUFreqIndicator = class CPUFreqIndicator extends baseindicator.CPUFreqBaseI } onPreferencesActivate(_item) { - if (parseFloat(Config.PACKAGE_VERSION.substring(0, 4)) >= 40) { - Util.trySpawnCommandLine(`${EXTENSIONDIR}/src/prefs40/main.js`); - } else if (parseFloat(Config.PACKAGE_VERSION.substring(0, 4)) > 3.32) { - Util.trySpawnCommandLine("gnome-extensions prefs cpupower@mko-sl.de"); - } else { - Util.trySpawnCommandLine("gnome-shell-extension-prefs cpupower@mko-sl.de"); - } - return 0; + const extension = Extension.lookupByURL(import.meta.url); + extension.openPreferences(); } -}; +} diff --git a/src/notinstalled.js b/src/notinstalled.js index 9e71852f..64ff45c3 100644 --- a/src/notinstalled.js +++ b/src/notinstalled.js @@ -27,18 +27,14 @@ */ // Gnome imports -const PopupMenu = imports.ui.popupMenu; +import Gio from 'gi://Gio'; -// Relative and misc imports and definitions -const Gio = imports.gi.Gio; -const ExtensionUtils = imports.misc.extensionUtils; -const Me = ExtensionUtils.getCurrentExtension(); -const baseindicator = Me.imports.src.baseindicator; -const attemptInstallation = Me.imports.src.utils.attemptInstallation; -const utils = Me.imports.src.utils; +import * as PopupMenu from 'resource:///org/gnome/shell/ui/popupMenu.js'; +import {gettext as _} from 'resource:///org/gnome/shell/extensions/extension.js'; -const Gettext = imports.gettext.domain("gnome-shell-extension-cpupower"); -const _ = Gettext.gettext; +// Relative and misc imports and definitions +import * as baseindicator from './baseindicator.js'; +import * as utils from './utils.js'; /* exported NotInstalledIndicator */ var NotInstalledIndicator = class NotInstalledIndicator extends baseindicator.CPUFreqBaseIndicator { @@ -81,7 +77,7 @@ var NotInstalledIndicator = class NotInstalledIndicator extends baseindicator.CP this.mainSection.addMenuItem(separator); this.attemptInstallationLabel = new PopupMenu.PopupMenuItem(_("Attempt installation"), {reactive: true}); - this.attemptInstallationLabel.connect("activate", attemptInstallation.bind(null, this.done)); + this.attemptInstallationLabel.connect("activate", utils.attemptInstallation.bind(null, this.done)); this.mainSection.addMenuItem(this.attemptInstallationLabel); } }; diff --git a/src/preferences.js b/src/preferences.js index a3df8236..eb5be44c 100644 --- a/src/preferences.js +++ b/src/preferences.js @@ -26,28 +26,24 @@ * */ -const Gtk = imports.gi.Gtk; -const Gio = imports.gi.Gio; -const GLib = imports.gi.GLib; -const Gettext = imports.gettext.domain("gnome-shell-extension-cpupower"); -const Config = imports.misc.config; -const _ = Gettext.gettext; -const ByteArray = imports.byteArray; - -const ExtensionUtils = imports.misc.extensionUtils; -const Me = ExtensionUtils.getCurrentExtension(); -const Convenience = Me.imports.src.convenience; -const CPUFreqProfile = Me.imports.src.profile.CPUFreqProfile; -const EXTENSIONDIR = Me.dir.get_path(); -const CONFIG = Me.imports.src.config; -const attemptUninstallation = Me.imports.src.utils.attemptUninstallation; -const Cpufreqctl = Me.imports.src.utils.Cpufreqctl; +import Gtk from 'gi://Gtk'; +import Gio from 'gi://Gio'; +import GLib from 'gi://GLib'; +import * as Config from 'resource:///org/gnome/Shell/Extensions/js/misc/config.js'; +import {gettext as _} from 'resource:///org/gnome/Shell/Extensions/js/extensions/prefs.js'; + +import * as Convenience from './convenience.js'; +import * as CONFIG from './config.js'; +import * as utils from './utils.js'; +import {CPUFreqProfile} from './profile.js'; + +const EXTENSIONDIR = import.meta.url.substr('file://'.length, import.meta.url.lastIndexOf('/') - 'file://'.length); const GLADE_FILE = `${EXTENSIONDIR}/data/cpupower-preferences.glade`; const SETTINGS_SCHEMA = "org.gnome.shell.extensions.cpupower"; /* exported CPUPowerPreferences */ -var CPUPowerPreferences = class CPUPowerPreferences { +export class CPUPowerPreferencesContent { constructor() { this.cpupowerService = null; this.cpupowerConnection = null; @@ -126,9 +122,9 @@ var CPUPowerPreferences = class CPUPowerPreferences { } checkFrequencies(cb) { - Cpufreqctl.info.frequencies(this.settings.get_string("cpufreqctl-backend"), (result) => { + utils.Cpufreqctl.info.frequencies(this.settings.get_string("cpufreqctl-backend"), (result) => { if (!result.ok || result.exitCode !== 0) { - let exitReason = Cpufreqctl.exitCodeToString(result.exitCode); + let exitReason = utils.Cpufreqctl.exitCodeToString(result.exitCode); log(`Failed to query supported frequency ranges from cpufreqctl, reason ${exitReason}! ` + "Assuming full range..."); log(result.response); @@ -547,7 +543,7 @@ var CPUPowerPreferences = class CPUPowerPreferences { let combobox = this.FrequencyScalingDriverComboBox; let backend = this.settings.get_string("cpufreqctl-backend"); liststore.clear(); - Cpufreqctl.backends.automatic((result) => { + utils.Cpufreqctl.backends.automatic((result) => { let iter = liststore.append(); let chosenBackend = result.response; if (!result.ok) { @@ -558,7 +554,7 @@ var CPUPowerPreferences = class CPUPowerPreferences { [0, 1, 2], [`${_("Automatic")} (${chosenBackend})`, "automatic", true], ); - Cpufreqctl.backends.list(backend, (result) => { + utils.Cpufreqctl.backends.list(backend, (result) => { if (!result.ok) { return; } @@ -626,10 +622,10 @@ var CPUPowerPreferences = class CPUPowerPreferences { this.status(`FrequencyScalingDriver: ${state}`); if (oldBackend !== state) { - Cpufreqctl.reset(oldBackend, (result) => { + utils.Cpufreqctl.reset(oldBackend, (result) => { if (!result.ok) { this.status(`Failed to reset frequency scaling driver of old backend ${oldBackend}: ` + - `${Cpufreqctl.exitCodeToString(result.exitCode)}`); + `${utils.Cpufreqctl.exitCodeToString(result.exitCode)}`); } }); } @@ -701,7 +697,7 @@ var CPUPowerPreferences = class CPUPowerPreferences { dialog.set_transient_for(parentWindow); uninstallButton.connect("clicked", () => { - attemptUninstallation((_success) => { + utils.attemptUninstallation((_success) => { dialog.close(); if (this.cpupowerConnection) { diff --git a/src/prefs40/main.js b/src/prefs40/main.js index f2979694..2ee638a8 100755 --- a/src/prefs40/main.js +++ b/src/prefs40/main.js @@ -1,17 +1,19 @@ #! /usr/bin/env gjs -const Gio = imports.gi.Gio; +import Gio from "gi://Gio"; +// imports.gi.versions.Gtk = "3.0"; +import Gtk from "gi://Gtk?version=4.0"; +//import * as prefs from "resource:///org/gnome/Shell/Extensions/js/extensions/prefs.js"; -let scriptdir = Gio.File.new_for_path(imports.system.programPath).get_parent(); -imports.searchPath.unshift(scriptdir.get_path()); -imports.searchPath.unshift(scriptdir.get_parent().get_parent().get_path()); +// imports.searchPath.unshift(scriptdir.get_path()); +// imports.searchPath.unshift(scriptdir.get_parent().get_parent().get_path()); -imports.gi.versions.Gtk = "3.0"; -const Gtk = imports.gi.Gtk; -const prefs = imports.prefs; +//const prefs = imports.prefs; + +//let scriptdir = Gio.File.new_for_path(imports.system.programPath).get_parent(); Gtk.init(null); -prefs.init(); +//prefs.init(); let win = new Gtk.Window(); win.connect("delete-event", () => { diff --git a/src/prefs40/misc.js b/src/prefs40/misc.js index 896019e6..491e882d 100644 --- a/src/prefs40/misc.js +++ b/src/prefs40/misc.js @@ -1,16 +1,15 @@ -const Gio = imports.gi.Gio; +import Gio from "gi://Gio"; +import Gtk from "gi://Gtk?version=4.0"; + +import { + ExtensionUtils, + gettext as _, +} from "resource:///org/gnome/Shell/Extensions/js/extensions/prefs.js"; /* exported extensionUtils */ -var extensionUtils = { - getCurrentExtension: () => { - return { - imports, - dir: Gio.File.new_for_path(imports.system.programPath).get_parent().get_parent().get_parent(), - }; - }, -}; +var extensionUtils = ExtensionUtils.getCurrentExtension(); /* exported config */ -var config = { - PACKAGE_VERSION: "40.0", +var Config = { + PACKAGE_VERSION: "45.0", }; diff --git a/src/profile.js b/src/profile.js index 382ababa..7e551634 100644 --- a/src/profile.js +++ b/src/profile.js @@ -30,8 +30,7 @@ function GenerateUUID() { return Math.floor(1 + Math.random() * 0xFFFFFFFE).toString(); } -/* exported CPUFreqProfile */ -var CPUFreqProfile = class CPUFreqProfile { +export class CPUFreqProfile { constructor() { this.UUID = GenerateUUID(); this.MinimumFrequency = 0; diff --git a/src/profilebutton.js b/src/profilebutton.js index 0910d283..7ae0afaa 100644 --- a/src/profilebutton.js +++ b/src/profilebutton.js @@ -25,31 +25,18 @@ * */ -const PopupMenu = imports.ui.popupMenu; -const GObject = imports.gi.GObject; -const Config = imports.misc.config; -const Gettext = imports.gettext.domain("gnome-shell-extension-cpupower"); -const _ = Gettext.gettext; +import GObject from 'gi://GObject'; + +import * as PopupMenu from 'resource:///org/gnome/shell/ui/popupMenu.js'; +import * as Config from 'resource:///org/gnome/shell/misc/config.js'; const DEFAULT_EMPTY_NAME = "No name"; -/* exported CPUFreqProfileButton */ -var CPUFreqProfileButton; +export class CPUFreqProfileButton extends PopupMenu.PopupMenuItem { + _init(profile) { + super._init(profile.Name || DEFAULT_EMPTY_NAME, {reactive: true}); + this.Profile = profile; + } +}; -// Handle different sub-classing paradigm between Gnome > 3.32 and Gnome <= 3.32 -if (parseFloat(Config.PACKAGE_VERSION.substring(0, 4)) > 3.32) { - CPUFreqProfileButton = class CPUFreqProfileButton extends PopupMenu.PopupMenuItem { - _init(profile) { - super._init(profile.Name || DEFAULT_EMPTY_NAME, {reactive: true}); - this.Profile = profile; - } - }; - CPUFreqProfileButton = GObject.registerClass({GTypeName: "CPUFreqProfileButton"}, CPUFreqProfileButton); -} else { - CPUFreqProfileButton = class CPUFreqProfileButton extends PopupMenu.PopupMenuItem { - constructor(profile) { - super(_(profile.Name || DEFAULT_EMPTY_NAME), {reactive: true}); - this.Profile = profile; - } - }; -} +GObject.registerClass({GTypeName: "CPUFreqProfileButton"}, CPUFreqProfileButton); diff --git a/src/slider2.js b/src/slider2.js index 645f73df..29766f7e 100644 --- a/src/slider2.js +++ b/src/slider2.js @@ -8,248 +8,270 @@ * See for details. */ -const {Atk, Clutter, GObject} = imports.gi; +import Clutter from "gi://Clutter"; +import Atk from "gi://Atk"; +import St from "gi://St"; +import GObject from "gi://GObject"; -const ExtensionUtils = imports.misc.extensionUtils; -const Config = imports.misc.config; - -const Me = ExtensionUtils.getCurrentExtension(); -const BarLevel2 = Me.imports.src.barLevel2; +import * as Config from "resource:///org/gnome/shell/misc/config.js"; +import { barLevel2 } from "./src/barLevel2.js"; /* exported Slider2 */ -var Slider2 = GObject.registerClass({ - GTypeName: "Slider2", - Signals: { - "drag-begin": {}, - "drag-end": {}, +var Slider2 = GObject.registerClass( + { + GTypeName: "Slider2", + Signals: { + "drag-begin": {}, + "drag-end": {}, + }, }, -}, class Slider2 extends BarLevel2.BarLevel2 { - _init(value) { - super._init({ - value, - style_class: "slider", - can_focus: true, - reactive: true, - accessible_role: Atk.Role.SLIDER, - x_expand: true, - }); - - this._releaseId = 0; - this._dragging = false; - - this._customAccessible.connect("get-minimum-increment", this._getMinimumIncrement.bind(this)); - } + class Slider2 extends BarLevel2.BarLevel2 { + _init(value) { + super._init({ + value, + style_class: "slider", + can_focus: true, + reactive: true, + accessible_role: Atk.Role.SLIDER, + x_expand: true, + }); + + this._releaseId = 0; + this._dragging = false; - vfunc_repaint() { - super.vfunc_repaint(); - - // Add handle - let cr = this.get_context(); - let themeNode = this.get_theme_node(); - let [width, height] = this.get_surface_size(); - - let handleRadius = themeNode.get_length("-slider-handle-radius"); - - let handleBorderWidth = themeNode.get_length("-slider-handle-border-width"); - let [hasHandleColor, handleBorderColor] = - themeNode.lookup_color("-slider-handle-border-color", false); - - const ceiledHandleRadius = Math.ceil(handleRadius + handleBorderWidth); - const handleX = ceiledHandleRadius + - (width - 2 * ceiledHandleRadius) * this._value / this._maxValue; - const handleY = height / 2; - - let color = themeNode.get_foreground_color(); - Clutter.cairo_set_source_color(cr, color); - cr.arc(handleX, handleY, handleRadius, 0, 2 * Math.PI); - cr.fillPreserve(); - if (hasHandleColor && handleBorderWidth) { - Clutter.cairo_set_source_color(cr, handleBorderColor); - cr.setLineWidth(handleBorderWidth); - cr.stroke(); + this._customAccessible.connect( + "get-minimum-increment", + this._getMinimumIncrement.bind(this) + ); } - cr.$dispose(); - } - vfunc_button_press_event() { - return this.startDragging(Clutter.get_current_event()); - } - - startDragging(event) { - if (this._dragging) { - return Clutter.EVENT_PROPAGATE; + vfunc_repaint() { + super.vfunc_repaint(); + + // Add handle + let cr = this.get_context(); + let themeNode = this.get_theme_node(); + let [width, height] = this.get_surface_size(); + + let handleRadius = themeNode.get_length("-slider-handle-radius"); + + let handleBorderWidth = themeNode.get_length( + "-slider-handle-border-width" + ); + let [hasHandleColor, handleBorderColor] = themeNode.lookup_color( + "-slider-handle-border-color", + false + ); + + const ceiledHandleRadius = Math.ceil( + handleRadius + handleBorderWidth + ); + const handleX = + ceiledHandleRadius + + ((width - 2 * ceiledHandleRadius) * this._value) / + this._maxValue; + const handleY = height / 2; + + let color = themeNode.get_foreground_color(); + Clutter.cairo_set_source_color(cr, color); + cr.arc(handleX, handleY, handleRadius, 0, 2 * Math.PI); + cr.fillPreserve(); + if (hasHandleColor && handleBorderWidth) { + Clutter.cairo_set_source_color(cr, handleBorderColor); + cr.setLineWidth(handleBorderWidth); + cr.stroke(); + } + cr.$dispose(); } - this._dragging = true; - - let device = event.get_device(); - let sequence = event.get_event_sequence(); - - if (parseFloat(Config.PACKAGE_VERSION.substring(0, 4)) >= 42) { - this._grab = global.stage.grab(this); - } else if (sequence) { - device.sequence_grab(sequence, this); - } else { - device.grab(this); + vfunc_button_press_event() { + return this.startDragging(Clutter.get_current_event()); } - this._grabbedDevice = device; - this._grabbedSequence = sequence; - - // We need to emit "drag-begin" before moving the handle to make - // sure that no "notify::value" signal is emitted before this one. - this.emit("drag-begin"); + startDragging(event) { + if (this._dragging) { + return Clutter.EVENT_PROPAGATE; + } - let absX, absY; - [absX, absY] = event.get_coords(); - this._moveHandle(absX, absY); - return Clutter.EVENT_STOP; - } + this._dragging = true; - _endDragging() { - if (this._dragging) { - if (this._releaseId) { - this.disconnect(this._releaseId); - this._releaseId = 0; - } + let device = event.get_device(); + let sequence = event.get_event_sequence(); if (parseFloat(Config.PACKAGE_VERSION.substring(0, 4)) >= 42) { - if (this._grab) { - this._grab.dismiss(); - this._grab = null; - } - } else if (this._grabbedSequence) { - this._grabbedDevice.sequence_ungrab(this._grabbedSequence); + this._grab = global.stage.grab(this); + } else if (sequence) { + device.sequence_grab(sequence, this); } else { - this._grabbedDevice.ungrab(); + device.grab(this); } - this._grabbedSequence = null; - this._grabbedDevice = null; - this._dragging = false; + this._grabbedDevice = device; + this._grabbedSequence = sequence; - this.emit("drag-end"); - } - return Clutter.EVENT_STOP; - } + // We need to emit "drag-begin" before moving the handle to make + // sure that no "notify::value" signal is emitted before this one. + this.emit("drag-begin"); - vfunc_button_release_event() { - if (this._dragging && !this._grabbedSequence) { - return this._endDragging(); + let absX, absY; + [absX, absY] = event.get_coords(); + this._moveHandle(absX, absY); + return Clutter.EVENT_STOP; } - return Clutter.EVENT_PROPAGATE; - } + _endDragging() { + if (this._dragging) { + if (this._releaseId) { + this.disconnect(this._releaseId); + this._releaseId = 0; + } + + if (parseFloat(Config.PACKAGE_VERSION.substring(0, 4)) >= 42) { + if (this._grab) { + this._grab.dismiss(); + this._grab = null; + } + } else if (this._grabbedSequence) { + this._grabbedDevice.sequence_ungrab(this._grabbedSequence); + } else { + this._grabbedDevice.ungrab(); + } - vfunc_touch_event() { - let event = Clutter.get_current_event(); - let device = event.get_device(); - let sequence = event.get_event_sequence(); + this._grabbedSequence = null; + this._grabbedDevice = null; + this._dragging = false; - if (!this._dragging && - event.type() === Clutter.EventType.TOUCH_BEGIN) { - this.startDragging(event); + this.emit("drag-end"); + } return Clutter.EVENT_STOP; - } else if ( - ( - parseFloat(Config.PACKAGE_VERSION.substring(0, 4)) >= 42 && ( - this._grabbedSequence && - sequence.get_slot() === this._grabbedSequence.get_slot() - ) - ) || ( - parseFloat(Config.PACKAGE_VERSION.substring(0, 4)) < 42 && ( - device.sequence_get_grabbed_actor(sequence) === this - ) - ) - ) { - if (event.type() === Clutter.EventType.TOUCH_UPDATE) { - return this._motionEvent(this, event); - } else if (event.type() === Clutter.EventType.TOUCH_END) { + } + + vfunc_button_release_event() { + if (this._dragging && !this._grabbedSequence) { return this._endDragging(); } - } - return Clutter.EVENT_PROPAGATE; - } + return Clutter.EVENT_PROPAGATE; + } - scroll(event) { - let direction = event.get_scroll_direction(); + vfunc_touch_event() { + let event = Clutter.get_current_event(); + let device = event.get_device(); + let sequence = event.get_event_sequence(); + + if ( + !this._dragging && + event.type() === Clutter.EventType.TOUCH_BEGIN + ) { + this.startDragging(event); + return Clutter.EVENT_STOP; + } else if ( + (parseFloat(Config.PACKAGE_VERSION.substring(0, 4)) >= 42 && + this._grabbedSequence && + sequence.get_slot() === this._grabbedSequence.get_slot()) || + (parseFloat(Config.PACKAGE_VERSION.substring(0, 4)) < 42 && + device.sequence_get_grabbed_actor(sequence) === this) + ) { + if (event.type() === Clutter.EventType.TOUCH_UPDATE) { + return this._motionEvent(this, event); + } else if (event.type() === Clutter.EventType.TOUCH_END) { + return this._endDragging(); + } + } - if (event.is_pointer_emulated()) { return Clutter.EVENT_PROPAGATE; } - let delta = this._getMinimumIncrement(); - if (direction === Clutter.ScrollDirection.DOWN) { - delta *= -1; - } else if (direction === Clutter.ScrollDirection.UP) { - delta *= 1; - } else if (direction === Clutter.ScrollDirection.SMOOTH) { - let [, dy] = event.get_scroll_delta(); - // Even though the slider is horizontal, use dy to match - // the UP/DOWN above. - delta *= -dy; - } + scroll(event) { + let direction = event.get_scroll_direction(); - this.value = Math.min(Math.max(this.limit_minimum, this._value + delta), this.limit_maximum); + if (event.is_pointer_emulated()) { + return Clutter.EVENT_PROPAGATE; + } - return Clutter.EVENT_STOP; - } + let delta = this._getMinimumIncrement(); + if (direction === Clutter.ScrollDirection.DOWN) { + delta *= -1; + } else if (direction === Clutter.ScrollDirection.UP) { + delta *= 1; + } else if (direction === Clutter.ScrollDirection.SMOOTH) { + let [, dy] = event.get_scroll_delta(); + // Even though the slider is horizontal, use dy to match + // the UP/DOWN above. + delta *= -dy; + } - vfunc_scroll_event() { - return this.scroll(Clutter.get_current_event()); - } + this.value = Math.min( + Math.max(this.limit_minimum, this._value + delta), + this.limit_maximum + ); - vfunc_motion_event() { - if (this._dragging && !this._grabbedSequence) { - return this._motionEvent(this, Clutter.get_current_event()); + return Clutter.EVENT_STOP; } - return Clutter.EVENT_PROPAGATE; - } - - _motionEvent(actor, event) { - let absX, absY; - [absX, absY] = event.get_coords(); - this._moveHandle(absX, absY); - return Clutter.EVENT_STOP; - } + vfunc_scroll_event() { + return this.scroll(Clutter.get_current_event()); + } - vfunc_key_press_event(keyPressEvent) { - let key = keyPressEvent.keyval; - if (key === Clutter.KEY_Right || key === Clutter.KEY_Left) { - let delta = this._getMinimumIncrement(); - if (key === Clutter.KEY_Left) { - delta *= -1; + vfunc_motion_event() { + if (this._dragging && !this._grabbedSequence) { + return this._motionEvent(this, Clutter.get_current_event()); } - this.value = this.value = Math.min(Math.max(this.limit_minimum, this._value + delta), this.limit_maximum); + + return Clutter.EVENT_PROPAGATE; + } + + _motionEvent(actor, event) { + let absX, absY; + [absX, absY] = event.get_coords(); + this._moveHandle(absX, absY); return Clutter.EVENT_STOP; } - return super.vfunc_key_press_event(keyPressEvent); - } - _moveHandle(absX, _absY) { - let relX, sliderX; - [sliderX] = this.get_transformed_position(); - relX = absX - sliderX; - - let width = this._barLevelWidth; - let handleRadius = this.get_theme_node().get_length("-slider-handle-radius"); - - let newvalue; - if (relX < handleRadius) { - newvalue = 0; - } else if (relX > width - handleRadius) { - newvalue = 1; - } else { - newvalue = (relX - handleRadius) / (width - 2 * handleRadius); + vfunc_key_press_event(keyPressEvent) { + let key = keyPressEvent.keyval; + if (key === Clutter.KEY_Right || key === Clutter.KEY_Left) { + let delta = this._getMinimumIncrement(); + if (key === Clutter.KEY_Left) { + delta *= -1; + } + this.value = this.value = Math.min( + Math.max(this.limit_minimum, this._value + delta), + this.limit_maximum + ); + return Clutter.EVENT_STOP; + } + return super.vfunc_key_press_event(keyPressEvent); } - newvalue *= this._maxValue; - this.value = Math.min(Math.max(this.limit_minimum, newvalue), this.limit_maximum); - } + _moveHandle(absX, _absY) { + let relX, sliderX; + [sliderX] = this.get_transformed_position(); + relX = absX - sliderX; + + let width = this._barLevelWidth; + let handleRadius = this.get_theme_node().get_length( + "-slider-handle-radius" + ); + + let newvalue; + if (relX < handleRadius) { + newvalue = 0; + } else if (relX > width - handleRadius) { + newvalue = 1; + } else { + newvalue = (relX - handleRadius) / (width - 2 * handleRadius); + } - _getMinimumIncrement() { - return 0.01 * this.maximum_value; + newvalue *= this._maxValue; + this.value = Math.min( + Math.max(this.limit_minimum, newvalue), + this.limit_maximum + ); + } + + _getMinimumIncrement() { + return 0.01 * this.maximum_value; + } } -}); +); diff --git a/src/update.js b/src/update.js index 9467a72a..dfed5532 100644 --- a/src/update.js +++ b/src/update.js @@ -27,16 +27,12 @@ */ // Gnome imports -const PopupMenu = imports.ui.popupMenu; +import * as PopupMenu from 'resource:///org/gnome/shell/ui/popupMenu.js'; +import {gettext as _} from 'resource:///org/gnome/shell/extensions/extension.js'; // Relative and misc imports and definitions -const ExtensionUtils = imports.misc.extensionUtils; -const Me = ExtensionUtils.getCurrentExtension(); -const baseindicator = Me.imports.src.baseindicator; -const attemptUpdate = Me.imports.src.utils.attemptUpdate; - -const Gettext = imports.gettext.domain("gnome-shell-extension-cpupower"); -const _ = Gettext.gettext; +import * as baseindicator from './baseindicator.js'; +import {attemptUpdate} from './utils.js'; /* eslint no-unused-vars: "off" */ const UPDATE = 1; diff --git a/src/utils.js b/src/utils.js index 5a303207..ecbbab96 100644 --- a/src/utils.js +++ b/src/utils.js @@ -26,21 +26,19 @@ * */ -const GLib = imports.gi.GLib; -const Gio = imports.gi.Gio; -const ByteArray = imports.byteArray; +import Gio from 'gi://Gio'; +import GLib from 'gi://GLib'; -const ExtensionUtils = imports.misc.extensionUtils; -const Me = ExtensionUtils.getCurrentExtension(); -const EXTENSIONDIR = Me.dir.get_path(); -const INSTALLER = `${EXTENSIONDIR}/tool/installer.sh`; const PKEXEC = GLib.find_program_in_path("pkexec"); -const CONFIG = Me.imports.src.config; +import * as CONFIG from './config.js'; + +const EXTENSIONDIR = import.meta.url.substr('file://'.length, import.meta.url.lastIndexOf('/') - 'file://'.length) + '/..'; +const INSTALLER = `${EXTENSIONDIR}/tool/installer.sh`; // FIXME: I don't know how to call linux's getuid directly... /* exported getuid */ -function getuid() { - return parseInt(ByteArray.toString(GLib.spawn_sync(null, ["id", "-u"], null, GLib.SpawnFlags.SEARCH_PATH, null)[1])); +export function getuid() { + return parseInt(TextDecoder.decode(GLib.spawn_sync(null, ["id", "-u"], null, GLib.SpawnFlags.SEARCH_PATH, null)[1])); } function spawnProcessCheckExitCode(argv, callback) { @@ -73,22 +71,22 @@ function spawnProcessCheckExitCode(argv, callback) { } /* exported INSTALLER_SUCCESS */ -var INSTALLER_SUCCESS = 0; +export var INSTALLER_SUCCESS = 0; /* exported INSTALLER_INVALID_ARG */ -var INSTALLER_INVALID_ARG = 1; +export var INSTALLER_INVALID_ARG = 1; /* exported INSTALLER_FAILED */ -var INSTALLER_FAILED = 2; +export var INSTALLER_FAILED = 2; /* exported INSTALLER_NEEDS_UPDATE */ -var INSTALLER_NEEDS_UPDATE = 3; +export var INSTALLER_NEEDS_UPDATE = 3; /* exported INSTALLER_NEEDS_SECURITY_UPDATE */ -var INSTALLER_NEEDS_SECURITY_UPDATE = 4; +export var INSTALLER_NEEDS_SECURITY_UPDATE = 4; /* exported INSTALLER_NOT_INSTALLED */ -var INSTALLER_NOT_INSTALLED = 5; +export var INSTALLER_NOT_INSTALLED = 5; /* exported INSTALLER_MUST_BE_ROOT */ -var INSTALLER_MUST_BE_ROOT = 6; +export var INSTALLER_MUST_BE_ROOT = 6; /* exported checkInstalled */ -function checkInstalled(callback) { +export function checkInstalled(callback) { spawnProcessCheckExitCode( [INSTALLER, "--prefix", CONFIG.PREFIX, "--tool-suffix", CONFIG.TOOL_SUFFIX, "check"], callback, @@ -96,7 +94,7 @@ function checkInstalled(callback) { } /* exported attemptInstallation */ -function attemptInstallation(done) { +export function attemptInstallation(done) { spawnProcessCheckExitCode( [PKEXEC, INSTALLER, "--prefix", CONFIG.PREFIX, "--tool-suffix", CONFIG.TOOL_SUFFIX, "install"], done, @@ -104,7 +102,7 @@ function attemptInstallation(done) { } /* exported attemptUninstallation */ -function attemptUninstallation(done) { +export function attemptUninstallation(done) { spawnProcessCheckExitCode( [PKEXEC, INSTALLER, "--prefix", CONFIG.PREFIX, "--tool-suffix", CONFIG.TOOL_SUFFIX, "uninstall"], done, @@ -112,7 +110,7 @@ function attemptUninstallation(done) { } /* exported attemptUpdate */ -function attemptUpdate(done) { +export function attemptUpdate(done) { spawnProcessCheckExitCode( [PKEXEC, INSTALLER, "--prefix", CONFIG.PREFIX, "--tool-suffix", CONFIG.TOOL_SUFFIX, "update"], done, @@ -120,21 +118,21 @@ function attemptUpdate(done) { } /* exported CPUFREQCTL_SUCCESS */ -var CPUFREQCTL_SUCCESS = 0; +export var CPUFREQCTL_SUCCESS = 0; /* exported CPUFREQCTL_NO_ARGUMENTS */ -var CPUFREQCTL_NO_ARGUMENTS = 3; +export var CPUFREQCTL_NO_ARGUMENTS = 3; /* exported CPUFREQCTL_INVALID_ARGUMENT */ -var CPUFREQCTL_INVALID_ARGUMENT = 4; +export var CPUFREQCTL_INVALID_ARGUMENT = 4; /* exported CPUFREQCTL_OUT_OF_RANGE */ -var CPUFREQCTL_OUT_OF_RANGE = 5; +export var CPUFREQCTL_OUT_OF_RANGE = 5; /* exported CPUFREQCTL_NO_BACKEND */ -var CPUFREQCTL_NO_BACKEND = 6; +export var CPUFREQCTL_NO_BACKEND = 6; /* exported CPUFREQCTL_INVALID_BACKEND */ -var CPUFREQCTL_INVALID_BACKEND = 7; +export var CPUFREQCTL_INVALID_BACKEND = 7; /* exported CPUFREQCTL_INTERNAL_ERROR */ -var CPUFREQCTL_INTERNAL_ERROR = 8; +export var CPUFREQCTL_INTERNAL_ERROR = 8; /* exported CPUFREQCTL_NOT_SUPPORTED */ -var CPUFREQCTL_NOT_SUPPORTED = 9; +export var CPUFREQCTL_NOT_SUPPORTED = 9; function runCpufreqctl(pkexecNeeded, backend, params, cb) { let args = [ @@ -210,7 +208,7 @@ function runCpufreqctl(pkexecNeeded, backend, params, cb) { } /* exported Cpufreqctl */ -var Cpufreqctl = { +export var Cpufreqctl = { turbo: { get(backend, cb) { runCpufreqctl(false, backend, ["turbo", "get"], cb); diff --git a/test.sh b/test.sh new file mode 100755 index 00000000..ea748363 --- /dev/null +++ b/test.sh @@ -0,0 +1,9 @@ +#!/bin/sh -e + +export G_MESSAGES_DEBUG=all +export MUTTER_DEBUG_DUMMY_MODE_SPECS=1366x768 + +dbus-run-session -- \ + gnome-shell --nested \ + --wayland + diff --git a/tool/cpufreqctl b/tool/cpufreqctl index 1ae96f2d..96806cd0 100755 --- a/tool/cpufreqctl +++ b/tool/cpufreqctl @@ -22,6 +22,7 @@ # along with this program. If not, see . set -o errexit -o nounset +renice -n 19 0 >/dev/null VERSION="10.1.2" PRODUCTION=yes @@ -93,6 +94,36 @@ not_supported () EXIT_CODE=9 } +# echo min/max/avg/rnd of a space-separated list of numbers +# $1 number of element +# $2 space-separated list of numbers +compute_min_max_avg_rnd () +{ + nb_measures=$1 + measures=$2 + max=0 + min=10000000 + tot=0 + idx=0 + rnd_id=$(shuf -i 0-$((nb_measures-1)) -n 1) + for i in $measures; do + tot=$((tot + i)) + if [ "$i" -gt "$max" ]; then + max=$i + fi + if [ "$i" -lt "$min" ]; then + min=$i + fi + if [ "$idx" -eq "$rnd_id" ]; then + rnd=$i + fi + idx=$((idx+1)) + done + avg=$((tot/nb_measures)) + + echo --min "${min}" --max "${max}" --avg "${avg}" --rnd "${rnd}" +} + fake_init () { FAKE_DIR=/tmp/cpufreqctl-fake-backend @@ -175,24 +206,9 @@ fake_info_frequencies () fake_info_current () { fake_init - - shuf -i 800000-3600000 -n 12 | sort -n | awk ' - BEGIN { - srand() - } - NR == 1 { - printf "%d ", $1 - } - { - sum += $1 - r[NR] = $1 - } - END { - printf "%d %.0f %d\n", $1, sum / NR, r[int(rand() * NR) + 1] - }' | while read -r min max avg rnd - do - report_info_current --min "${min}" --max "${max}" --avg "${avg}" --rnd "${rnd}" - done + measures=$(shuf -i 800000-3600000 -n 12) + num_cores=12 + report_info_current $(compute_min_max_avg_rnd "$num_cores" "$measures") } intel_pstate_supported () @@ -276,26 +292,9 @@ intel_pstate_info_frequencies () intel_pstate_info_current () { - for scaling_cur_freq in /sys/devices/system/cpu/cpufreq/policy*/scaling_cur_freq - do - cat "${scaling_cur_freq}" & - done | sort -n | awk ' - BEGIN { - srand() - } - NR == 1 { - printf "%d ", $1 - } - { - sum += $1 - r[NR] = $1 - } - END { - printf "%d %.0f %d\n", $1, sum / NR, r[int(rand() * NR) + 1] - }' | while read -r min max avg rnd - do - report_info_current --min "${min}" --max "${max}" --avg "${avg}" --rnd "${rnd}" - done + measures=$(cat /sys/devices/system/cpu/cpufreq/policy*/scaling_cur_freq) + num_cores=$(getconf _NPROCESSORS_ONLN) + report_info_current $(compute_min_max_avg_rnd "$num_cores" "$measures") } cpufreq_supported () @@ -472,26 +471,9 @@ cpufreq_info_frequencies () cpufreq_info_current () { - for scaling_cur_freq in /sys/devices/system/cpu/cpufreq/policy*/scaling_cur_freq - do - cat "${scaling_cur_freq}" & - done | sort -n | awk ' - BEGIN { - srand() - } - NR == 1 { - printf "%d ", $1 - } - { - sum += $1 - r[NR] = $1 - } - END { - printf "%d %.0f %d\n", $1, sum / NR, r[int(rand() * NR) + 1] - }' | while read -r min max avg rnd - do - report_info_current --min "${min}" --max "${max}" --avg "${avg}" --rnd "${rnd}" - done + measures=$(cat /sys/devices/system/cpu/cpufreq/policy*/scaling_cur_freq) + num_cores=$(getconf _NPROCESSORS_ONLN) + report_info_current $(compute_min_max_avg_rnd "$num_cores" "$measures") } backend_select()