From e6afacba6b1652132d058c8768fbfb8c695126b2 Mon Sep 17 00:00:00 2001 From: Gustavo Freitas Date: Sun, 8 Jan 2023 20:52:24 -0300 Subject: [PATCH 01/10] add 43 version --- metadata.json | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/metadata.json b/metadata.json index a5f4ee8f..55a5795e 100644 --- a/metadata.json +++ b/metadata.json @@ -1,11 +1,9 @@ { - "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": ["3.28", "3.30", "3.36", "3.38", "40", "41", "42", "43"], + "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" } From 712c8260908c45025edba9483e6967f6dc91991e Mon Sep 17 00:00:00 2001 From: Gustavo Freitas Date: Sun, 8 Jan 2023 23:05:37 -0300 Subject: [PATCH 02/10] fix --- src/indicator.js | 1014 +++++++++++++++++++++++++--------------------- 1 file changed, 545 insertions(+), 469 deletions(-) diff --git a/src/indicator.js b/src/indicator.js index 573796f5..0a7571b2 100644 --- a/src/indicator.js +++ b/src/indicator.js @@ -54,521 +54,597 @@ const LASTSETTINGS = `${GLib.get_user_cache_dir()}/cpupower.last-settings`; /* exported CPUFreqIndicator */ var CPUFreqIndicator = class CPUFreqIndicator extends baseindicator.CPUFreqBaseIndicator { - constructor(onConstructed) { - super(); - this.cpufreq = 800; - this.cpucount = 0; - this.isTurboBoostActive = true; - this.isAutoSwitchActive = true; - this.minVal = 0; - this.maxVal = 100; - - // read the cached settings file. - if (GLib.file_test(LASTSETTINGS, GLib.FileTest.EXISTS)) { - 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} }`); - - this.updateMin(); - this.updateMax(); - this.updateTurbo(); - this.updateAutoSwitch(); - } - } else { - log(`Cached last settings not found: ${LASTSETTINGS}`); - } - - this.createIndicator(); - - this.checkFrequencies((result) => { - this.cpuMinLimit = result.min; - this.cpuMaxLimit = result.max; - this.createMenu(); - this.updateFreqMinMax(true); - - if (onConstructed) { - onConstructed(this); - } - }); - } - - onSettingsChanged() { - this.checkFrequencies((result) => { - this.cpuMinLimit = result.min; - this.cpuMaxLimit = result.max; - this.createIndicator(); - this.createMenu(); - this.updateFreqMinMax(true); - }); - } - - enable() { - this.power = Main.panel.statusArea["aggregateMenu"]._power; - this.powerState = this.power._proxy.State; - this.powerConnectSignalId = this.power._proxy.connect( - "g-properties-changed", - this.onPowerChanged.bind(this), + constructor(onConstructed) { + super(); + this.cpufreq = 800; + this.cpucount = 0; + this.isTurboBoostActive = true; + this.isAutoSwitchActive = true; + this.minVal = 0; + this.maxVal = 100; + + // read the cached settings file. + if (GLib.file_test(LASTSETTINGS, GLib.FileTest.EXISTS)) { + 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} }` ); - // 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.updateMin(); + this.updateMax(); + this.updateTurbo(); + this.updateAutoSwitch(); + } + } else { + log(`Cached last settings not found: ${LASTSETTINGS}`); } - onPowerChanged() { - let newState = this.power._proxy.State; - - if (newState !== this.powerState) { - this.powerActions(newState, null); - } - - this.powerState = newState; + this.createIndicator(); + + this.checkFrequencies((result) => { + this.cpuMinLimit = result.min; + this.cpuMaxLimit = result.max; + this.createMenu(); + this.updateFreqMinMax(true); + + if (onConstructed) { + onConstructed(this); + } + }); + } + + onSettingsChanged() { + this.checkFrequencies((result) => { + this.cpuMinLimit = result.min; + this.cpuMaxLimit = result.max; + this.createIndicator(); + this.createMenu(); + this.updateFreqMinMax(true); + }); + } + + enable() { + const Config = imports.misc.config; + if (parseInt(Config.PACKAGE_VERSION) >= 43) { + this.power = + Main.panel.statusArea.quickSettings._system._systemItem._powerToggle; + } else { + this.power = Main.panel.statusArea["aggregateMenu"]._power; } - powerActions(powerState, done) { - let doneScheduled = false; - - if (powerState === UPower.DeviceState.DISCHARGING) { - 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++) { - if (this.profiles[i].Profile.UUID === defaultBatProfileID) { - doneScheduled = true; - this.applyProfile(this.profiles[i].Profile, done); - break; - } - } - } - } else if (powerState === UPower.DeviceState.CHARGING || - powerState === UPower.DeviceState.FULLY_CHARGED) { - if (powerState === UPower.DeviceState.CHARGING) { - log("Power state changed: charging"); - } else { - log("Power state changed: fully charged"); - } - // 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++) { - if (this.profiles[i].Profile.UUID === defaultACProfileID) { - doneScheduled = true; - this.applyProfile(this.profiles[i].Profile, done); - break; - } - } - } - } + this.powerState = this.power._proxy.State; + this.powerConnectSignalId = this.power._proxy.connect( + "g-properties-changed", + this.onPowerChanged.bind(this) + ); + // select the right profile at login + this.powerActions(this.powerState, null); - if (!doneScheduled && done) { - done(); - } - } + super.enable(); - showError(msg, report) { - this.hasError = true; - this.lbl.set_text(""); - this.mainSection.removeAll(); - 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}, - ); - reportLabel.connect("activate", function () { - Gio.AppInfo.launch_default_for_uri("https://github.com/deinstapel/cpupower/issues/new", null); - }); - this.mainSection.addMenuItem(reportLabel); - } + this.timeout = Mainloop.timeout_add_seconds(1, () => this.updateFreq()); + this.timeoutMinMax = Mainloop.timeout_add_seconds(1, () => + this.updateFreqMinMax(false) + ); + } - this.mainSection.addMenuItem(new PopupMenu.PopupSeparatorMenuItem()); - this.imPrefsBtn = new PopupMenu.PopupMenuItem(_("Preferences")); - this.imPrefsBtn.connect("activate", this.onPreferencesActivate.bind(this)); - this.mainSection.addMenuItem(this.imPrefsBtn); - } + onPowerChanged() { + let newState = this.power._proxy.State; - clearError() { - if (this.hasError) { - this.createMenu(); - } + if (newState !== this.powerState) { + this.powerActions(newState, null); } - createMenu() { - super.createMenu(); - - let profiles = this.settings.get_value("profiles"); - profiles = profiles.deep_unpack(); - this.profiles = []; - for (var j = 0; j < profiles.length; j++) { - var profile = new CPUFreqProfile(); - profile.load(profiles[j]); - var profileButton = new CPUFreqProfileButton(profile); - this.profiles.push(profileButton); - } - this.profiles.reverse(); - - 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.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.connect("toggled", (item) => { - this.isTurboBoostActive = item.state; - this.updateTurbo(); - }); - - 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.minSlider.x_expand = true; - this.minSlider.maximum_value = 100; - this.minSlider.overdrive_start = 100; - // set max first, otherwise min will get clamped - this.minSlider.limit_maximum = this.maxVal; - this.minSlider.limit_minimum = this.cpuMinLimit; - this.imSliderMin.connect("key-press-event", (_actor, event) => { - return this.minSlider.emit("key-press-event", event); - }); - this.minSlider.connect("notify::value", (item) => { - this.minVal = Math.floor(item.value); - this.imMinLabel.set_text(this.getMinText()); - this.maxSlider.limit_minimum = this.minVal; - 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.powerState = newState; + } - this.imSliderMax = new PopupMenu.PopupBaseMenuItem({activate: false}); - this.maxSlider = new Slider.Slider2(this.maxVal); - this.maxSlider.x_expand = true; - this.maxSlider.maximum_value = 100; - this.maxSlider.overdrive_start = 100; - // set max first, otherwise min will get clamped - this.maxSlider.limit_maximum = this.cpuMaxLimit; - this.maxSlider.limit_minimum = this.minVal; - this.imSliderMax.connect("key-press-event", (_actor, event) => { - return this.maxSlider.emit("key-press-event", event); - }); - this.maxSlider.connect("notify::value", (item) => { - this.maxVal = Math.floor(item.value); - this.imMaxLabel.set_text(this.getMaxText()); - this.minSlider.limit_maximum = this.maxVal; - this.updateMax(); - }); + powerActions(powerState, done) { + let doneScheduled = false; - 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}); + if (powerState === UPower.DeviceState.DISCHARGING) { + 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++ + ) { + if (this.profiles[i].Profile.UUID === defaultBatProfileID) { + doneScheduled = true; + this.applyProfile(this.profiles[i].Profile, done); + break; + } } - - 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); - - this.mainSection.addMenuItem(this.imMinTitle); - this.mainSection.addMenuItem(this.imSliderMin); - this.mainSection.addMenuItem(new PopupMenu.PopupSeparatorMenuItem()); - this.mainSection.addMenuItem(this.imMaxTitle); - this.mainSection.addMenuItem(this.imSliderMax); - this.mainSection.addMenuItem(new PopupMenu.PopupSeparatorMenuItem()); - this.mainSection.addMenuItem(this.imTurboSwitch); - this.mainSection.addMenuItem(new PopupMenu.PopupSeparatorMenuItem()); - this.mainSection.addMenuItem(this.imCurrentTitle); - 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.mainSection.addMenuItem(this.profiles[i]); + } + } else if ( + powerState === UPower.DeviceState.CHARGING || + powerState === UPower.DeviceState.FULLY_CHARGED + ) { + if (powerState === UPower.DeviceState.CHARGING) { + log("Power state changed: charging"); + } else { + log("Power state changed: fully charged"); + } + // 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++ + ) { + if (this.profiles[i].Profile.UUID === defaultACProfileID) { + doneScheduled = true; + this.applyProfile(this.profiles[i].Profile, done); + break; + } } - - this.mainSection.addMenuItem(new PopupMenu.PopupSeparatorMenuItem()); - this.mainSection.addMenuItem(this.imAutoSwitch); - - this.imPrefsBtn = new PopupMenu.PopupMenuItem(_("Preferences")); - 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) => { - 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, - ); - } - } else { - this.clearError(); - } - }); + } } - applyProfile(profile, done) { - this.minVal = profile.MinimumFrequency; - this.updateMin(() => { - this.maxVal = profile.MaximumFrequency; - this.updateMax(() => { - this.isTurboBoostActive = profile.TurboBoost; - this.updateTurbo(() => { - this.updateUi(); - - if (done) { - done(); - } - }); - }); - }); + if (!doneScheduled && done) { + done(); } - - disable() { - this.power._proxy.disconnect(this.powerConnectSignalId); - super.disable(); - Mainloop.source_remove(this.timeout); - Mainloop.source_remove(this.timeoutMinMax); + } + + showError(msg, report) { + this.hasError = true; + this.lbl.set_text(""); + this.mainSection.removeAll(); + 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 } + ); + reportLabel.connect("activate", function () { + Gio.AppInfo.launch_default_for_uri( + "https://github.com/deinstapel/cpupower/issues/new", + null + ); + }); + this.mainSection.addMenuItem(reportLabel); } - getMinText() { - return `${Math.floor(this.minVal).toString()}%`; - } + this.mainSection.addMenuItem(new PopupMenu.PopupSeparatorMenuItem()); + this.imPrefsBtn = new PopupMenu.PopupMenuItem(_("Preferences")); + this.imPrefsBtn.connect("activate", this.onPreferencesActivate.bind(this)); + this.mainSection.addMenuItem(this.imPrefsBtn); + } - getMaxText() { - return `${Math.floor(this.maxVal).toString()}%`; + clearError() { + if (this.hasError) { + this.createMenu(); } - - updateFile() { - let cmd = `${Math.floor(this.minVal)}\n` + - `${Math.floor(this.maxVal)}\n` + - `${this.isTurboBoostActive ? "true" : "false"}\n` + - `${this.isAutoSwitchActive ? "true" : "false"}\n`; - // log("Updating cpufreq settings cache file: " + LASTSETTINGS); - GLib.file_set_contents(LASTSETTINGS, cmd); + } + + createMenu() { + super.createMenu(); + + let profiles = this.settings.get_value("profiles"); + profiles = profiles.deep_unpack(); + this.profiles = []; + for (var j = 0; j < profiles.length; j++) { + var profile = new CPUFreqProfile(); + profile.load(profiles[j]); + var profileButton = new CPUFreqProfileButton(profile); + this.profiles.push(profileButton); } - - updateMax(done) { - let backend = this.settings.get_string("cpufreqctl-backend"); - Cpufreqctl.max.set(backend, Math.floor(this.maxVal).toString(), (_result) => { - this.updateFile(); - - if (done) { - done(); - } - }); + this.profiles.reverse(); + + 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.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.connect("toggled", (item) => { + this.isTurboBoostActive = item.state; + this.updateTurbo(); + }); + + 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.minSlider.x_expand = true; + this.minSlider.maximum_value = 100; + this.minSlider.overdrive_start = 100; + // set max first, otherwise min will get clamped + this.minSlider.limit_maximum = this.maxVal; + this.minSlider.limit_minimum = this.cpuMinLimit; + this.imSliderMin.connect("key-press-event", (_actor, event) => { + return this.minSlider.emit("key-press-event", event); + }); + this.minSlider.connect("notify::value", (item) => { + this.minVal = Math.floor(item.value); + this.imMinLabel.set_text(this.getMinText()); + this.maxSlider.limit_minimum = this.minVal; + 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 }); } - updateMin(done) { - let backend = this.settings.get_string("cpufreqctl-backend"); - Cpufreqctl.min.set(backend, Math.floor(this.minVal).toString(), (_result) => { - this.updateFile(); - - if (done) { - done(); - } - }); + this.imSliderMax = new PopupMenu.PopupBaseMenuItem({ activate: false }); + this.maxSlider = new Slider.Slider2(this.maxVal); + this.maxSlider.x_expand = true; + this.maxSlider.maximum_value = 100; + this.maxSlider.overdrive_start = 100; + // set max first, otherwise min will get clamped + this.maxSlider.limit_maximum = this.cpuMaxLimit; + this.maxSlider.limit_minimum = this.minVal; + this.imSliderMax.connect("key-press-event", (_actor, event) => { + return this.maxSlider.emit("key-press-event", event); + }); + this.maxSlider.connect("notify::value", (item) => { + this.maxVal = Math.floor(item.value); + this.imMaxLabel.set_text(this.getMaxText()); + this.minSlider.limit_maximum = this.maxVal; + 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 }); } - updateTurbo(done) { - let backend = this.settings.get_string("cpufreqctl-backend"); - Cpufreqctl.turbo.set(backend, this.isTurboBoostActive ? "on" : "off", (_result) => { - this.updateFile(); - - if (done) { - done(); - } - }); + 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); + + this.mainSection.addMenuItem(this.imMinTitle); + this.mainSection.addMenuItem(this.imSliderMin); + this.mainSection.addMenuItem(new PopupMenu.PopupSeparatorMenuItem()); + this.mainSection.addMenuItem(this.imMaxTitle); + this.mainSection.addMenuItem(this.imSliderMax); + this.mainSection.addMenuItem(new PopupMenu.PopupSeparatorMenuItem()); + this.mainSection.addMenuItem(this.imTurboSwitch); + this.mainSection.addMenuItem(new PopupMenu.PopupSeparatorMenuItem()); + this.mainSection.addMenuItem(this.imCurrentTitle); + 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.mainSection.addMenuItem(this.profiles[i]); } - updateAutoSwitch() { - if (this.powerState) { - this.powerActions(this.powerState, () => { - this.updateFile(); - }); + this.mainSection.addMenuItem(new PopupMenu.PopupSeparatorMenuItem()); + this.mainSection.addMenuItem(this.imAutoSwitch); + + this.imPrefsBtn = new PopupMenu.PopupMenuItem(_("Preferences")); + 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) => { + 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 + ); } - } - - updateUi() { - if (this.hasError) { - return; + } else { + this.clearError(); + } + }); + } + + applyProfile(profile, done) { + this.minVal = profile.MinimumFrequency; + this.updateMin(() => { + this.maxVal = profile.MaximumFrequency; + this.updateMax(() => { + this.isTurboBoostActive = profile.TurboBoost; + this.updateTurbo(() => { + this.updateUi(); + + if (done) { + done(); + } + }); + }); + }); + } + + disable() { + this.power._proxy.disconnect(this.powerConnectSignalId); + super.disable(); + Mainloop.source_remove(this.timeout); + Mainloop.source_remove(this.timeoutMinMax); + } + + getMinText() { + return `${Math.floor(this.minVal).toString()}%`; + } + + getMaxText() { + return `${Math.floor(this.maxVal).toString()}%`; + } + + updateFile() { + let cmd = + `${Math.floor(this.minVal)}\n` + + `${Math.floor(this.maxVal)}\n` + + `${this.isTurboBoostActive ? "true" : "false"}\n` + + `${this.isAutoSwitchActive ? "true" : "false"}\n`; + // log("Updating cpufreq settings cache file: " + LASTSETTINGS); + GLib.file_set_contents(LASTSETTINGS, cmd); + } + + updateMax(done) { + let backend = this.settings.get_string("cpufreqctl-backend"); + Cpufreqctl.max.set( + backend, + Math.floor(this.maxVal).toString(), + (_result) => { + this.updateFile(); + + if (done) { + done(); } - - this.imMinLabel.set_text(this.getMinText()); - this.minSlider.value = this.minVal; - - this.imMaxLabel.set_text(this.getMaxText()); - this.maxSlider.value = this.maxVal; - - this.imTurboSwitch.setToggleState(this.isTurboBoostActive); - this.imAutoSwitch.setToggleState(this.isAutoSwitchActive); - for (let p of this.profiles) { - p.setOrnament( - this.minVal === p.Profile.MinimumFrequency && - this.maxVal === p.Profile.MaximumFrequency && - this.isTurboBoostActive === p.Profile.TurboBoost - ? PopupMenu.Ornament.DOT : PopupMenu.Ornament.NONE, - ); + } + ); + } + + updateMin(done) { + let backend = this.settings.get_string("cpufreqctl-backend"); + Cpufreqctl.min.set( + backend, + Math.floor(this.minVal).toString(), + (_result) => { + this.updateFile(); + + if (done) { + done(); + } + } + ); + } + + updateTurbo(done) { + let backend = this.settings.get_string("cpufreqctl-backend"); + Cpufreqctl.turbo.set( + backend, + this.isTurboBoostActive ? "on" : "off", + (_result) => { + this.updateFile(); + + if (done) { + done(); } + } + ); + } + + updateAutoSwitch() { + if (this.powerState) { + this.powerActions(this.powerState, () => { + this.updateFile(); + }); } + } - 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)) { - return true; - } + updateUi() { + if (this.hasError) { + return; + } - const backend = this.settings.get_string("cpufreqctl-backend"); - 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; - } - this.cpufreq = value / 1000; - if (this.menu && this.menu.isOpen) { - this.imCurrentLabel.set_text(this.getCurFreq()); - } - this.lbl.set_text(this.getCurFreq()); - } - }); + this.imMinLabel.set_text(this.getMinText()); + this.minSlider.value = this.minVal; + + this.imMaxLabel.set_text(this.getMaxText()); + this.maxSlider.value = this.maxVal; + + this.imTurboSwitch.setToggleState(this.isTurboBoostActive); + this.imAutoSwitch.setToggleState(this.isAutoSwitchActive); + for (let p of this.profiles) { + p.setOrnament( + this.minVal === p.Profile.MinimumFrequency && + this.maxVal === p.Profile.MaximumFrequency && + this.isTurboBoostActive === p.Profile.TurboBoost + ? PopupMenu.Ornament.DOT + : PopupMenu.Ornament.NONE + ); + } + } - return true; + 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))) { + return true; } - updateFreqMinMax(force) { - const menuOpen = this.menu && this.menu.isOpen; - if (!force && !menuOpen) { - return true; + const backend = this.settings.get_string("cpufreqctl-backend"); + 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; } + this.cpufreq = value / 1000; + if (this.menu && this.menu.isOpen) { + this.imCurrentLabel.set_text(this.getCurFreq()); + } + this.lbl.set_text(this.getCurFreq()); + } + }); - // merging multiple async callbacks in js is a pain... - let counter = 0; - const updateUi = () => { - counter += 1; - if ((force || menuOpen) && counter >= 3) { - this.updateUi(); - } - }; - - const backend = this.settings.get_string("cpufreqctl-backend"); - Cpufreqctl.turbo.get(backend, (result) => { - if (result.ok && result.exitCode === 0) { - this.isTurboBoostActive = result.response === "on"; - } - updateUi(); - }); - - Cpufreqctl.min.get(backend, (result) => { - if (result.ok && result.exitCode === 0) { - this.minVal = result.response; - } - updateUi(); - }); - - Cpufreqctl.max.get(backend, (result) => { - if (result.ok && result.exitCode === 0) { - this.maxVal = result.response; - } - updateUi(); - }); - - return true; - } + return true; + } - 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, - }); - } - }); + updateFreqMinMax(force) { + const menuOpen = this.menu && this.menu.isOpen; + if (!force && !menuOpen) { + return true; } - getCurFreq() { - if (this.lblUnit) { - return `${(this.cpufreq / 1000).toFixed(2)} GHz`; + // merging multiple async callbacks in js is a pain... + let counter = 0; + const updateUi = () => { + counter += 1; + if ((force || menuOpen) && counter >= 3) { + this.updateUi(); + } + }; + + const backend = this.settings.get_string("cpufreqctl-backend"); + Cpufreqctl.turbo.get(backend, (result) => { + if (result.ok && result.exitCode === 0) { + this.isTurboBoostActive = result.response === "on"; + } + updateUi(); + }); + + Cpufreqctl.min.get(backend, (result) => { + if (result.ok && result.exitCode === 0) { + this.minVal = result.response; + } + updateUi(); + }); + + Cpufreqctl.max.get(backend, (result) => { + if (result.ok && result.exitCode === 0) { + this.maxVal = result.response; + } + updateUi(); + }); + + return true; + } + + 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 { - return `${Math.round(this.cpufreq)} MHz`; + log( + `Cpufreqctl signaled unsupported frequency mode ${result.response.mode}! ` + + "Assuming full range..." + ); + cb({ + min: 0, + max: 100, + }); } + } + ); + } + + getCurFreq() { + if (this.lblUnit) { + return `${(this.cpufreq / 1000).toFixed(2)} GHz`; + } else { + return `${Math.round(this.cpufreq)} MHz`; } - - 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; + } + + 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; + } }; From 29b1d8b03bfec6f5fe75e056d90a2ffca9cb98f2 Mon Sep 17 00:00:00 2001 From: Gustavo Freitas Date: Sun, 8 Jan 2023 23:18:43 -0300 Subject: [PATCH 03/10] 4 spaces prettier --- src/indicator.js | 1105 +++++++++++++++++++++++----------------------- 1 file changed, 561 insertions(+), 544 deletions(-) diff --git a/src/indicator.js b/src/indicator.js index 0a7571b2..0b428a4c 100644 --- a/src/indicator.js +++ b/src/indicator.js @@ -54,597 +54,614 @@ const LASTSETTINGS = `${GLib.get_user_cache_dir()}/cpupower.last-settings`; /* exported CPUFreqIndicator */ var CPUFreqIndicator = class CPUFreqIndicator extends baseindicator.CPUFreqBaseIndicator { - constructor(onConstructed) { - super(); - this.cpufreq = 800; - this.cpucount = 0; - this.isTurboBoostActive = true; - this.isAutoSwitchActive = true; - this.minVal = 0; - this.maxVal = 100; - - // read the cached settings file. - if (GLib.file_test(LASTSETTINGS, GLib.FileTest.EXISTS)) { - 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} }` + constructor(onConstructed) { + super(); + this.cpufreq = 800; + this.cpucount = 0; + this.isTurboBoostActive = true; + this.isAutoSwitchActive = true; + this.minVal = 0; + this.maxVal = 100; + + // read the cached settings file. + if (GLib.file_test(LASTSETTINGS, GLib.FileTest.EXISTS)) { + 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} }` + ); + + this.updateMin(); + this.updateMax(); + this.updateTurbo(); + this.updateAutoSwitch(); + } + } else { + log(`Cached last settings not found: ${LASTSETTINGS}`); + } + + this.createIndicator(); + + this.checkFrequencies((result) => { + this.cpuMinLimit = result.min; + this.cpuMaxLimit = result.max; + this.createMenu(); + this.updateFreqMinMax(true); + + if (onConstructed) { + onConstructed(this); + } + }); + } + + onSettingsChanged() { + this.checkFrequencies((result) => { + this.cpuMinLimit = result.min; + this.cpuMaxLimit = result.max; + this.createIndicator(); + this.createMenu(); + this.updateFreqMinMax(true); + }); + } + + enable() { + const Config = imports.misc.config; + if (parseInt(Config.PACKAGE_VERSION) >= 43) { + this.power = + Main.panel.statusArea.quickSettings._system._systemItem._powerToggle; + } else { + this.power = Main.panel.statusArea["aggregateMenu"]._power; + } + + this.powerState = this.power._proxy.State; + this.powerConnectSignalId = this.power._proxy.connect( + "g-properties-changed", + this.onPowerChanged.bind(this) ); + // select the right profile at login + this.powerActions(this.powerState, null); + + super.enable(); - this.updateMin(); - this.updateMax(); - this.updateTurbo(); - this.updateAutoSwitch(); - } - } else { - log(`Cached last settings not found: ${LASTSETTINGS}`); + this.timeout = Mainloop.timeout_add_seconds(1, () => this.updateFreq()); + this.timeoutMinMax = Mainloop.timeout_add_seconds(1, () => + this.updateFreqMinMax(false) + ); } - this.createIndicator(); - - this.checkFrequencies((result) => { - this.cpuMinLimit = result.min; - this.cpuMaxLimit = result.max; - this.createMenu(); - this.updateFreqMinMax(true); - - if (onConstructed) { - onConstructed(this); - } - }); - } - - onSettingsChanged() { - this.checkFrequencies((result) => { - this.cpuMinLimit = result.min; - this.cpuMaxLimit = result.max; - this.createIndicator(); - this.createMenu(); - this.updateFreqMinMax(true); - }); - } - - enable() { - const Config = imports.misc.config; - if (parseInt(Config.PACKAGE_VERSION) >= 43) { - this.power = - Main.panel.statusArea.quickSettings._system._systemItem._powerToggle; - } else { - this.power = Main.panel.statusArea["aggregateMenu"]._power; + onPowerChanged() { + let newState = this.power._proxy.State; + + if (newState !== this.powerState) { + this.powerActions(newState, null); + } + + this.powerState = newState; } - this.powerState = this.power._proxy.State; - this.powerConnectSignalId = this.power._proxy.connect( - "g-properties-changed", - this.onPowerChanged.bind(this) - ); - // select the right profile at login - this.powerActions(this.powerState, null); + powerActions(powerState, done) { + let doneScheduled = false; + + if (powerState === UPower.DeviceState.DISCHARGING) { + 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++ + ) { + if (this.profiles[i].Profile.UUID === defaultBatProfileID) { + doneScheduled = true; + this.applyProfile(this.profiles[i].Profile, done); + break; + } + } + } + } else if ( + powerState === UPower.DeviceState.CHARGING || + powerState === UPower.DeviceState.FULLY_CHARGED + ) { + if (powerState === UPower.DeviceState.CHARGING) { + log("Power state changed: charging"); + } else { + log("Power state changed: fully charged"); + } + // 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++ + ) { + if (this.profiles[i].Profile.UUID === defaultACProfileID) { + doneScheduled = true; + this.applyProfile(this.profiles[i].Profile, done); + break; + } + } + } + } - super.enable(); + if (!doneScheduled && done) { + done(); + } + } - this.timeout = Mainloop.timeout_add_seconds(1, () => this.updateFreq()); - this.timeoutMinMax = Mainloop.timeout_add_seconds(1, () => - this.updateFreqMinMax(false) - ); - } + showError(msg, report) { + this.hasError = true; + this.lbl.set_text(""); + this.mainSection.removeAll(); + this.mainSection.addMenuItem( + new PopupMenu.PopupMenuItem(msg, { reactive: false }) + ); - onPowerChanged() { - let newState = this.power._proxy.State; + 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 } + ); + reportLabel.connect("activate", function () { + 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.mainSection.addMenuItem(this.imPrefsBtn); + } - if (newState !== this.powerState) { - this.powerActions(newState, null); + clearError() { + if (this.hasError) { + this.createMenu(); + } } - this.powerState = newState; - } + createMenu() { + super.createMenu(); + + let profiles = this.settings.get_value("profiles"); + profiles = profiles.deep_unpack(); + this.profiles = []; + for (var j = 0; j < profiles.length; j++) { + var profile = new CPUFreqProfile(); + profile.load(profiles[j]); + var profileButton = new CPUFreqProfileButton(profile); + this.profiles.push(profileButton); + } + this.profiles.reverse(); - powerActions(powerState, done) { - let doneScheduled = false; + 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); - if (powerState === UPower.DeviceState.DISCHARGING) { - 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" + this.imMaxTitle = new PopupMenu.PopupMenuItem( + `${_("Maximum Frequency")}:`, + { reactive: false } ); - 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); - break; - } + 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.connect("toggled", (item) => { + this.isTurboBoostActive = item.state; + this.updateTurbo(); + }); + + 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.minSlider.x_expand = true; + this.minSlider.maximum_value = 100; + this.minSlider.overdrive_start = 100; + // set max first, otherwise min will get clamped + this.minSlider.limit_maximum = this.maxVal; + this.minSlider.limit_minimum = this.cpuMinLimit; + this.imSliderMin.connect("key-press-event", (_actor, event) => { + return this.minSlider.emit("key-press-event", event); + }); + this.minSlider.connect("notify::value", (item) => { + this.minVal = Math.floor(item.value); + this.imMinLabel.set_text(this.getMinText()); + this.maxSlider.limit_minimum = this.minVal; + 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 }); } - } - } else if ( - powerState === UPower.DeviceState.CHARGING || - powerState === UPower.DeviceState.FULLY_CHARGED - ) { - if (powerState === UPower.DeviceState.CHARGING) { - log("Power state changed: charging"); - } else { - log("Power state changed: fully charged"); - } - // 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++ - ) { - if (this.profiles[i].Profile.UUID === defaultACProfileID) { - doneScheduled = true; - this.applyProfile(this.profiles[i].Profile, done); - break; - } + + this.imSliderMax = new PopupMenu.PopupBaseMenuItem({ activate: false }); + this.maxSlider = new Slider.Slider2(this.maxVal); + this.maxSlider.x_expand = true; + this.maxSlider.maximum_value = 100; + this.maxSlider.overdrive_start = 100; + // set max first, otherwise min will get clamped + this.maxSlider.limit_maximum = this.cpuMaxLimit; + this.maxSlider.limit_minimum = this.minVal; + this.imSliderMax.connect("key-press-event", (_actor, event) => { + return this.maxSlider.emit("key-press-event", event); + }); + this.maxSlider.connect("notify::value", (item) => { + this.maxVal = Math.floor(item.value); + this.imMaxLabel.set_text(this.getMaxText()); + this.minSlider.limit_maximum = this.maxVal; + 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.imCurrentLabel.set_style("width: 4.5em; text-align: right"); + this.imCurrentTitle.actor.add_child(this.imCurrentLabel); + + this.mainSection.addMenuItem(this.imMinTitle); + this.mainSection.addMenuItem(this.imSliderMin); + this.mainSection.addMenuItem(new PopupMenu.PopupSeparatorMenuItem()); + this.mainSection.addMenuItem(this.imMaxTitle); + this.mainSection.addMenuItem(this.imSliderMax); + this.mainSection.addMenuItem(new PopupMenu.PopupSeparatorMenuItem()); + this.mainSection.addMenuItem(this.imTurboSwitch); + this.mainSection.addMenuItem(new PopupMenu.PopupSeparatorMenuItem()); + this.mainSection.addMenuItem(this.imCurrentTitle); + 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.mainSection.addMenuItem(this.profiles[i]); } - } + + this.mainSection.addMenuItem(new PopupMenu.PopupSeparatorMenuItem()); + this.mainSection.addMenuItem(this.imAutoSwitch); + + this.imPrefsBtn = new PopupMenu.PopupMenuItem(_("Preferences")); + 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) => { + 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 + ); + } + } else { + this.clearError(); + } + }); } - if (!doneScheduled && done) { - done(); + applyProfile(profile, done) { + this.minVal = profile.MinimumFrequency; + this.updateMin(() => { + this.maxVal = profile.MaximumFrequency; + this.updateMax(() => { + this.isTurboBoostActive = profile.TurboBoost; + this.updateTurbo(() => { + this.updateUi(); + + if (done) { + done(); + } + }); + }); + }); } - } - - showError(msg, report) { - this.hasError = true; - this.lbl.set_text(""); - this.mainSection.removeAll(); - 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 } - ); - reportLabel.connect("activate", function () { - Gio.AppInfo.launch_default_for_uri( - "https://github.com/deinstapel/cpupower/issues/new", - null - ); - }); - this.mainSection.addMenuItem(reportLabel); + + disable() { + this.power._proxy.disconnect(this.powerConnectSignalId); + super.disable(); + Mainloop.source_remove(this.timeout); + Mainloop.source_remove(this.timeoutMinMax); } - this.mainSection.addMenuItem(new PopupMenu.PopupSeparatorMenuItem()); - this.imPrefsBtn = new PopupMenu.PopupMenuItem(_("Preferences")); - this.imPrefsBtn.connect("activate", this.onPreferencesActivate.bind(this)); - this.mainSection.addMenuItem(this.imPrefsBtn); - } + getMinText() { + return `${Math.floor(this.minVal).toString()}%`; + } - clearError() { - if (this.hasError) { - this.createMenu(); + getMaxText() { + return `${Math.floor(this.maxVal).toString()}%`; } - } - - createMenu() { - super.createMenu(); - - let profiles = this.settings.get_value("profiles"); - profiles = profiles.deep_unpack(); - this.profiles = []; - for (var j = 0; j < profiles.length; j++) { - var profile = new CPUFreqProfile(); - profile.load(profiles[j]); - var profileButton = new CPUFreqProfileButton(profile); - this.profiles.push(profileButton); + + updateFile() { + let cmd = + `${Math.floor(this.minVal)}\n` + + `${Math.floor(this.maxVal)}\n` + + `${this.isTurboBoostActive ? "true" : "false"}\n` + + `${this.isAutoSwitchActive ? "true" : "false"}\n`; + // log("Updating cpufreq settings cache file: " + LASTSETTINGS); + GLib.file_set_contents(LASTSETTINGS, cmd); } - this.profiles.reverse(); - - 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.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.connect("toggled", (item) => { - this.isTurboBoostActive = item.state; - this.updateTurbo(); - }); - - 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.minSlider.x_expand = true; - this.minSlider.maximum_value = 100; - this.minSlider.overdrive_start = 100; - // set max first, otherwise min will get clamped - this.minSlider.limit_maximum = this.maxVal; - this.minSlider.limit_minimum = this.cpuMinLimit; - this.imSliderMin.connect("key-press-event", (_actor, event) => { - return this.minSlider.emit("key-press-event", event); - }); - this.minSlider.connect("notify::value", (item) => { - this.minVal = Math.floor(item.value); - this.imMinLabel.set_text(this.getMinText()); - this.maxSlider.limit_minimum = this.minVal; - 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 }); + + updateMax(done) { + let backend = this.settings.get_string("cpufreqctl-backend"); + Cpufreqctl.max.set( + backend, + Math.floor(this.maxVal).toString(), + (_result) => { + this.updateFile(); + + if (done) { + done(); + } + } + ); } - this.imSliderMax = new PopupMenu.PopupBaseMenuItem({ activate: false }); - this.maxSlider = new Slider.Slider2(this.maxVal); - this.maxSlider.x_expand = true; - this.maxSlider.maximum_value = 100; - this.maxSlider.overdrive_start = 100; - // set max first, otherwise min will get clamped - this.maxSlider.limit_maximum = this.cpuMaxLimit; - this.maxSlider.limit_minimum = this.minVal; - this.imSliderMax.connect("key-press-event", (_actor, event) => { - return this.maxSlider.emit("key-press-event", event); - }); - this.maxSlider.connect("notify::value", (item) => { - this.maxVal = Math.floor(item.value); - this.imMaxLabel.set_text(this.getMaxText()); - this.minSlider.limit_maximum = this.maxVal; - 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 }); + updateMin(done) { + let backend = this.settings.get_string("cpufreqctl-backend"); + Cpufreqctl.min.set( + backend, + Math.floor(this.minVal).toString(), + (_result) => { + this.updateFile(); + + if (done) { + done(); + } + } + ); } - 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); - - this.mainSection.addMenuItem(this.imMinTitle); - this.mainSection.addMenuItem(this.imSliderMin); - this.mainSection.addMenuItem(new PopupMenu.PopupSeparatorMenuItem()); - this.mainSection.addMenuItem(this.imMaxTitle); - this.mainSection.addMenuItem(this.imSliderMax); - this.mainSection.addMenuItem(new PopupMenu.PopupSeparatorMenuItem()); - this.mainSection.addMenuItem(this.imTurboSwitch); - this.mainSection.addMenuItem(new PopupMenu.PopupSeparatorMenuItem()); - this.mainSection.addMenuItem(this.imCurrentTitle); - 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.mainSection.addMenuItem(this.profiles[i]); + updateTurbo(done) { + let backend = this.settings.get_string("cpufreqctl-backend"); + Cpufreqctl.turbo.set( + backend, + this.isTurboBoostActive ? "on" : "off", + (_result) => { + this.updateFile(); + + if (done) { + done(); + } + } + ); } - this.mainSection.addMenuItem(new PopupMenu.PopupSeparatorMenuItem()); - this.mainSection.addMenuItem(this.imAutoSwitch); - - this.imPrefsBtn = new PopupMenu.PopupMenuItem(_("Preferences")); - 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) => { - 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 - ); - } - } else { - this.clearError(); - } - }); - } - - applyProfile(profile, done) { - this.minVal = profile.MinimumFrequency; - this.updateMin(() => { - this.maxVal = profile.MaximumFrequency; - this.updateMax(() => { - this.isTurboBoostActive = profile.TurboBoost; - this.updateTurbo(() => { - this.updateUi(); - - if (done) { - done(); - } - }); - }); - }); - } - - disable() { - this.power._proxy.disconnect(this.powerConnectSignalId); - super.disable(); - Mainloop.source_remove(this.timeout); - Mainloop.source_remove(this.timeoutMinMax); - } - - getMinText() { - return `${Math.floor(this.minVal).toString()}%`; - } - - getMaxText() { - return `${Math.floor(this.maxVal).toString()}%`; - } - - updateFile() { - let cmd = - `${Math.floor(this.minVal)}\n` + - `${Math.floor(this.maxVal)}\n` + - `${this.isTurboBoostActive ? "true" : "false"}\n` + - `${this.isAutoSwitchActive ? "true" : "false"}\n`; - // log("Updating cpufreq settings cache file: " + LASTSETTINGS); - GLib.file_set_contents(LASTSETTINGS, cmd); - } - - updateMax(done) { - let backend = this.settings.get_string("cpufreqctl-backend"); - Cpufreqctl.max.set( - backend, - Math.floor(this.maxVal).toString(), - (_result) => { - this.updateFile(); - - if (done) { - done(); + updateAutoSwitch() { + if (this.powerState) { + this.powerActions(this.powerState, () => { + this.updateFile(); + }); } - } - ); - } - - updateMin(done) { - let backend = this.settings.get_string("cpufreqctl-backend"); - Cpufreqctl.min.set( - backend, - Math.floor(this.minVal).toString(), - (_result) => { - this.updateFile(); - - if (done) { - done(); + } + + updateUi() { + if (this.hasError) { + return; } - } - ); - } - - updateTurbo(done) { - let backend = this.settings.get_string("cpufreqctl-backend"); - Cpufreqctl.turbo.set( - backend, - this.isTurboBoostActive ? "on" : "off", - (_result) => { - this.updateFile(); - - if (done) { - done(); + + this.imMinLabel.set_text(this.getMinText()); + this.minSlider.value = this.minVal; + + this.imMaxLabel.set_text(this.getMaxText()); + this.maxSlider.value = this.maxVal; + + this.imTurboSwitch.setToggleState(this.isTurboBoostActive); + this.imAutoSwitch.setToggleState(this.isAutoSwitchActive); + for (let p of this.profiles) { + p.setOrnament( + this.minVal === p.Profile.MinimumFrequency && + this.maxVal === p.Profile.MaximumFrequency && + this.isTurboBoostActive === p.Profile.TurboBoost + ? PopupMenu.Ornament.DOT + : PopupMenu.Ornament.NONE + ); } - } - ); - } - - updateAutoSwitch() { - if (this.powerState) { - this.powerActions(this.powerState, () => { - this.updateFile(); - }); } - } - updateUi() { - if (this.hasError) { - return; - } + 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)) + ) { + return true; + } - this.imMinLabel.set_text(this.getMinText()); - this.minSlider.value = this.minVal; - - this.imMaxLabel.set_text(this.getMaxText()); - this.maxSlider.value = this.maxVal; - - this.imTurboSwitch.setToggleState(this.isTurboBoostActive); - this.imAutoSwitch.setToggleState(this.isAutoSwitchActive); - for (let p of this.profiles) { - p.setOrnament( - this.minVal === p.Profile.MinimumFrequency && - this.maxVal === p.Profile.MaximumFrequency && - this.isTurboBoostActive === p.Profile.TurboBoost - ? PopupMenu.Ornament.DOT - : PopupMenu.Ornament.NONE - ); - } - } + const backend = this.settings.get_string("cpufreqctl-backend"); + 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; + } + this.cpufreq = value / 1000; + if (this.menu && this.menu.isOpen) { + this.imCurrentLabel.set_text(this.getCurFreq()); + } + this.lbl.set_text(this.getCurFreq()); + } + }); - 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))) { - return true; + return true; } - const backend = this.settings.get_string("cpufreqctl-backend"); - 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; - } - this.cpufreq = value / 1000; - if (this.menu && this.menu.isOpen) { - this.imCurrentLabel.set_text(this.getCurFreq()); + updateFreqMinMax(force) { + const menuOpen = this.menu && this.menu.isOpen; + if (!force && !menuOpen) { + return true; } - this.lbl.set_text(this.getCurFreq()); - } - }); - return true; - } + // merging multiple async callbacks in js is a pain... + let counter = 0; + const updateUi = () => { + counter += 1; + if ((force || menuOpen) && counter >= 3) { + this.updateUi(); + } + }; + + const backend = this.settings.get_string("cpufreqctl-backend"); + Cpufreqctl.turbo.get(backend, (result) => { + if (result.ok && result.exitCode === 0) { + this.isTurboBoostActive = result.response === "on"; + } + updateUi(); + }); + + Cpufreqctl.min.get(backend, (result) => { + if (result.ok && result.exitCode === 0) { + this.minVal = result.response; + } + updateUi(); + }); + + Cpufreqctl.max.get(backend, (result) => { + if (result.ok && result.exitCode === 0) { + this.maxVal = result.response; + } + updateUi(); + }); + + return true; + } - updateFreqMinMax(force) { - const menuOpen = this.menu && this.menu.isOpen; - if (!force && !menuOpen) { - return true; + 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, + }); + } + } + ); } - // merging multiple async callbacks in js is a pain... - let counter = 0; - const updateUi = () => { - counter += 1; - if ((force || menuOpen) && counter >= 3) { - this.updateUi(); - } - }; - - const backend = this.settings.get_string("cpufreqctl-backend"); - Cpufreqctl.turbo.get(backend, (result) => { - if (result.ok && result.exitCode === 0) { - this.isTurboBoostActive = result.response === "on"; - } - updateUi(); - }); - - Cpufreqctl.min.get(backend, (result) => { - if (result.ok && result.exitCode === 0) { - this.minVal = result.response; - } - updateUi(); - }); - - Cpufreqctl.max.get(backend, (result) => { - if (result.ok && result.exitCode === 0) { - this.maxVal = result.response; - } - updateUi(); - }); - - return true; - } - - 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, - }); + getCurFreq() { + if (this.lblUnit) { + return `${(this.cpufreq / 1000).toFixed(2)} GHz`; } else { - log( - `Cpufreqctl signaled unsupported frequency mode ${result.response.mode}! ` + - "Assuming full range..." - ); - cb({ - min: 0, - max: 100, - }); + return `${Math.round(this.cpufreq)} MHz`; } - } - ); - } - - getCurFreq() { - if (this.lblUnit) { - return `${(this.cpufreq / 1000).toFixed(2)} GHz`; - } else { - return `${Math.round(this.cpufreq)} MHz`; } - } - - 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" - ); + + 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; } - return 0; - } }; From 9cbafce5a9f8f0ba05e07057e424e0680829493f Mon Sep 17 00:00:00 2001 From: Gustavo Date: Sat, 25 Mar 2023 21:29:22 -0300 Subject: [PATCH 04/10] add gnome 44 --- metadata.json | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/metadata.json b/metadata.json index 55a5795e..cf18f167 100644 --- a/metadata.json +++ b/metadata.json @@ -1,9 +1,19 @@ { - "localedir": "/usr/local/share/locale", - "shell-version": ["3.28", "3.30", "3.36", "3.38", "40", "41", "42", "43"], - "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": [ + "3.28", + "3.30", + "3.36", + "3.38", + "40", + "41", + "42", + "43", + "44" + ], + "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" } From 71154b38d1b01f6fae1b08bd6cea19c29c867c63 Mon Sep 17 00:00:00 2001 From: Gustavo Freitas Date: Tue, 3 Oct 2023 08:36:48 -0300 Subject: [PATCH 05/10] fix gnome 45 --- deploy.sh | 5 + src/barLevel2.js | 804 ++++++++++++++++++++++++++----------------- src/baseindicator.js | 48 +-- src/indicator.js | 82 ++--- src/prefs40/misc.js | 7 +- src/slider2.js | 416 +++++++++++----------- src/utils.js | 14 +- 7 files changed, 783 insertions(+), 593 deletions(-) create mode 100755 deploy.sh 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/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..b82d068e 100644 --- a/src/baseindicator.js +++ b/src/baseindicator.js @@ -26,20 +26,21 @@ * */ +import * as PanelMenu from "resource:///org/gnome/shell/ui/panelMenu.js"; +import * as Main from "resource:///org/gnome/shell/ui/main.js"; +import * as Util from "resource:///org/gnome/shell/misc/util.js"; +import * as Config from "resource:///org/gnome/shell/misc/config.js"; +import * as PopupMenu from "resource:///org/gnome/shell/ui/popupMenu.js"; + // 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 Gio from "gi://Gio"; +import St from "gi://St"; +import Gio from "gi://Gio"; +import Clutter from "gi://Clutter"; + +//Relative imports -// Relative and misc imports and definitions -const ExtensionUtils = imports.misc.extensionUtils; -const Me = ExtensionUtils.getCurrentExtension(); -const Convenience = Me.imports.src.convenience; -const SETTINGS_ID = "org.gnome.shell.extensions.cpupower"; +import { CpuPowerExtension } from "./../extension.js"; /* exported CPUFreqBaseIndicator */ var CPUFreqBaseIndicator = class CPUFreqBaseIndicator { @@ -47,23 +48,24 @@ var CPUFreqBaseIndicator = class CPUFreqBaseIndicator { this.mainButton = new PanelMenu.Button(null, "cpupower"); this.menu = this.mainButton.menu; - if (parseFloat(Config.PACKAGE_VERSION.substring(0, 4)) > 3.32) { - this.actor = this.mainButton; - } else { - this.actor = this.mainButton.actor; - } - - this.settings = Convenience.getSettings(SETTINGS_ID); - + this.actor = this.mainButton; + ax; + this.settings = new CpuPowerExtension().settings; 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`); + 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` + ); this.icon = new St.Icon({ gicon, style_class: "system-status-icon", }); - this.lbl = new St.Label({text: "", y_expand: true, y_align: Clutter.ActorAlign.CENTER}); + this.lbl = new St.Label({ + text: "", + y_expand: true, + y_align: Clutter.ActorAlign.CENTER, + }); this.arrow = PopupMenu.arrowIcon(St.Side.BOTTOM); this.createIndicator(); diff --git a/src/indicator.js b/src/indicator.js index 0b428a4c..8a0e3cdc 100644 --- a/src/indicator.js +++ b/src/indicator.js @@ -25,30 +25,32 @@ * */ -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 Clutter from "gi://Clutter"; +import GLib from "gi://GLib"; +import Shell from "gi://Shell"; +import St from "gi://St"; +import UPower from "gi://UPowerGlib"; +import Gio from "gi://Gio"; + +import * as PopupMenu from "resource:///org/gnome/shell/ui/popupMenu.js"; +import * as Main from "resource:///org/gnome/shell/ui/main.js"; +import * as Util from "resource:///org/gnome/shell/misc/util.js"; +import * as Config from "resource:///org/gnome/shell/misc/config.js"; +// import Gettext from 'gettext'; +// const _ = Gettext.domain('gnome-shell-extension-cpupower'); + +import { + Extension, + gettext as _, + ngettext, + pgettext, +} from "resource:///org/gnome/shell/extensions/extension.js"; + +import { utils, Cpufreqctl } from "./utils.js"; +import { CPUFreqProfile } from "./profile.js"; +import { CPUFreqProfileButton } from "./profilebutton.js"; +import { Slider } from "./slider2.js"; +import { baseindicator } from "./baseindicator.js"; const LASTSETTINGS = `${GLib.get_user_cache_dir()}/cpupower.last-settings`; @@ -111,14 +113,7 @@ var CPUFreqIndicator = class CPUFreqIndicator extends baseindicator.CPUFreqBaseI } enable() { - const Config = imports.misc.config; - if (parseInt(Config.PACKAGE_VERSION) >= 43) { - this.power = - Main.panel.statusArea.quickSettings._system._systemItem._powerToggle; - } else { - this.power = Main.panel.statusArea["aggregateMenu"]._power; - } - + this.power = Main.panel.statusArea["aggregateMenu"]._power; this.powerState = this.power._proxy.State; this.powerConnectSignalId = this.power._proxy.connect( "g-properties-changed", @@ -129,8 +124,8 @@ var CPUFreqIndicator = class CPUFreqIndicator extends baseindicator.CPUFreqBaseI super.enable(); - this.timeout = Mainloop.timeout_add_seconds(1, () => this.updateFreq()); - this.timeoutMinMax = Mainloop.timeout_add_seconds(1, () => + this.timeout = GLib.timeout_add_seconds(1, () => this.updateFreq()); + this.timeoutMinMax = GLib.timeout_add_seconds(1, () => this.updateFreqMinMax(false) ); } @@ -651,17 +646,14 @@ 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" - ); - } + Util.trySpawnCommandLine( + GLib.uri_resolve_relative( + import.meta.url, + "./src/prefs40/main.js", + GLib.UriFlags.NONE + ) + ); + return 0; } }; diff --git a/src/prefs40/misc.js b/src/prefs40/misc.js index 896019e6..58bc5e5c 100644 --- a/src/prefs40/misc.js +++ b/src/prefs40/misc.js @@ -1,11 +1,14 @@ -const Gio = imports.gi.Gio; +import Gio from "gi://Gio"; /* exported extensionUtils */ var extensionUtils = { getCurrentExtension: () => { return { imports, - dir: Gio.File.new_for_path(imports.system.programPath).get_parent().get_parent().get_parent(), + dir: Gio.File.new_for_path(imports.system.programPath) + .get_parent() + .get_parent() + .get_parent(), }; }, }; 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/utils.js b/src/utils.js index 5a303207..279813d9 100644 --- a/src/utils.js +++ b/src/utils.js @@ -26,16 +26,14 @@ * */ -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 EXTENSIONDIR = Me.dir.get_path(); +const INSTALLER = GLib.uri_resolve_relative(import.meta.url, '/tool/installer.sh', GLib.UriFlags.NONE)); const PKEXEC = GLib.find_program_in_path("pkexec"); -const CONFIG = Me.imports.src.config; +import { CONFIG } from "./src/config.js" // FIXME: I don't know how to call linux's getuid directly... /* exported getuid */ From db709ba5210aac7cd68a40cbb6f6f051008d50c1 Mon Sep 17 00:00:00 2001 From: Gustavo Freitas Date: Tue, 3 Oct 2023 09:41:34 -0300 Subject: [PATCH 06/10] testing --- metadata.json | 12 +- src/config.js | 10 +- src/convenience.js | 20 +- src/notinstalled.js | 65 ++++-- src/preferences.js | 458 +++++++++++++++++++++++++++---------------- src/prefs40/main.js | 18 +- src/prefs40/misc.js | 22 +-- src/profilebutton.js | 36 +++- src/update.js | 46 +++-- 9 files changed, 432 insertions(+), 255 deletions(-) diff --git a/metadata.json b/metadata.json index cf18f167..2b61f8a8 100644 --- a/metadata.json +++ b/metadata.json @@ -1,16 +1,6 @@ { "localedir": "/usr/local/share/locale", - "shell-version": [ - "3.28", - "3.30", - "3.36", - "3.38", - "40", - "41", - "42", - "43", - "44" - ], + "shell-version": ["45"], "uuid": "cpupower@mko-sl.de", "name": "CPU Power Manager", "url": "https://github.com/deinstapel/cpupower", diff --git a/src/config.js b/src/config.js index 09419ba2..dab540e1 100644 --- a/src/config.js +++ b/src/config.js @@ -26,9 +26,13 @@ * */ -const GLib = imports.gi.GLib; -const ExtensionUtils = imports.misc.extensionUtils; -const Me = ExtensionUtils.getCurrentExtension(); +import GLib from "gi://GLib"; +//const ExtensionUtils = imports.misc.extensionUtils; + +import { + ExtensionUtils, + gettext as _, +} from "resource:///org/gnome/Shell/Extensions/js/extensions/prefs.js"; /* exported PREFIX */ var PREFIX = "/usr"; diff --git a/src/convenience.js b/src/convenience.js index e4b260d9..0ac7f076 100644 --- a/src/convenience.js +++ b/src/convenience.js @@ -24,11 +24,13 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -const Gettext = imports.gettext; -const Gio = imports.gi.Gio; +import Gio from "gi://Gio"; -const Config = imports.misc.config; -const ExtensionUtils = imports.misc.extensionUtils; +import Config from "./prefs40/misc"; +import { + ExtensionUtils, + gettext as _, +} from "resource:///org/gnome/Shell/Extensions/js/extensions/prefs.js"; /* exported initTranslations */ /** @@ -82,7 +84,7 @@ function getSettings(schema) { schemaSource = GioSSS.new_from_directory( schemaDir.get_path(), GioSSS.get_default(), - false, + false ); } else { schemaSource = GioSSS.get_default(); @@ -90,9 +92,11 @@ function getSettings(schema) { let schemaObj = schemaSource.lookup(schema, true); if (!schemaObj) { - throw new Error(`Schema ${schema} could not be found for extension ${extension.metadata.uuid}. ` + - "Please check your installation."); + throw new Error( + `Schema ${schema} could not be found for extension ${extension.metadata.uuid}. ` + + "Please check your installation." + ); } - return new Gio.Settings({settings_schema: schemaObj}); + return new Gio.Settings({ settings_schema: schemaObj }); } diff --git a/src/notinstalled.js b/src/notinstalled.js index 9e71852f..01805d67 100644 --- a/src/notinstalled.js +++ b/src/notinstalled.js @@ -27,18 +27,27 @@ */ // Gnome imports -const PopupMenu = imports.ui.popupMenu; +import * as PanelMenu from "resource:///org/gnome/shell/ui/panelMenu.js"; +import * as PopupMenu from "resource:///org/gnome/shell/ui/popupMenu.js"; +import * as Main from "resource:///org/gnome/shell/ui/main.js"; +import * as Util from "resource:///org/gnome/shell/misc/util.js"; +import { + ExtensionUtils, + gettext as _, +} from "resource:///org/gnome/shell/extensions/extension.js"; +import Gtk from "gi://Gtk"; +import Gio from "gi://Gio"; +import GLib from "gi://GLib"; -// 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; +// // Relative and misc imports and definitions +// const ExtensionUtils = imports.misc.extensionUtils; +// const Me = ExtensionUtils.getCurrentExtension(); +import baseindicator from "baseindicator"; +import attemptInstallation from "utils.attemptInstallation"; +import utils from "utils"; -const Gettext = imports.gettext.domain("gnome-shell-extension-cpupower"); -const _ = Gettext.gettext; +// const Gettext = imports.gettext.domain("gnome-shell-extension-cpupower"); +// const _ = Gettext.gettext; /* exported NotInstalledIndicator */ var NotInstalledIndicator = class NotInstalledIndicator extends baseindicator.CPUFreqBaseIndicator { @@ -57,21 +66,31 @@ var NotInstalledIndicator = class NotInstalledIndicator extends baseindicator.CP super.createMenu(); if (this.exitCode === utils.INSTALLER_NOT_INSTALLED) { - let notInstalledLabel = new PopupMenu.PopupMenuItem(_("Installation required."), {reactive: false}); + let notInstalledLabel = new PopupMenu.PopupMenuItem( + _("Installation required."), + { reactive: false } + ); this.mainSection.addMenuItem(notInstalledLabel); } else { let errorLabel = new PopupMenu.PopupMenuItem( - _("Oh no! This should not have happened.\n" + - "An error occurred while checking the installation!"), - {reactive: false}, + _( + "Oh no! This should not have happened.\n" + + "An error occurred while checking the installation!" + ), + { reactive: false } ); 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(errorLabel); this.mainSection.addMenuItem(reportLabel); @@ -80,8 +99,14 @@ var NotInstalledIndicator = class NotInstalledIndicator extends baseindicator.CP let separator = new PopupMenu.PopupSeparatorMenuItem(); this.mainSection.addMenuItem(separator); - this.attemptInstallationLabel = new PopupMenu.PopupMenuItem(_("Attempt installation"), {reactive: true}); - this.attemptInstallationLabel.connect("activate", attemptInstallation.bind(null, this.done)); + this.attemptInstallationLabel = new PopupMenu.PopupMenuItem( + _("Attempt installation"), + { reactive: true } + ); + this.attemptInstallationLabel.connect( + "activate", + attemptInstallation.bind(null, this.done) + ); this.mainSection.addMenuItem(this.attemptInstallationLabel); } }; diff --git a/src/preferences.js b/src/preferences.js index a3df8236..7eadd42d 100644 --- a/src/preferences.js +++ b/src/preferences.js @@ -26,23 +26,35 @@ * */ -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 * as PanelMenu from "resource:///org/gnome/shell/ui/panelMenu.js"; +import * as PopupMenu from "resource:///org/gnome/shell/ui/popupMenu.js"; +import * as Main from "resource:///org/gnome/shell/ui/main.js"; +import * as Util from "resource:///org/gnome/shell/misc/util.js"; +import { + Extension, + gettext as _, +} from "resource:///org/gnome/shell/extensions/extension.js"; +import Gtk from "gi://Gtk"; +import Gio from "gi://Gio"; +import GLib from "gi://GLib"; + +// 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(); +import Convenience from "convenience"; +import CPUFreqProfile from "profile.CPUFreqProfile"; +import * as CONFIG from "config"; +import attemptUninstallation from "utils.attemptUninstallation"; +import Cpufreqctl from "utils.Cpufreqctl"; + +const EXTENSIONDIR = dir.get_path(); const GLADE_FILE = `${EXTENSIONDIR}/data/cpupower-preferences.glade`; const SETTINGS_SCHEMA = "org.gnome.shell.extensions.cpupower"; @@ -57,18 +69,21 @@ var CPUPowerPreferences = class CPUPowerPreferences { Gio.BusNameOwnerFlags.NONE, this.onBusAcquired.bind(this), this.onNameAcquired.bind(this), - this.onNameLost.bind(this), + this.onNameLost.bind(this) ); this.Builder = new Gtk.Builder(); this.Builder.set_translation_domain("gnome-shell-extension-cpupower"); - this.Builder.add_objects_from_file( - GLADE_FILE, - ["MainWidget", "AboutButton", "FrequencyScalingDriverListStore"], + this.Builder.add_objects_from_file(GLADE_FILE, [ + "MainWidget", + "AboutButton", + "FrequencyScalingDriverListStore", + ]); + this.Builder.connect_signals_full( + (builder, object, signal, handler) => { + object.connect(signal, this[handler].bind(this)); + } ); - this.Builder.connect_signals_full((builder, object, signal, handler) => { - object.connect(signal, this[handler].bind(this)); - }); this.loadWidgets( "MainWidget", "AboutButton", @@ -90,22 +105,30 @@ var CPUPowerPreferences = class CPUPowerPreferences { "CpufreqctlPathLabel", "PolicykitRulePathLabel", "InstallationWarningLabel", - "UninstallButton", + "UninstallButton" ); this.ProfilesMap = new Map(); } onBusAcquired(connection, _name) { log("DBus bus acquired!"); - const interfaceBinary = GLib.file_get_contents(`${EXTENSIONDIR}/schemas/io.github.martin31821.cpupower.dbus.xml`)[1]; + 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(); } - this.cpupowerService = Gio.DBusExportedObject.wrapJSObject(interfaceXml, {}); - this.cpupowerService.export(connection, "/io/github/martin31821/cpupower"); + this.cpupowerService = Gio.DBusExportedObject.wrapJSObject( + interfaceXml, + {} + ); + this.cpupowerService.export( + connection, + "/io/github/martin31821/cpupower" + ); // do not set connection in 'this' here, as we use it to check if name is // acquired @@ -126,30 +149,39 @@ var CPUPowerPreferences = class CPUPowerPreferences { } 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, - }); + 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, + }); + } } - }); + ); } updateSettings(done) { @@ -260,7 +292,11 @@ var CPUPowerPreferences = class CPUPowerPreferences { syncOrdering() { for (let profileContext of this.ProfilesMap.values()) { let index = profileContext.ListItem.Row.get_index(); - this.ProfileStack.child_set_property(profileContext.Settings.StackItem, "position", index); + this.ProfileStack.child_set_property( + profileContext.Settings.StackItem, + "position", + index + ); } } @@ -323,93 +359,102 @@ var CPUPowerPreferences = class CPUPowerPreferences { }; let profileSettingsBuilder = new Gtk.Builder(); - profileSettingsBuilder.set_translation_domain("gnome-shell-extension-cpupower"); - profileSettingsBuilder.add_objects_from_file( - GLADE_FILE, - [ - "ProfileSettingsGrid", - "MaximumFrequencyAdjustment", - "MinimumFrequencyAdjustment", - ], - ); - profileContext.Settings.NameEntry = profileSettingsBuilder.get_object( - "ProfileNameEntry", - ); - profileContext.Settings.MinimumFrequencyScale = profileSettingsBuilder.get_object( - "ProfileMinimumFrequencyScale", - ); - profileContext.Settings.MaximumFrequencyScale = profileSettingsBuilder.get_object( - "ProfileMaximumFrequencyScale", - ); - profileContext.Settings.TurboBoostSwitch = profileSettingsBuilder.get_object( - "ProfileTurboBoostSwitch", + profileSettingsBuilder.set_translation_domain( + "gnome-shell-extension-cpupower" ); - profileContext.Settings.DiscardButton = profileSettingsBuilder.get_object( - "ProfileDiscardButton", - ); - profileContext.Settings.SaveButton = profileSettingsBuilder.get_object( - "ProfileSaveButton", - ); - profileContext.Settings.StackItem = profileSettingsBuilder.get_object( + profileSettingsBuilder.add_objects_from_file(GLADE_FILE, [ "ProfileSettingsGrid", - ); - profileContext.Settings.CpuInfoGrid = profileSettingsBuilder.get_object( - "ProfileInfoGrid", - ); - profileContext.Settings.LimitMinLabel = profileSettingsBuilder.get_object( - "ProfileLimitMinLabel", - ); - profileContext.Settings.LimitMaxLabel = profileSettingsBuilder.get_object( - "ProfileLimitMaxLabel", - ); - profileContext.Settings.MinimumFrequencyAdjustment = profileSettingsBuilder.get_object( - "MinimumFrequencyAdjustment", - ); - profileContext.Settings.MaximumFrequencyAdjustment = profileSettingsBuilder.get_object( "MaximumFrequencyAdjustment", - ); - profileContext.Settings.MinimumFrequencyValueLabel = profileSettingsBuilder.get_object( - "ProfileMinimumFrequencyValueLabel", - ); - profileContext.Settings.MaximumFrequencyValueLabel = profileSettingsBuilder.get_object( - "ProfileMaximumFrequencyValueLabel", - ); + "MinimumFrequencyAdjustment", + ]); + profileContext.Settings.NameEntry = + profileSettingsBuilder.get_object("ProfileNameEntry"); + profileContext.Settings.MinimumFrequencyScale = + profileSettingsBuilder.get_object( + "ProfileMinimumFrequencyScale" + ); + profileContext.Settings.MaximumFrequencyScale = + profileSettingsBuilder.get_object( + "ProfileMaximumFrequencyScale" + ); + profileContext.Settings.TurboBoostSwitch = + profileSettingsBuilder.get_object("ProfileTurboBoostSwitch"); + profileContext.Settings.DiscardButton = + profileSettingsBuilder.get_object("ProfileDiscardButton"); + profileContext.Settings.SaveButton = + profileSettingsBuilder.get_object("ProfileSaveButton"); + profileContext.Settings.StackItem = + profileSettingsBuilder.get_object("ProfileSettingsGrid"); + profileContext.Settings.CpuInfoGrid = + profileSettingsBuilder.get_object("ProfileInfoGrid"); + profileContext.Settings.LimitMinLabel = + profileSettingsBuilder.get_object("ProfileLimitMinLabel"); + profileContext.Settings.LimitMaxLabel = + profileSettingsBuilder.get_object("ProfileLimitMaxLabel"); + profileContext.Settings.MinimumFrequencyAdjustment = + profileSettingsBuilder.get_object("MinimumFrequencyAdjustment"); + profileContext.Settings.MaximumFrequencyAdjustment = + profileSettingsBuilder.get_object("MaximumFrequencyAdjustment"); + profileContext.Settings.MinimumFrequencyValueLabel = + profileSettingsBuilder.get_object( + "ProfileMinimumFrequencyValueLabel" + ); + profileContext.Settings.MaximumFrequencyValueLabel = + profileSettingsBuilder.get_object( + "ProfileMaximumFrequencyValueLabel" + ); let profileListItemBuilder = new Gtk.Builder(); - profileListItemBuilder.set_translation_domain("gnome-shell-extension-cpupower"); - profileListItemBuilder.add_objects_from_file(GLADE_FILE, ["ProfileListBoxRow"]); - profileContext.ListItem.NameLabel = profileListItemBuilder.get_object( - "ProfileRowNameLabel", - ); - profileContext.ListItem.MinimumFrequencyLabel = profileListItemBuilder.get_object( - "ProfileRowMinimumFrequencyLabel", + profileListItemBuilder.set_translation_domain( + "gnome-shell-extension-cpupower" ); - profileContext.ListItem.MaximumFrequencyLabel = profileListItemBuilder.get_object( - "ProfileRowMaximumFrequencyLabel", - ); - profileContext.ListItem.TurboBoostStatusLabel = profileListItemBuilder.get_object( - "ProfileRowTurboBoostStatusLabel", - ); - profileContext.ListItem.AutoSwitchACIcon = profileListItemBuilder.get_object( - "ProfileRowACIcon", - ); - profileContext.ListItem.AutoSwitchBatIcon = profileListItemBuilder.get_object( - "ProfileRowBatIcon", - ); - profileContext.ListItem.Row = profileListItemBuilder.get_object( + profileListItemBuilder.add_objects_from_file(GLADE_FILE, [ "ProfileListBoxRow", + ]); + profileContext.ListItem.NameLabel = + profileListItemBuilder.get_object("ProfileRowNameLabel"); + profileContext.ListItem.MinimumFrequencyLabel = + profileListItemBuilder.get_object( + "ProfileRowMinimumFrequencyLabel" + ); + profileContext.ListItem.MaximumFrequencyLabel = + profileListItemBuilder.get_object( + "ProfileRowMaximumFrequencyLabel" + ); + profileContext.ListItem.TurboBoostStatusLabel = + profileListItemBuilder.get_object( + "ProfileRowTurboBoostStatusLabel" + ); + profileContext.ListItem.AutoSwitchACIcon = + profileListItemBuilder.get_object("ProfileRowACIcon"); + profileContext.ListItem.AutoSwitchBatIcon = + profileListItemBuilder.get_object("ProfileRowBatIcon"); + profileContext.ListItem.Row = + profileListItemBuilder.get_object("ProfileListBoxRow"); + + profileSettingsBuilder.connect_signals_full( + (builder, object, signal, handler) => { + object.connect( + signal, + this[handler].bind(this, profileContext) + ); + } ); - profileSettingsBuilder.connect_signals_full((builder, object, signal, handler) => { - object.connect(signal, this[handler].bind(this, profileContext)); - }); - - profileListItemBuilder.connect_signals_full((builder, object, signal, handler) => { - object.connect(signal, this[handler].bind(this, profileContext)); - }); + profileListItemBuilder.connect_signals_full( + (builder, object, signal, handler) => { + object.connect( + signal, + this[handler].bind(this, profileContext) + ); + } + ); this.ProfilesListBox.prepend(profileContext.ListItem.Row); - this.ProfileStack.add_named(profileContext.Settings.StackItem, profileContext.Profile.UUID.toString(16)); + this.ProfileStack.add_named( + profileContext.Settings.StackItem, + profileContext.Profile.UUID.toString(16) + ); this.ProfilesMap.set(profileContext.Profile.UUID, profileContext); this.syncOrdering(); } else { @@ -422,34 +467,60 @@ var CPUPowerPreferences = class CPUPowerPreferences { profileContext.Settings.LimitMaxLabel.set_text(`${this.cpuMaxLimit}%`); // modify adjustments - profileContext.Settings.MinimumFrequencyAdjustment.set_lower(this.cpuMinLimit); - profileContext.Settings.MinimumFrequencyAdjustment.set_upper(profileContext.Profile.MaximumFrequency); - profileContext.Settings.MaximumFrequencyAdjustment.set_lower(profileContext.Profile.MinimumFrequency); - profileContext.Settings.MaximumFrequencyAdjustment.set_upper(this.cpuMaxLimit); + profileContext.Settings.MinimumFrequencyAdjustment.set_lower( + this.cpuMinLimit + ); + profileContext.Settings.MinimumFrequencyAdjustment.set_upper( + profileContext.Profile.MaximumFrequency + ); + profileContext.Settings.MaximumFrequencyAdjustment.set_lower( + profileContext.Profile.MinimumFrequency + ); + profileContext.Settings.MaximumFrequencyAdjustment.set_upper( + this.cpuMaxLimit + ); - profileContext.Settings.MinimumFrequencyScale.set_value(profileContext.Profile.MinimumFrequency); - profileContext.Settings.MaximumFrequencyScale.set_value(profileContext.Profile.MaximumFrequency); + profileContext.Settings.MinimumFrequencyScale.set_value( + profileContext.Profile.MinimumFrequency + ); + profileContext.Settings.MaximumFrequencyScale.set_value( + profileContext.Profile.MaximumFrequency + ); profileContext.Settings.MinimumFrequencyValueLabel.set_text( - `${profileContext.Profile.MinimumFrequency}%`, + `${profileContext.Profile.MinimumFrequency}%` ); profileContext.Settings.MaximumFrequencyValueLabel.set_text( - `${profileContext.Profile.MaximumFrequency}%`, + `${profileContext.Profile.MaximumFrequency}%` ); profileContext.Settings.NameEntry.set_text(profileContext.Profile.Name); - profileContext.Settings.TurboBoostSwitch.set_active(profileContext.Profile.TurboBoost); + profileContext.Settings.TurboBoostSwitch.set_active( + profileContext.Profile.TurboBoost + ); profileContext.ListItem.NameLabel.set_text(profileContext.Profile.Name); - profileContext.ListItem.MinimumFrequencyLabel.set_text(profileContext.Profile.MinimumFrequency.toString()); - profileContext.ListItem.MaximumFrequencyLabel.set_text(profileContext.Profile.MaximumFrequency.toString()); - profileContext.ListItem.TurboBoostStatusLabel.set_text(profileContext.Profile.TurboBoost ? _("Yes") : _("No")); + profileContext.ListItem.MinimumFrequencyLabel.set_text( + profileContext.Profile.MinimumFrequency.toString() + ); + profileContext.ListItem.MaximumFrequencyLabel.set_text( + profileContext.Profile.MaximumFrequency.toString() + ); + profileContext.ListItem.TurboBoostStatusLabel.set_text( + profileContext.Profile.TurboBoost ? _("Yes") : _("No") + ); - if (this.settings.get_string("default-ac-profile") === profileContext.Profile.UUID) { + if ( + this.settings.get_string("default-ac-profile") === + profileContext.Profile.UUID + ) { profileContext.ListItem.AutoSwitchACIcon.set_visible(true); } else { profileContext.ListItem.AutoSwitchACIcon.set_visible(false); } - if (this.settings.get_string("default-battery-profile") === profileContext.Profile.UUID) { + if ( + this.settings.get_string("default-battery-profile") === + profileContext.Profile.UUID + ) { profileContext.ListItem.AutoSwitchBatIcon.set_visible(true); } else { profileContext.ListItem.AutoSwitchBatIcon.set_visible(false); @@ -469,10 +540,16 @@ var CPUPowerPreferences = class CPUPowerPreferences { let profileContext = this.ProfilesMap.get(profile.UUID); // set default profile to none if the removed profile was selected - if (this.DefaultACComboBox.get_active_id() === profileContext.Profile.UUID) { + if ( + this.DefaultACComboBox.get_active_id() === + profileContext.Profile.UUID + ) { this.settings.set_string("default-ac-profile", ""); } - if (this.DefaultBatComboBox.get_active_id() === profileContext.Profile.UUID) { + if ( + this.DefaultBatComboBox.get_active_id() === + profileContext.Profile.UUID + ) { this.settings.set_string("default-battery-profile", ""); } @@ -527,7 +604,11 @@ var CPUPowerPreferences = class CPUPowerPreferences { this.DefaultBatComboBox.append("", _("None")); let profileArray = Array.from(this.ProfilesMap.values()); - profileArray.sort((p1, p2) => this.getProfileIndex(p1.Profile) - this.getProfileIndex(p2.Profile)); + profileArray.sort( + (p1, p2) => + this.getProfileIndex(p1.Profile) - + this.getProfileIndex(p2.Profile) + ); for (let i in profileArray) { let profile = profileArray[i].Profile; @@ -556,7 +637,7 @@ var CPUPowerPreferences = class CPUPowerPreferences { liststore.set( iter, [0, 1, 2], - [`${_("Automatic")} (${chosenBackend})`, "automatic", true], + [`${_("Automatic")} (${chosenBackend})`, "automatic", true] ); Cpufreqctl.backends.list(backend, (result) => { if (!result.ok) { @@ -568,7 +649,7 @@ var CPUPowerPreferences = class CPUPowerPreferences { liststore.set( iter, [0, 1, 2], - [backend, backend, supported], + [backend, backend, supported] ); } combobox.set_active_id(backend); @@ -628,8 +709,10 @@ var CPUPowerPreferences = class CPUPowerPreferences { if (oldBackend !== state) { Cpufreqctl.reset(oldBackend, (result) => { if (!result.ok) { - this.status(`Failed to reset frequency scaling driver of old backend ${oldBackend}: ` + - `${Cpufreqctl.exitCodeToString(result.exitCode)}`); + this.status( + `Failed to reset frequency scaling driver of old backend ${oldBackend}: ` + + `${Cpufreqctl.exitCodeToString(result.exitCode)}` + ); } }); } @@ -692,11 +775,21 @@ var CPUPowerPreferences = class CPUPowerPreferences { onUninstallButtonClicked(_button) { let uninstallDialogBuilder = new Gtk.Builder(); - uninstallDialogBuilder.set_translation_domain("gnome-shell-extension-cpupower"); - uninstallDialogBuilder.add_objects_from_file(GLADE_FILE, ["UninstallMessageDialog"]); - let dialog = uninstallDialogBuilder.get_object("UninstallMessageDialog"); - let uninstallButton = uninstallDialogBuilder.get_object("UninstallDialogUninstall"); - let cancelButton = uninstallDialogBuilder.get_object("UninstallDialogCancel"); + uninstallDialogBuilder.set_translation_domain( + "gnome-shell-extension-cpupower" + ); + uninstallDialogBuilder.add_objects_from_file(GLADE_FILE, [ + "UninstallMessageDialog", + ]); + let dialog = uninstallDialogBuilder.get_object( + "UninstallMessageDialog" + ); + let uninstallButton = uninstallDialogBuilder.get_object( + "UninstallDialogUninstall" + ); + let cancelButton = uninstallDialogBuilder.get_object( + "UninstallDialogCancel" + ); let parentWindow = this.MainWidget.get_toplevel(); dialog.set_transient_for(parentWindow); @@ -706,11 +799,16 @@ var CPUPowerPreferences = class CPUPowerPreferences { if (this.cpupowerConnection) { log("reloading extension"); - let result = this.cpupowerService.emit_signal("ExtensionReloadRequired", null); + let result = this.cpupowerService.emit_signal( + "ExtensionReloadRequired", + null + ); log(`emit signal result: ${result}`); } else { // hmm... extension seems not to be running, so who cares? - log("Could not trigger extension reload as dbus connection is offline!"); + log( + "Could not trigger extension reload as dbus connection is offline!" + ); } GLib.timeout_add(GLib.PRIORITY_DEFAULT, 0, () => { @@ -727,8 +825,12 @@ var CPUPowerPreferences = class CPUPowerPreferences { } showCpuLimitInfo(profileContext) { - if (profileContext.Settings.MinimumFrequencyScale.get_value() === this.cpuMinLimit || - profileContext.Settings.MaximumFrequencyScale.get_value() === this.cpuMaxLimit) { + if ( + profileContext.Settings.MinimumFrequencyScale.get_value() === + this.cpuMinLimit || + profileContext.Settings.MaximumFrequencyScale.get_value() === + this.cpuMaxLimit + ) { profileContext.Settings.CpuInfoGrid.set_visible(true); } else { profileContext.Settings.CpuInfoGrid.set_visible(false); @@ -738,7 +840,9 @@ var CPUPowerPreferences = class CPUPowerPreferences { onProfilesListBoxRowSelected(_box, _row) { let profileContext = this.getSelectedProfileContext(); if (profileContext) { - this.ProfileStack.set_visible_child(profileContext.Settings.StackItem); + this.ProfileStack.set_visible_child( + profileContext.Settings.StackItem + ); } } @@ -758,13 +862,18 @@ var CPUPowerPreferences = class CPUPowerPreferences { } onProfileMinimumFrequencyScaleValueChanged(profileContext, scale) { - let changed = profileContext.Profile.MinimumFrequency !== scale.get_value(); + let changed = + profileContext.Profile.MinimumFrequency !== scale.get_value(); if (changed) { profileContext.Settings.DiscardButton.sensitive = true; profileContext.Settings.SaveButton.sensitive = true; - profileContext.Settings.MaximumFrequencyAdjustment.set_lower(scale.get_value()); - profileContext.Settings.MinimumFrequencyValueLabel.set_text(`${scale.get_value()}%`); + profileContext.Settings.MaximumFrequencyAdjustment.set_lower( + scale.get_value() + ); + profileContext.Settings.MinimumFrequencyValueLabel.set_text( + `${scale.get_value()}%` + ); this.showCpuLimitInfo(profileContext); @@ -777,13 +886,18 @@ var CPUPowerPreferences = class CPUPowerPreferences { } onProfileMaximumFrequencyScaleValueChanged(profileContext, scale) { - let changed = profileContext.Profile.MaximumFrequency !== scale.get_value(); + let changed = + profileContext.Profile.MaximumFrequency !== scale.get_value(); if (changed) { profileContext.Settings.DiscardButton.sensitive = true; profileContext.Settings.SaveButton.sensitive = true; - profileContext.Settings.MinimumFrequencyAdjustment.set_upper(scale.get_value()); - profileContext.Settings.MaximumFrequencyValueLabel.set_text(`${scale.get_value()}%`); + profileContext.Settings.MinimumFrequencyAdjustment.set_upper( + scale.get_value() + ); + profileContext.Settings.MaximumFrequencyValueLabel.set_text( + `${scale.get_value()}%` + ); this.showCpuLimitInfo(profileContext); @@ -796,7 +910,8 @@ var CPUPowerPreferences = class CPUPowerPreferences { } onProfileTurboBoostSwitchActiveNotify(profileContext, switchButton) { - let changed = profileContext.Profile.TurboBoost !== switchButton.get_active(); + let changed = + profileContext.Profile.TurboBoost !== switchButton.get_active(); if (changed) { profileContext.Settings.DiscardButton.sensitive = true; @@ -816,8 +931,10 @@ var CPUPowerPreferences = class CPUPowerPreferences { onProfileSaveButtonClicked(profileContext, _button) { let name = profileContext.Settings.NameEntry.get_text(); - let minimumFrequency = profileContext.Settings.MinimumFrequencyScale.get_value(); - let maximumFrequency = profileContext.Settings.MaximumFrequencyScale.get_value(); + let minimumFrequency = + profileContext.Settings.MinimumFrequencyScale.get_value(); + let maximumFrequency = + profileContext.Settings.MaximumFrequencyScale.get_value(); let turboBoost = profileContext.Settings.TurboBoostSwitch.get_active(); profileContext.Profile.Name = name; @@ -833,7 +950,10 @@ var CPUPowerPreferences = class CPUPowerPreferences { let saved = []; for (let value of this.ProfilesMap.entries()) { this.status(`value: ${value[0]}${value[1]}`); - let idx = this.ProfilesMap.size - 1 - this.getProfileIndex(value[1].Profile); + let idx = + this.ProfilesMap.size - + 1 - + this.getProfileIndex(value[1].Profile); this.status(`Saving: ${value[1].Profile.UUID} to idx ${idx}`); saved[idx] = value[1].Profile.save(); } 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 58bc5e5c..491e882d 100644 --- a/src/prefs40/misc.js +++ b/src/prefs40/misc.js @@ -1,19 +1,15 @@ 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/profilebutton.js b/src/profilebutton.js index 0910d283..1800b215 100644 --- a/src/profilebutton.js +++ b/src/profilebutton.js @@ -25,11 +25,20 @@ * */ -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 * as PanelMenu from "resource:///org/gnome/shell/ui/panelMenu.js"; +import * as PopupMenu from "resource:///org/gnome/shell/ui/popupMenu.js"; +import * as Main from "resource:///org/gnome/shell/ui/main.js"; +import * as Util from "resource:///org/gnome/shell/misc/util.js"; +import { + Extension, + gettext as _, +} from "resource:///org/gnome/shell/extensions/extension.js"; +import GObject from "gi://GObject"; + +import Config from "./prefs40/misc"; + +// const Gettext = imports.gettext.domain("gnome-shell-extension-cpupower"); +// const _ = Gettext.gettext; const DEFAULT_EMPTY_NAME = "No name"; @@ -38,17 +47,24 @@ var CPUFreqProfileButton; // 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 { + CPUFreqProfileButton = class CPUFreqProfileButton extends ( + PopupMenu.PopupMenuItem + ) { _init(profile) { - super._init(profile.Name || DEFAULT_EMPTY_NAME, {reactive: true}); + super._init(profile.Name || DEFAULT_EMPTY_NAME, { reactive: true }); this.Profile = profile; } }; - CPUFreqProfileButton = GObject.registerClass({GTypeName: "CPUFreqProfileButton"}, CPUFreqProfileButton); + CPUFreqProfileButton = GObject.registerClass( + { GTypeName: "CPUFreqProfileButton" }, + CPUFreqProfileButton + ); } else { - CPUFreqProfileButton = class CPUFreqProfileButton extends PopupMenu.PopupMenuItem { + CPUFreqProfileButton = class CPUFreqProfileButton extends ( + PopupMenu.PopupMenuItem + ) { constructor(profile) { - super(_(profile.Name || DEFAULT_EMPTY_NAME), {reactive: true}); + super(_(profile.Name || DEFAULT_EMPTY_NAME), { reactive: true }); this.Profile = profile; } }; diff --git a/src/update.js b/src/update.js index 9467a72a..e4a36c89 100644 --- a/src/update.js +++ b/src/update.js @@ -27,16 +27,24 @@ */ // Gnome imports -const PopupMenu = imports.ui.popupMenu; +import * as PanelMenu from "resource:///org/gnome/shell/ui/panelMenu.js"; +import * as PopupMenu from "resource:///org/gnome/shell/ui/popupMenu.js"; +import * as Main from "resource:///org/gnome/shell/ui/main.js"; +import * as Util from "resource:///org/gnome/shell/misc/util.js"; +import { + Extension, + gettext as _, +} from "resource:///org/gnome/shell/extensions/extension.js"; +import GObject from "gi://GObject"; // 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 ExtensionUtils = imports.misc.extensionUtils; +// const Me = ExtensionUtils.getCurrentExtension(); +import baseindicator from "./baseindicator"; +import attemptUpdate from "./utils.attemptUpdate"; -const Gettext = imports.gettext.domain("gnome-shell-extension-cpupower"); -const _ = Gettext.gettext; +// const Gettext = imports.gettext.domain("gnome-shell-extension-cpupower"); +// const _ = Gettext.gettext; /* eslint no-unused-vars: "off" */ const UPDATE = 1; @@ -58,22 +66,34 @@ var UpdateIndicator = class UpdateIndicator extends baseindicator.CPUFreqBaseInd createMenu() { super.createMenu(); - let updateText = _("Your CPU Power Manager installation needs updating!"); - let securityText = _("Warning: Security issues were found with your installation!\n" + - "Please update immediately!"); + let updateText = _( + "Your CPU Power Manager installation needs updating!" + ); + let securityText = _( + "Warning: Security issues were found with your installation!\n" + + "Please update immediately!" + ); if (this.updateType === SECURITY_UPDATE) { updateText += "\n"; updateText += securityText; } - let updateLabel = new PopupMenu.PopupMenuItem(updateText, {reactive: false}); + let updateLabel = new PopupMenu.PopupMenuItem(updateText, { + reactive: false, + }); this.mainSection.addMenuItem(updateLabel); let separator = new PopupMenu.PopupSeparatorMenuItem(); this.mainSection.addMenuItem(separator); - this.attemptUpdateLabel = new PopupMenu.PopupMenuItem(_("Attempt tool update"), {reactive: true}); - this.attemptUpdateLabel.connect("activate", attemptUpdate.bind(null, this.done)); + this.attemptUpdateLabel = new PopupMenu.PopupMenuItem( + _("Attempt tool update"), + { reactive: true } + ); + this.attemptUpdateLabel.connect( + "activate", + attemptUpdate.bind(null, this.done) + ); this.mainSection.addMenuItem(this.attemptUpdateLabel); } }; From 899a522527ec882efab1232dc023e2bbe7e2082d Mon Sep 17 00:00:00 2001 From: Gustavo Date: Fri, 17 Nov 2023 09:58:21 -0300 Subject: [PATCH 07/10] merge from NicolasDerumigny branch --- .Rhistory | 0 .gitignore | 1 + .tern-project | 13 + README.md | 8 +- data/cpupower-preferences.glade | 2 +- .../SPECS/gnome-shell-extension-cpupower.spec | 4 - extension.js | 179 ++++--- metadata.json | 17 +- prefs.js | 49 +- src/baseindicator.js | 49 +- src/config.js | 20 +- src/convenience.js | 49 +- src/indicator.js | 96 ++-- src/notinstalled.js | 61 +-- src/preferences.js | 464 +++++++----------- src/profile.js | 3 +- src/profilebutton.js | 49 +- src/update.js | 44 +- src/utils.js | 52 +- test.sh | 9 + tool/cpufreqctl | 98 ++-- 21 files changed, 496 insertions(+), 771 deletions(-) create mode 100644 .Rhistory create mode 100644 .tern-project create mode 100755 test.sh 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/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 2b61f8a8..4688132c 100644 --- a/metadata.json +++ b/metadata.json @@ -1,9 +1,12 @@ { - "localedir": "/usr/local/share/locale", - "shell-version": ["45"], - "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" + ], + "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/baseindicator.js b/src/baseindicator.js index b82d068e..52a5c6ec 100644 --- a/src/baseindicator.js +++ b/src/baseindicator.js @@ -26,46 +26,43 @@ * */ -import * as PanelMenu from "resource:///org/gnome/shell/ui/panelMenu.js"; -import * as Main from "resource:///org/gnome/shell/ui/main.js"; -import * as Util from "resource:///org/gnome/shell/misc/util.js"; -import * as Config from "resource:///org/gnome/shell/misc/config.js"; -import * as PopupMenu from "resource:///org/gnome/shell/ui/popupMenu.js"; - // Gnome imports -import Gio from "gi://Gio"; -import St from "gi://St"; -import Gio from "gi://Gio"; -import Clutter from "gi://Clutter"; - -//Relative imports +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'; -import { CpuPowerExtension } from "./../extension.js"; +// Relative and misc imports and definitions +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; - this.actor = this.mainButton; - ax; - this.settings = new CpuPowerExtension().settings; + if (parseFloat(Config.PACKAGE_VERSION.substring(0, 4)) > 3.32) { + this.actor = this.mainButton; + } else { + this.actor = this.mainButton.actor; + } + + this.settings = Convenience.getSettings(SETTINGS_ID); + 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` - ); + this.hbox = new St.BoxLayout({style_class: "panel-status-menu-box"}); + let gicon = Gio.icon_new_for_string(EXTENSIONDIR + '/data/icons/cpu-symbolic.svg'); this.icon = new St.Icon({ gicon, style_class: "system-status-icon", }); - this.lbl = new St.Label({ - text: "", - y_expand: true, - y_align: Clutter.ActorAlign.CENTER, - }); + this.lbl = new St.Label({text: "", y_expand: true, y_align: Clutter.ActorAlign.CENTER}); this.arrow = PopupMenu.arrowIcon(St.Side.BOTTOM); this.createIndicator(); diff --git a/src/config.js b/src/config.js index dab540e1..6586f1ee 100644 --- a/src/config.js +++ b/src/config.js @@ -26,27 +26,21 @@ * */ -import GLib from "gi://GLib"; -//const ExtensionUtils = imports.misc.extensionUtils; - -import { - ExtensionUtils, - gettext as _, -} from "resource:///org/gnome/Shell/Extensions/js/extensions/prefs.js"; +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 0ac7f076..11080503 100644 --- a/src/convenience.js +++ b/src/convenience.js @@ -24,38 +24,9 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -import Gio from "gi://Gio"; - -import Config from "./prefs40/misc"; -import { - ExtensionUtils, - gettext as _, -} from "resource:///org/gnome/Shell/Extensions/js/extensions/prefs.js"; - -/* 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 */ /** @@ -66,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"]; @@ -84,7 +55,7 @@ function getSettings(schema) { schemaSource = GioSSS.new_from_directory( schemaDir.get_path(), GioSSS.get_default(), - false + false, ); } else { schemaSource = GioSSS.get_default(); @@ -92,11 +63,9 @@ function getSettings(schema) { let schemaObj = schemaSource.lookup(schema, true); if (!schemaObj) { - throw new Error( - `Schema ${schema} could not be found for extension ${extension.metadata.uuid}. ` + - "Please check your installation." - ); + throw new Error(`Schema ${schema} could not be found for extension ${extension.metadata.uuid}. ` + + "Please check your installation."); } - return new Gio.Settings({ settings_schema: schemaObj }); + return new Gio.Settings({settings_schema: schemaObj}); } diff --git a/src/indicator.js b/src/indicator.js index 8a0e3cdc..3502fa16 100644 --- a/src/indicator.js +++ b/src/indicator.js @@ -25,37 +25,37 @@ * */ -import Clutter from "gi://Clutter"; +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 St from "gi://St"; import UPower from "gi://UPowerGlib"; -import Gio from "gi://Gio"; -import * as PopupMenu from "resource:///org/gnome/shell/ui/popupMenu.js"; 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 Gettext from 'gettext'; -// const _ = Gettext.domain('gnome-shell-extension-cpupower'); - import { Extension, gettext as _, - ngettext, - pgettext, } from "resource:///org/gnome/shell/extensions/extension.js"; -import { utils, Cpufreqctl } from "./utils.js"; +import * as utils from "./utils.js"; +import * as baseindicator from "./baseindicator.js"; import { CPUFreqProfile } from "./profile.js"; import { CPUFreqProfileButton } from "./profilebutton.js"; -import { Slider } from "./slider2.js"; -import { baseindicator } from "./baseindicator.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; @@ -113,7 +113,8 @@ 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", @@ -124,9 +125,13 @@ var CPUFreqIndicator = class CPUFreqIndicator extends baseindicator.CPUFreqBaseI super.enable(); - this.timeout = GLib.timeout_add_seconds(1, () => this.updateFreq()); - this.timeoutMinMax = GLib.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) ); } @@ -283,7 +288,7 @@ var CPUFreqIndicator = class CPUFreqIndicator extends baseindicator.CPUFreqBaseI }); this.imSliderMin = new PopupMenu.PopupBaseMenuItem({ activate: false }); - this.minSlider = new Slider.Slider2(this.minVal); + this.minSlider = new Slider.Slider(this.minVal); this.minSlider.x_expand = true; this.minSlider.maximum_value = 100; this.minSlider.overdrive_start = 100; @@ -300,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.imSliderMin.add_child(this.minSlider); this.imSliderMax = new PopupMenu.PopupBaseMenuItem({ activate: false }); - this.maxSlider = new Slider.Slider2(this.maxVal); + this.maxSlider = new Slider.Slider(this.maxVal); this.maxSlider.x_expand = true; this.maxSlider.maximum_value = 100; this.maxSlider.overdrive_start = 100; @@ -324,12 +324,7 @@ 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.imSliderMax.add_child(this.maxSlider); this.imCurrentTitle = new PopupMenu.PopupMenuItem( `${_("Current Frequency")}:`, { reactive: false } @@ -369,7 +364,7 @@ var CPUFreqIndicator = class CPUFreqIndicator extends baseindicator.CPUFreqBaseI 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: @@ -386,7 +381,7 @@ var CPUFreqIndicator = class CPUFreqIndicator extends baseindicator.CPUFreqBaseI `${_("Oh no! Something went wrong.")}\n` + `${_( "An internal error occurred:" - )} ${Cpufreqctl.exitCodeToString( + )} ${utils.Cpufreqctl.exitCodeToString( result.exitCode )}`, true @@ -418,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() { @@ -442,7 +437,7 @@ var CPUFreqIndicator = class CPUFreqIndicator extends baseindicator.CPUFreqBaseI updateMax(done) { let backend = this.settings.get_string("cpufreqctl-backend"); - Cpufreqctl.max.set( + utils.Cpufreqctl.max.set( backend, Math.floor(this.maxVal).toString(), (_result) => { @@ -457,7 +452,7 @@ var CPUFreqIndicator = class CPUFreqIndicator extends baseindicator.CPUFreqBaseI updateMin(done) { let backend = this.settings.get_string("cpufreqctl-backend"); - Cpufreqctl.min.set( + utils.Cpufreqctl.min.set( backend, Math.floor(this.minVal).toString(), (_result) => { @@ -472,7 +467,7 @@ var CPUFreqIndicator = class CPUFreqIndicator extends baseindicator.CPUFreqBaseI updateTurbo(done) { let backend = this.settings.get_string("cpufreqctl-backend"); - Cpufreqctl.turbo.set( + utils.Cpufreqctl.turbo.set( backend, this.isTurboBoostActive ? "on" : "off", (_result) => { @@ -527,7 +522,7 @@ var CPUFreqIndicator = class CPUFreqIndicator extends baseindicator.CPUFreqBaseI } 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")) { @@ -577,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; } @@ -602,11 +597,11 @@ var CPUFreqIndicator = class CPUFreqIndicator extends baseindicator.CPUFreqBaseI } checkFrequencies(cb) { - Cpufreqctl.info.frequencies( + utils.Cpufreqctl.info.frequencies( this.settings.get_string("cpufreqctl-backend"), (result) => { if (!result.ok || result.exitCode !== 0) { - let exitReason = Cpufreqctl.exitCodeToString( + let exitReason = utils.Cpufreqctl.exitCodeToString( result.exitCode ); log( @@ -646,14 +641,7 @@ var CPUFreqIndicator = class CPUFreqIndicator extends baseindicator.CPUFreqBaseI } onPreferencesActivate(_item) { - Util.trySpawnCommandLine( - GLib.uri_resolve_relative( - import.meta.url, - "./src/prefs40/main.js", - GLib.UriFlags.NONE - ) - ); - - return 0; + const extension = Extension.lookupByURL(import.meta.url); + extension.openPreferences(); } -}; +} diff --git a/src/notinstalled.js b/src/notinstalled.js index 01805d67..64ff45c3 100644 --- a/src/notinstalled.js +++ b/src/notinstalled.js @@ -27,27 +27,14 @@ */ // Gnome imports -import * as PanelMenu from "resource:///org/gnome/shell/ui/panelMenu.js"; -import * as PopupMenu from "resource:///org/gnome/shell/ui/popupMenu.js"; -import * as Main from "resource:///org/gnome/shell/ui/main.js"; -import * as Util from "resource:///org/gnome/shell/misc/util.js"; -import { - ExtensionUtils, - gettext as _, -} from "resource:///org/gnome/shell/extensions/extension.js"; -import Gtk from "gi://Gtk"; -import Gio from "gi://Gio"; -import GLib from "gi://GLib"; +import Gio from 'gi://Gio'; -// // Relative and misc imports and definitions -// const ExtensionUtils = imports.misc.extensionUtils; -// const Me = ExtensionUtils.getCurrentExtension(); -import baseindicator from "baseindicator"; -import attemptInstallation from "utils.attemptInstallation"; -import utils from "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 { @@ -66,31 +53,21 @@ var NotInstalledIndicator = class NotInstalledIndicator extends baseindicator.CP super.createMenu(); if (this.exitCode === utils.INSTALLER_NOT_INSTALLED) { - let notInstalledLabel = new PopupMenu.PopupMenuItem( - _("Installation required."), - { reactive: false } - ); + let notInstalledLabel = new PopupMenu.PopupMenuItem(_("Installation required."), {reactive: false}); this.mainSection.addMenuItem(notInstalledLabel); } else { let errorLabel = new PopupMenu.PopupMenuItem( - _( - "Oh no! This should not have happened.\n" + - "An error occurred while checking the installation!" - ), - { reactive: false } + _("Oh no! This should not have happened.\n" + + "An error occurred while checking the installation!"), + {reactive: false}, ); 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(errorLabel); this.mainSection.addMenuItem(reportLabel); @@ -99,14 +76,8 @@ var NotInstalledIndicator = class NotInstalledIndicator extends baseindicator.CP let separator = new PopupMenu.PopupSeparatorMenuItem(); this.mainSection.addMenuItem(separator); - this.attemptInstallationLabel = new PopupMenu.PopupMenuItem( - _("Attempt installation"), - { reactive: true } - ); - this.attemptInstallationLabel.connect( - "activate", - attemptInstallation.bind(null, this.done) - ); + this.attemptInstallationLabel = new PopupMenu.PopupMenuItem(_("Attempt installation"), {reactive: true}); + 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 7eadd42d..eb5be44c 100644 --- a/src/preferences.js +++ b/src/preferences.js @@ -26,40 +26,24 @@ * */ -import * as PanelMenu from "resource:///org/gnome/shell/ui/panelMenu.js"; -import * as PopupMenu from "resource:///org/gnome/shell/ui/popupMenu.js"; -import * as Main from "resource:///org/gnome/shell/ui/main.js"; -import * as Util from "resource:///org/gnome/shell/misc/util.js"; -import { - Extension, - gettext as _, -} from "resource:///org/gnome/shell/extensions/extension.js"; -import Gtk from "gi://Gtk"; -import Gio from "gi://Gio"; -import GLib from "gi://GLib"; - -// 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(); -import Convenience from "convenience"; -import CPUFreqProfile from "profile.CPUFreqProfile"; -import * as CONFIG from "config"; -import attemptUninstallation from "utils.attemptUninstallation"; -import Cpufreqctl from "utils.Cpufreqctl"; - -const EXTENSIONDIR = dir.get_path(); +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; @@ -69,21 +53,18 @@ var CPUPowerPreferences = class CPUPowerPreferences { Gio.BusNameOwnerFlags.NONE, this.onBusAcquired.bind(this), this.onNameAcquired.bind(this), - this.onNameLost.bind(this) + this.onNameLost.bind(this), ); this.Builder = new Gtk.Builder(); this.Builder.set_translation_domain("gnome-shell-extension-cpupower"); - this.Builder.add_objects_from_file(GLADE_FILE, [ - "MainWidget", - "AboutButton", - "FrequencyScalingDriverListStore", - ]); - this.Builder.connect_signals_full( - (builder, object, signal, handler) => { - object.connect(signal, this[handler].bind(this)); - } + this.Builder.add_objects_from_file( + GLADE_FILE, + ["MainWidget", "AboutButton", "FrequencyScalingDriverListStore"], ); + this.Builder.connect_signals_full((builder, object, signal, handler) => { + object.connect(signal, this[handler].bind(this)); + }); this.loadWidgets( "MainWidget", "AboutButton", @@ -105,30 +86,22 @@ var CPUPowerPreferences = class CPUPowerPreferences { "CpufreqctlPathLabel", "PolicykitRulePathLabel", "InstallationWarningLabel", - "UninstallButton" + "UninstallButton", ); this.ProfilesMap = new Map(); } onBusAcquired(connection, _name) { log("DBus bus acquired!"); - const interfaceBinary = GLib.file_get_contents( - `${EXTENSIONDIR}/schemas/io.github.martin31821.cpupower.dbus.xml` - )[1]; + 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(); } - this.cpupowerService = Gio.DBusExportedObject.wrapJSObject( - interfaceXml, - {} - ); - this.cpupowerService.export( - connection, - "/io/github/martin31821/cpupower" - ); + this.cpupowerService = Gio.DBusExportedObject.wrapJSObject(interfaceXml, {}); + this.cpupowerService.export(connection, "/io/github/martin31821/cpupower"); // do not set connection in 'this' here, as we use it to check if name is // acquired @@ -149,39 +122,30 @@ var CPUPowerPreferences = class CPUPowerPreferences { } 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, + }); } - ); + }); } updateSettings(done) { @@ -292,11 +256,7 @@ var CPUPowerPreferences = class CPUPowerPreferences { syncOrdering() { for (let profileContext of this.ProfilesMap.values()) { let index = profileContext.ListItem.Row.get_index(); - this.ProfileStack.child_set_property( - profileContext.Settings.StackItem, - "position", - index - ); + this.ProfileStack.child_set_property(profileContext.Settings.StackItem, "position", index); } } @@ -359,102 +319,93 @@ var CPUPowerPreferences = class CPUPowerPreferences { }; let profileSettingsBuilder = new Gtk.Builder(); - profileSettingsBuilder.set_translation_domain( - "gnome-shell-extension-cpupower" + profileSettingsBuilder.set_translation_domain("gnome-shell-extension-cpupower"); + profileSettingsBuilder.add_objects_from_file( + GLADE_FILE, + [ + "ProfileSettingsGrid", + "MaximumFrequencyAdjustment", + "MinimumFrequencyAdjustment", + ], + ); + profileContext.Settings.NameEntry = profileSettingsBuilder.get_object( + "ProfileNameEntry", + ); + profileContext.Settings.MinimumFrequencyScale = profileSettingsBuilder.get_object( + "ProfileMinimumFrequencyScale", ); - profileSettingsBuilder.add_objects_from_file(GLADE_FILE, [ + profileContext.Settings.MaximumFrequencyScale = profileSettingsBuilder.get_object( + "ProfileMaximumFrequencyScale", + ); + profileContext.Settings.TurboBoostSwitch = profileSettingsBuilder.get_object( + "ProfileTurboBoostSwitch", + ); + profileContext.Settings.DiscardButton = profileSettingsBuilder.get_object( + "ProfileDiscardButton", + ); + profileContext.Settings.SaveButton = profileSettingsBuilder.get_object( + "ProfileSaveButton", + ); + profileContext.Settings.StackItem = profileSettingsBuilder.get_object( "ProfileSettingsGrid", - "MaximumFrequencyAdjustment", + ); + profileContext.Settings.CpuInfoGrid = profileSettingsBuilder.get_object( + "ProfileInfoGrid", + ); + profileContext.Settings.LimitMinLabel = profileSettingsBuilder.get_object( + "ProfileLimitMinLabel", + ); + profileContext.Settings.LimitMaxLabel = profileSettingsBuilder.get_object( + "ProfileLimitMaxLabel", + ); + profileContext.Settings.MinimumFrequencyAdjustment = profileSettingsBuilder.get_object( "MinimumFrequencyAdjustment", - ]); - profileContext.Settings.NameEntry = - profileSettingsBuilder.get_object("ProfileNameEntry"); - profileContext.Settings.MinimumFrequencyScale = - profileSettingsBuilder.get_object( - "ProfileMinimumFrequencyScale" - ); - profileContext.Settings.MaximumFrequencyScale = - profileSettingsBuilder.get_object( - "ProfileMaximumFrequencyScale" - ); - profileContext.Settings.TurboBoostSwitch = - profileSettingsBuilder.get_object("ProfileTurboBoostSwitch"); - profileContext.Settings.DiscardButton = - profileSettingsBuilder.get_object("ProfileDiscardButton"); - profileContext.Settings.SaveButton = - profileSettingsBuilder.get_object("ProfileSaveButton"); - profileContext.Settings.StackItem = - profileSettingsBuilder.get_object("ProfileSettingsGrid"); - profileContext.Settings.CpuInfoGrid = - profileSettingsBuilder.get_object("ProfileInfoGrid"); - profileContext.Settings.LimitMinLabel = - profileSettingsBuilder.get_object("ProfileLimitMinLabel"); - profileContext.Settings.LimitMaxLabel = - profileSettingsBuilder.get_object("ProfileLimitMaxLabel"); - profileContext.Settings.MinimumFrequencyAdjustment = - profileSettingsBuilder.get_object("MinimumFrequencyAdjustment"); - profileContext.Settings.MaximumFrequencyAdjustment = - profileSettingsBuilder.get_object("MaximumFrequencyAdjustment"); - profileContext.Settings.MinimumFrequencyValueLabel = - profileSettingsBuilder.get_object( - "ProfileMinimumFrequencyValueLabel" - ); - profileContext.Settings.MaximumFrequencyValueLabel = - profileSettingsBuilder.get_object( - "ProfileMaximumFrequencyValueLabel" - ); + ); + profileContext.Settings.MaximumFrequencyAdjustment = profileSettingsBuilder.get_object( + "MaximumFrequencyAdjustment", + ); + profileContext.Settings.MinimumFrequencyValueLabel = profileSettingsBuilder.get_object( + "ProfileMinimumFrequencyValueLabel", + ); + profileContext.Settings.MaximumFrequencyValueLabel = profileSettingsBuilder.get_object( + "ProfileMaximumFrequencyValueLabel", + ); let profileListItemBuilder = new Gtk.Builder(); - profileListItemBuilder.set_translation_domain( - "gnome-shell-extension-cpupower" + profileListItemBuilder.set_translation_domain("gnome-shell-extension-cpupower"); + profileListItemBuilder.add_objects_from_file(GLADE_FILE, ["ProfileListBoxRow"]); + profileContext.ListItem.NameLabel = profileListItemBuilder.get_object( + "ProfileRowNameLabel", ); - profileListItemBuilder.add_objects_from_file(GLADE_FILE, [ + profileContext.ListItem.MinimumFrequencyLabel = profileListItemBuilder.get_object( + "ProfileRowMinimumFrequencyLabel", + ); + profileContext.ListItem.MaximumFrequencyLabel = profileListItemBuilder.get_object( + "ProfileRowMaximumFrequencyLabel", + ); + profileContext.ListItem.TurboBoostStatusLabel = profileListItemBuilder.get_object( + "ProfileRowTurboBoostStatusLabel", + ); + profileContext.ListItem.AutoSwitchACIcon = profileListItemBuilder.get_object( + "ProfileRowACIcon", + ); + profileContext.ListItem.AutoSwitchBatIcon = profileListItemBuilder.get_object( + "ProfileRowBatIcon", + ); + profileContext.ListItem.Row = profileListItemBuilder.get_object( "ProfileListBoxRow", - ]); - profileContext.ListItem.NameLabel = - profileListItemBuilder.get_object("ProfileRowNameLabel"); - profileContext.ListItem.MinimumFrequencyLabel = - profileListItemBuilder.get_object( - "ProfileRowMinimumFrequencyLabel" - ); - profileContext.ListItem.MaximumFrequencyLabel = - profileListItemBuilder.get_object( - "ProfileRowMaximumFrequencyLabel" - ); - profileContext.ListItem.TurboBoostStatusLabel = - profileListItemBuilder.get_object( - "ProfileRowTurboBoostStatusLabel" - ); - profileContext.ListItem.AutoSwitchACIcon = - profileListItemBuilder.get_object("ProfileRowACIcon"); - profileContext.ListItem.AutoSwitchBatIcon = - profileListItemBuilder.get_object("ProfileRowBatIcon"); - profileContext.ListItem.Row = - profileListItemBuilder.get_object("ProfileListBoxRow"); - - profileSettingsBuilder.connect_signals_full( - (builder, object, signal, handler) => { - object.connect( - signal, - this[handler].bind(this, profileContext) - ); - } ); - profileListItemBuilder.connect_signals_full( - (builder, object, signal, handler) => { - object.connect( - signal, - this[handler].bind(this, profileContext) - ); - } - ); + profileSettingsBuilder.connect_signals_full((builder, object, signal, handler) => { + object.connect(signal, this[handler].bind(this, profileContext)); + }); + + profileListItemBuilder.connect_signals_full((builder, object, signal, handler) => { + object.connect(signal, this[handler].bind(this, profileContext)); + }); this.ProfilesListBox.prepend(profileContext.ListItem.Row); - this.ProfileStack.add_named( - profileContext.Settings.StackItem, - profileContext.Profile.UUID.toString(16) - ); + this.ProfileStack.add_named(profileContext.Settings.StackItem, profileContext.Profile.UUID.toString(16)); this.ProfilesMap.set(profileContext.Profile.UUID, profileContext); this.syncOrdering(); } else { @@ -467,60 +418,34 @@ var CPUPowerPreferences = class CPUPowerPreferences { profileContext.Settings.LimitMaxLabel.set_text(`${this.cpuMaxLimit}%`); // modify adjustments - profileContext.Settings.MinimumFrequencyAdjustment.set_lower( - this.cpuMinLimit - ); - profileContext.Settings.MinimumFrequencyAdjustment.set_upper( - profileContext.Profile.MaximumFrequency - ); - profileContext.Settings.MaximumFrequencyAdjustment.set_lower( - profileContext.Profile.MinimumFrequency - ); - profileContext.Settings.MaximumFrequencyAdjustment.set_upper( - this.cpuMaxLimit - ); + profileContext.Settings.MinimumFrequencyAdjustment.set_lower(this.cpuMinLimit); + profileContext.Settings.MinimumFrequencyAdjustment.set_upper(profileContext.Profile.MaximumFrequency); + profileContext.Settings.MaximumFrequencyAdjustment.set_lower(profileContext.Profile.MinimumFrequency); + profileContext.Settings.MaximumFrequencyAdjustment.set_upper(this.cpuMaxLimit); - profileContext.Settings.MinimumFrequencyScale.set_value( - profileContext.Profile.MinimumFrequency - ); - profileContext.Settings.MaximumFrequencyScale.set_value( - profileContext.Profile.MaximumFrequency - ); + profileContext.Settings.MinimumFrequencyScale.set_value(profileContext.Profile.MinimumFrequency); + profileContext.Settings.MaximumFrequencyScale.set_value(profileContext.Profile.MaximumFrequency); profileContext.Settings.MinimumFrequencyValueLabel.set_text( - `${profileContext.Profile.MinimumFrequency}%` + `${profileContext.Profile.MinimumFrequency}%`, ); profileContext.Settings.MaximumFrequencyValueLabel.set_text( - `${profileContext.Profile.MaximumFrequency}%` + `${profileContext.Profile.MaximumFrequency}%`, ); profileContext.Settings.NameEntry.set_text(profileContext.Profile.Name); - profileContext.Settings.TurboBoostSwitch.set_active( - profileContext.Profile.TurboBoost - ); + profileContext.Settings.TurboBoostSwitch.set_active(profileContext.Profile.TurboBoost); profileContext.ListItem.NameLabel.set_text(profileContext.Profile.Name); - profileContext.ListItem.MinimumFrequencyLabel.set_text( - profileContext.Profile.MinimumFrequency.toString() - ); - profileContext.ListItem.MaximumFrequencyLabel.set_text( - profileContext.Profile.MaximumFrequency.toString() - ); - profileContext.ListItem.TurboBoostStatusLabel.set_text( - profileContext.Profile.TurboBoost ? _("Yes") : _("No") - ); + profileContext.ListItem.MinimumFrequencyLabel.set_text(profileContext.Profile.MinimumFrequency.toString()); + profileContext.ListItem.MaximumFrequencyLabel.set_text(profileContext.Profile.MaximumFrequency.toString()); + profileContext.ListItem.TurboBoostStatusLabel.set_text(profileContext.Profile.TurboBoost ? _("Yes") : _("No")); - if ( - this.settings.get_string("default-ac-profile") === - profileContext.Profile.UUID - ) { + if (this.settings.get_string("default-ac-profile") === profileContext.Profile.UUID) { profileContext.ListItem.AutoSwitchACIcon.set_visible(true); } else { profileContext.ListItem.AutoSwitchACIcon.set_visible(false); } - if ( - this.settings.get_string("default-battery-profile") === - profileContext.Profile.UUID - ) { + if (this.settings.get_string("default-battery-profile") === profileContext.Profile.UUID) { profileContext.ListItem.AutoSwitchBatIcon.set_visible(true); } else { profileContext.ListItem.AutoSwitchBatIcon.set_visible(false); @@ -540,16 +465,10 @@ var CPUPowerPreferences = class CPUPowerPreferences { let profileContext = this.ProfilesMap.get(profile.UUID); // set default profile to none if the removed profile was selected - if ( - this.DefaultACComboBox.get_active_id() === - profileContext.Profile.UUID - ) { + if (this.DefaultACComboBox.get_active_id() === profileContext.Profile.UUID) { this.settings.set_string("default-ac-profile", ""); } - if ( - this.DefaultBatComboBox.get_active_id() === - profileContext.Profile.UUID - ) { + if (this.DefaultBatComboBox.get_active_id() === profileContext.Profile.UUID) { this.settings.set_string("default-battery-profile", ""); } @@ -604,11 +523,7 @@ var CPUPowerPreferences = class CPUPowerPreferences { this.DefaultBatComboBox.append("", _("None")); let profileArray = Array.from(this.ProfilesMap.values()); - profileArray.sort( - (p1, p2) => - this.getProfileIndex(p1.Profile) - - this.getProfileIndex(p2.Profile) - ); + profileArray.sort((p1, p2) => this.getProfileIndex(p1.Profile) - this.getProfileIndex(p2.Profile)); for (let i in profileArray) { let profile = profileArray[i].Profile; @@ -628,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) { @@ -637,9 +552,9 @@ var CPUPowerPreferences = class CPUPowerPreferences { liststore.set( iter, [0, 1, 2], - [`${_("Automatic")} (${chosenBackend})`, "automatic", true] + [`${_("Automatic")} (${chosenBackend})`, "automatic", true], ); - Cpufreqctl.backends.list(backend, (result) => { + utils.Cpufreqctl.backends.list(backend, (result) => { if (!result.ok) { return; } @@ -649,7 +564,7 @@ var CPUPowerPreferences = class CPUPowerPreferences { liststore.set( iter, [0, 1, 2], - [backend, backend, supported] + [backend, backend, supported], ); } combobox.set_active_id(backend); @@ -707,12 +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)}` - ); + this.status(`Failed to reset frequency scaling driver of old backend ${oldBackend}: ` + + `${utils.Cpufreqctl.exitCodeToString(result.exitCode)}`); } }); } @@ -775,40 +688,25 @@ var CPUPowerPreferences = class CPUPowerPreferences { onUninstallButtonClicked(_button) { let uninstallDialogBuilder = new Gtk.Builder(); - uninstallDialogBuilder.set_translation_domain( - "gnome-shell-extension-cpupower" - ); - uninstallDialogBuilder.add_objects_from_file(GLADE_FILE, [ - "UninstallMessageDialog", - ]); - let dialog = uninstallDialogBuilder.get_object( - "UninstallMessageDialog" - ); - let uninstallButton = uninstallDialogBuilder.get_object( - "UninstallDialogUninstall" - ); - let cancelButton = uninstallDialogBuilder.get_object( - "UninstallDialogCancel" - ); + uninstallDialogBuilder.set_translation_domain("gnome-shell-extension-cpupower"); + uninstallDialogBuilder.add_objects_from_file(GLADE_FILE, ["UninstallMessageDialog"]); + let dialog = uninstallDialogBuilder.get_object("UninstallMessageDialog"); + let uninstallButton = uninstallDialogBuilder.get_object("UninstallDialogUninstall"); + let cancelButton = uninstallDialogBuilder.get_object("UninstallDialogCancel"); let parentWindow = this.MainWidget.get_toplevel(); dialog.set_transient_for(parentWindow); uninstallButton.connect("clicked", () => { - attemptUninstallation((_success) => { + utils.attemptUninstallation((_success) => { dialog.close(); if (this.cpupowerConnection) { log("reloading extension"); - let result = this.cpupowerService.emit_signal( - "ExtensionReloadRequired", - null - ); + let result = this.cpupowerService.emit_signal("ExtensionReloadRequired", null); log(`emit signal result: ${result}`); } else { // hmm... extension seems not to be running, so who cares? - log( - "Could not trigger extension reload as dbus connection is offline!" - ); + log("Could not trigger extension reload as dbus connection is offline!"); } GLib.timeout_add(GLib.PRIORITY_DEFAULT, 0, () => { @@ -825,12 +723,8 @@ var CPUPowerPreferences = class CPUPowerPreferences { } showCpuLimitInfo(profileContext) { - if ( - profileContext.Settings.MinimumFrequencyScale.get_value() === - this.cpuMinLimit || - profileContext.Settings.MaximumFrequencyScale.get_value() === - this.cpuMaxLimit - ) { + if (profileContext.Settings.MinimumFrequencyScale.get_value() === this.cpuMinLimit || + profileContext.Settings.MaximumFrequencyScale.get_value() === this.cpuMaxLimit) { profileContext.Settings.CpuInfoGrid.set_visible(true); } else { profileContext.Settings.CpuInfoGrid.set_visible(false); @@ -840,9 +734,7 @@ var CPUPowerPreferences = class CPUPowerPreferences { onProfilesListBoxRowSelected(_box, _row) { let profileContext = this.getSelectedProfileContext(); if (profileContext) { - this.ProfileStack.set_visible_child( - profileContext.Settings.StackItem - ); + this.ProfileStack.set_visible_child(profileContext.Settings.StackItem); } } @@ -862,18 +754,13 @@ var CPUPowerPreferences = class CPUPowerPreferences { } onProfileMinimumFrequencyScaleValueChanged(profileContext, scale) { - let changed = - profileContext.Profile.MinimumFrequency !== scale.get_value(); + let changed = profileContext.Profile.MinimumFrequency !== scale.get_value(); if (changed) { profileContext.Settings.DiscardButton.sensitive = true; profileContext.Settings.SaveButton.sensitive = true; - profileContext.Settings.MaximumFrequencyAdjustment.set_lower( - scale.get_value() - ); - profileContext.Settings.MinimumFrequencyValueLabel.set_text( - `${scale.get_value()}%` - ); + profileContext.Settings.MaximumFrequencyAdjustment.set_lower(scale.get_value()); + profileContext.Settings.MinimumFrequencyValueLabel.set_text(`${scale.get_value()}%`); this.showCpuLimitInfo(profileContext); @@ -886,18 +773,13 @@ var CPUPowerPreferences = class CPUPowerPreferences { } onProfileMaximumFrequencyScaleValueChanged(profileContext, scale) { - let changed = - profileContext.Profile.MaximumFrequency !== scale.get_value(); + let changed = profileContext.Profile.MaximumFrequency !== scale.get_value(); if (changed) { profileContext.Settings.DiscardButton.sensitive = true; profileContext.Settings.SaveButton.sensitive = true; - profileContext.Settings.MinimumFrequencyAdjustment.set_upper( - scale.get_value() - ); - profileContext.Settings.MaximumFrequencyValueLabel.set_text( - `${scale.get_value()}%` - ); + profileContext.Settings.MinimumFrequencyAdjustment.set_upper(scale.get_value()); + profileContext.Settings.MaximumFrequencyValueLabel.set_text(`${scale.get_value()}%`); this.showCpuLimitInfo(profileContext); @@ -910,8 +792,7 @@ var CPUPowerPreferences = class CPUPowerPreferences { } onProfileTurboBoostSwitchActiveNotify(profileContext, switchButton) { - let changed = - profileContext.Profile.TurboBoost !== switchButton.get_active(); + let changed = profileContext.Profile.TurboBoost !== switchButton.get_active(); if (changed) { profileContext.Settings.DiscardButton.sensitive = true; @@ -931,10 +812,8 @@ var CPUPowerPreferences = class CPUPowerPreferences { onProfileSaveButtonClicked(profileContext, _button) { let name = profileContext.Settings.NameEntry.get_text(); - let minimumFrequency = - profileContext.Settings.MinimumFrequencyScale.get_value(); - let maximumFrequency = - profileContext.Settings.MaximumFrequencyScale.get_value(); + let minimumFrequency = profileContext.Settings.MinimumFrequencyScale.get_value(); + let maximumFrequency = profileContext.Settings.MaximumFrequencyScale.get_value(); let turboBoost = profileContext.Settings.TurboBoostSwitch.get_active(); profileContext.Profile.Name = name; @@ -950,10 +829,7 @@ var CPUPowerPreferences = class CPUPowerPreferences { let saved = []; for (let value of this.ProfilesMap.entries()) { this.status(`value: ${value[0]}${value[1]}`); - let idx = - this.ProfilesMap.size - - 1 - - this.getProfileIndex(value[1].Profile); + let idx = this.ProfilesMap.size - 1 - this.getProfileIndex(value[1].Profile); this.status(`Saving: ${value[1].Profile.UUID} to idx ${idx}`); saved[idx] = value[1].Profile.save(); } 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 1800b215..7ae0afaa 100644 --- a/src/profilebutton.js +++ b/src/profilebutton.js @@ -25,47 +25,18 @@ * */ -import * as PanelMenu from "resource:///org/gnome/shell/ui/panelMenu.js"; -import * as PopupMenu from "resource:///org/gnome/shell/ui/popupMenu.js"; -import * as Main from "resource:///org/gnome/shell/ui/main.js"; -import * as Util from "resource:///org/gnome/shell/misc/util.js"; -import { - Extension, - gettext as _, -} from "resource:///org/gnome/shell/extensions/extension.js"; -import GObject from "gi://GObject"; +import GObject from 'gi://GObject'; -import Config from "./prefs40/misc"; - -// const Gettext = imports.gettext.domain("gnome-shell-extension-cpupower"); -// const _ = Gettext.gettext; +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/update.js b/src/update.js index e4a36c89..dfed5532 100644 --- a/src/update.js +++ b/src/update.js @@ -27,24 +27,12 @@ */ // Gnome imports -import * as PanelMenu from "resource:///org/gnome/shell/ui/panelMenu.js"; -import * as PopupMenu from "resource:///org/gnome/shell/ui/popupMenu.js"; -import * as Main from "resource:///org/gnome/shell/ui/main.js"; -import * as Util from "resource:///org/gnome/shell/misc/util.js"; -import { - Extension, - gettext as _, -} from "resource:///org/gnome/shell/extensions/extension.js"; -import GObject from "gi://GObject"; +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(); -import baseindicator from "./baseindicator"; -import attemptUpdate from "./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; @@ -66,34 +54,22 @@ var UpdateIndicator = class UpdateIndicator extends baseindicator.CPUFreqBaseInd createMenu() { super.createMenu(); - let updateText = _( - "Your CPU Power Manager installation needs updating!" - ); - let securityText = _( - "Warning: Security issues were found with your installation!\n" + - "Please update immediately!" - ); + let updateText = _("Your CPU Power Manager installation needs updating!"); + let securityText = _("Warning: Security issues were found with your installation!\n" + + "Please update immediately!"); if (this.updateType === SECURITY_UPDATE) { updateText += "\n"; updateText += securityText; } - let updateLabel = new PopupMenu.PopupMenuItem(updateText, { - reactive: false, - }); + let updateLabel = new PopupMenu.PopupMenuItem(updateText, {reactive: false}); this.mainSection.addMenuItem(updateLabel); let separator = new PopupMenu.PopupSeparatorMenuItem(); this.mainSection.addMenuItem(separator); - this.attemptUpdateLabel = new PopupMenu.PopupMenuItem( - _("Attempt tool update"), - { reactive: true } - ); - this.attemptUpdateLabel.connect( - "activate", - attemptUpdate.bind(null, this.done) - ); + this.attemptUpdateLabel = new PopupMenu.PopupMenuItem(_("Attempt tool update"), {reactive: true}); + this.attemptUpdateLabel.connect("activate", attemptUpdate.bind(null, this.done)); this.mainSection.addMenuItem(this.attemptUpdateLabel); } }; diff --git a/src/utils.js b/src/utils.js index 279813d9..ecbbab96 100644 --- a/src/utils.js +++ b/src/utils.js @@ -29,16 +29,16 @@ import Gio from 'gi://Gio'; import GLib from 'gi://GLib'; - -//const EXTENSIONDIR = Me.dir.get_path(); -const INSTALLER = GLib.uri_resolve_relative(import.meta.url, '/tool/installer.sh', GLib.UriFlags.NONE)); const PKEXEC = GLib.find_program_in_path("pkexec"); -import { CONFIG } from "./src/config.js" +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) { @@ -71,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, @@ -94,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, @@ -102,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, @@ -110,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, @@ -118,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 = [ @@ -208,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() From 7b78a745ddb6d1a109fba7d83b1aebb697827b28 Mon Sep 17 00:00:00 2001 From: Gustavo Freitas Date: Tue, 5 Mar 2024 10:41:34 -0300 Subject: [PATCH 08/10] new version --- metadata.json | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/metadata.json b/metadata.json index 4688132c..d15716c1 100644 --- a/metadata.json +++ b/metadata.json @@ -1,12 +1,10 @@ { - "localedir": "/usr/local/share/locale", - "shell-version": [ - "45" - ], - "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" + "localedir": "/usr/local/share/locale", + "shell-version": ["45", "45.1", "45.2", "45.3", "46"], + "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" } From 72890222ba114806b7d11c16db4c591eff7136de Mon Sep 17 00:00:00 2001 From: Gustavo Freitas Date: Tue, 5 Mar 2024 10:51:33 -0300 Subject: [PATCH 09/10] novos gnomes --- metadata.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/metadata.json b/metadata.json index d15716c1..15df44bf 100644 --- a/metadata.json +++ b/metadata.json @@ -1,6 +1,6 @@ { "localedir": "/usr/local/share/locale", - "shell-version": ["45", "45.1", "45.2", "45.3", "46"], + "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", From 1d72d3a89779cbb09878bd2e19db8bfc5818cb90 Mon Sep 17 00:00:00 2001 From: jekkos Date: Sun, 15 Sep 2024 10:29:18 +0200 Subject: [PATCH 10/10] Gnome 46 support --- src/baseindicator.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/baseindicator.js b/src/baseindicator.js index 52a5c6ec..daab0db2 100644 --- a/src/baseindicator.js +++ b/src/baseindicator.js @@ -82,13 +82,13 @@ export class CPUFreqBaseIndicator { this.arrowActive = this.settings.get_boolean("show-arrow-in-taskbar"); this.hbox.remove_all_children(); if (this.iconActive) { - this.hbox.add_actor(this.icon); + this.hbox.add_child(this.icon); } if (this.lblActive) { - this.hbox.add_actor(this.lbl); + this.hbox.add_child(this.lbl); } if (this.arrowActive) { - this.hbox.add_actor(this.arrow); + this.hbox.add_child(this.arrow); } } @@ -99,11 +99,11 @@ export class CPUFreqBaseIndicator { } disable() { - this.actor.remove_actor(this.hbox); + this.actor.remove_child(this.hbox); } enable() { - this.actor.add_actor(this.hbox); + this.actor.add_child(this.hbox); } destroy() {