Code refactoring, more readable and easier to modify (#736)

* Add global variables

* Add global variables

* Code refactoring

* Refactoring
This commit is contained in:
Angel 2024-07-16 16:37:04 +02:00 committed by GitHub
parent 34ebd04df0
commit 6f7e469e66
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
20 changed files with 475 additions and 1021 deletions

View File

@ -1,20 +1,20 @@
#!/usr/bin/env python3
import subprocess
from subprocess import PIPE, run
from auto_cpufreq.battery_scripts.thinkpad import thinkpad_setup, thinkpad_print_thresholds
from auto_cpufreq.battery_scripts.ideapad_acpi import ideapad_acpi_setup, ideapad_acpi_print_thresholds
from auto_cpufreq.battery_scripts.ideapad_laptop import ideapad_laptop_setup, ideapad_laptop_print_thresholds
from auto_cpufreq.battery_scripts.ideapad_acpi import ideapad_acpi_print_thresholds, ideapad_acpi_setup
from auto_cpufreq.battery_scripts.ideapad_laptop import ideapad_laptop_print_thresholds, ideapad_laptop_setup
from auto_cpufreq.battery_scripts.thinkpad import thinkpad_print_thresholds, thinkpad_setup
def lsmod(module): return module in subprocess.run(['lsmod'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True).stdout
def battery_setup():
if lsmod("thinkpad_acpi"): thinkpad_setup()
elif lsmod("ideapad_acpi"): ideapad_acpi_setup()
elif lsmod("ideapad_laptop"): ideapad_laptop_setup()
else: return
def lsmod(module): return module in run(['lsmod'], stdout=PIPE, stderr=PIPE, text=True).stdout
def battery_get_thresholds():
if lsmod("thinkpad_acpi"): thinkpad_print_thresholds()
elif lsmod("ideapad_acpi"): ideapad_acpi_print_thresholds()
if lsmod("ideapad_acpi"): ideapad_acpi_print_thresholds()
elif lsmod("ideapad_laptop"): ideapad_laptop_print_thresholds()
elif lsmod("thinkpad_acpi"): thinkpad_print_thresholds()
else: return
def battery_setup():
if lsmod("ideapad_acpi"): ideapad_acpi_setup()
elif lsmod("ideapad_laptop"): ideapad_laptop_setup()
elif lsmod("thinkpad_acpi"): thinkpad_setup()
else: return

View File

@ -1,9 +1,8 @@
#!/usr/bin/env python3
import os
import subprocess
from auto_cpufreq.utils.config import config
import os, subprocess
POWER_SUPPLY_DIR = "/sys/class/power_supply/"
from auto_cpufreq.config.config import config
from auto_cpufreq.globals import POWER_SUPPLY_DIR
def set_battery(value, mode, bat):
path = f"{POWER_SUPPLY_DIR}{bat}/charge_{mode}_threshold"
@ -25,7 +24,7 @@ def ideapad_acpi_setup():
for bat in batteries:
set_battery(get_threshold_value("start"), "start", bat)
set_battery(get_threshold_value("stop"), "stop", bat)
else: print(f"WARNING: could NOT access {POWER_SUPPLY_DIR}")
else: print("WARNING: could NOT access", POWER_SUPPLY_DIR)
def ideapad_acpi_print_thresholds():
batteries = [name for name in os.listdir(POWER_SUPPLY_DIR) if name.startswith('BAT')]
@ -35,4 +34,4 @@ def ideapad_acpi_print_thresholds():
try:
print(f'{bat} start threshold = {subprocess.getoutput(f"cat {POWER_SUPPLY_DIR}{bat}/charge_start_threshold")}')
print(f'{bat} start threshold = {subprocess.getoutput(f"cat {POWER_SUPPLY_DIR}{bat}/charge_stop_threshold")}')
except Exception as e: print(f"ERROR: failed to read battery {bat} thresholds: ", repr(e))
except Exception as e: print(f"ERROR: failed to read battery {bat} thresholds:", repr(e))

View File

@ -1,9 +1,8 @@
#!/usr/bin/env python3
import os
import subprocess
from auto_cpufreq.utils.config import config
import os, subprocess
POWER_SUPPLY_DIR = "/sys/class/power_supply/"
from auto_cpufreq.config.config import config
from auto_cpufreq.globals import CONSERVATION_MODE_FILE, POWER_SUPPLY_DIR
def set_battery(value, mode, bat):
path = f"{POWER_SUPPLY_DIR}{bat}/charge_{mode}_threshold"
@ -17,14 +16,14 @@ def get_threshold_value(mode):
def conservation_mode(value):
try:
subprocess.check_output(f"echo {value} | tee /sys/bus/platform/drivers/ideapad_acpi/VPC2004:00/conservation_mode", shell=True, text=True)
subprocess.check_output(f"echo {value} | tee {CONSERVATION_MODE_FILE}", shell=True, text=True)
print(f"conservation_mode is {value}")
except: print("unable to set conservation mode")
return
def check_conservation_mode():
try:
value = subprocess.check_output("cat /sys/bus/platform/drivers/ideapad_acpi/VPC2004:00/conservation_mode", shell=True, text=True)
value = subprocess.check_output(["cat", CONSERVATION_MODE_FILE], text=True)
if value == "1": return True
elif value == "0": return False
else:
@ -66,4 +65,4 @@ def ideapad_laptop_print_thresholds():
try:
print(f'{bat} start threshold = {subprocess.getoutput(f"cat {POWER_SUPPLY_DIR}{bat}/charge_start_threshold")}')
print(f'{bat} start threshold = {subprocess.getoutput(f"cat {POWER_SUPPLY_DIR}{bat}/charge_stop_threshold")}')
except Exception as e: print(f"ERROR: failed to read battery {bat} thresholds: ", repr(e))
except Exception as e: print(f"ERROR: failed to read battery {bat} thresholds:", repr(e))

View File

@ -1,9 +1,8 @@
#!/usr/bin/env python3
import os
import subprocess
from auto_cpufreq.utils.config import config
import os, subprocess
POWER_SUPPLY_DIR = "/sys/class/power_supply/"
from auto_cpufreq.config.config import config
from auto_cpufreq.globals import POWER_SUPPLY_DIR
def set_battery(value, mode, bat):
path = f"{POWER_SUPPLY_DIR}{bat}/charge_{mode}_threshold"
@ -36,4 +35,4 @@ def thinkpad_print_thresholds():
try:
print(f'{bat} start threshold = {subprocess.getoutput(f"cat {POWER_SUPPLY_DIR}{bat}/charge_start_threshold")}')
print(f'{bat} start threshold = {subprocess.getoutput(f"cat {POWER_SUPPLY_DIR}{bat}/charge_stop_threshold")}')
except Exception as e: print(f"ERROR: failed to read battery {bat} thresholds: ", repr(e))
except Exception as e: print(f"ERROR: failed to read battery {bat} thresholds:", repr(e))

View File

@ -5,36 +5,32 @@
# Blog post: https://foolcontrol.org/?p=3124
# core import
import sys
import time
from click import UsageError
from subprocess import call, run
import sys, time
from subprocess import run
from shutil import rmtree
# sys.path.append("../")
from auto_cpufreq.core import *
from auto_cpufreq.power_helper import *
from auto_cpufreq.battery_scripts.battery import *
from auto_cpufreq.utils.config import config as conf, find_config_file
# cli
from auto_cpufreq.config.config import config as conf, find_config_file
from auto_cpufreq.core import *
from auto_cpufreq.globals import GITHUB, IS_INSTALLED_WITH_AUR, IS_INSTALLED_WITH_SNAP
from auto_cpufreq.power_helper import *
@click.command()
@click.option("--monitor", is_flag=True, help="Monitor and see suggestions for CPU optimizations")
@click.option("--live", is_flag=True, help="Monitor and make (temp.) suggested CPU optimizations")
@click.option("--daemon", is_flag=True, hidden=True)
@click.option("--install", is_flag=True, help="Install daemon for (permanent) automatic CPU optimizations")
@click.option("--update", is_flag=False, help="Update daemon and package for (permanent) automatic CPU optimizations", flag_value="--update")
@click.option("--remove", is_flag=True, help="Remove daemon for (permanent) automatic CPU optimizations")
@click.option("--stats", is_flag=True, help="View live stats of CPU optimizations made by daemon")
@click.option("--force", is_flag=False, help="Force use of either \"powersave\" or \"performance\" governors. Setting to \"reset\" will go back to normal mode")
@click.option("--get-state", is_flag=True, hidden=True)
@click.option("--config", is_flag=False, required=False, help="Use config file at defined path",)
@click.option("--stats", is_flag=True, help="View live stats of CPU optimizations made by daemon")
@click.option("--get-state", is_flag=True, hidden=True)
@click.option("--completions", is_flag=False, help="Enables shell completions for bash, zsh and fish.\n Possible values bash|zsh|fish")
@click.option("--debug", is_flag=True, help="Show debug info (include when submitting bugs)")
@click.option("--version", is_flag=True, help="Show currently installed version")
@click.option("--donate", is_flag=True, help="Support the project")
@click.option("--completions", is_flag=False, help="Enables shell completions for bash, zsh and fish.\n Possible values bash|zsh|fish")
@click.option("--log", is_flag=True, hidden=True)
@click.option("--daemon", is_flag=True, hidden=True)
def main(config, daemon, debug, update, install, remove, live, log, monitor, stats, version, donate, force, get_state, completions):
def main(monitor, live, daemon, install, update, remove, force, config, stats, get_state, completions, debug, version, donate):
# display info if config file is used
config_path = find_config_file(config)
conf.set_path(config_path)
@ -42,12 +38,6 @@ def main(config, daemon, debug, update, install, remove, live, log, monitor, sta
if conf.has_config():
print("\nUsing settings defined in " + config_path + " file")
# set governor override unless None or invalid
if force is not None:
not_running_daemon_check()
root_check() # Calling root_check before set_override as it will require sudo access
set_override(force) # Calling set override, only if force has some values
if len(sys.argv) == 1:
print("\n" + "-" * 32 + " auto-cpufreq " + "-" * 33 + "\n")
print("Automatic CPU speed & power optimizer for Linux")
@ -58,37 +48,20 @@ def main(config, daemon, debug, update, install, remove, live, log, monitor, sta
run(["auto-cpufreq", "--help"])
footer()
else:
if daemon:
config_info_dialog()
root_check()
file_stats()
if os.getenv("PKG_MARKER") == "SNAP" and dcheck == "enabled":
gnome_power_detect_snap()
tlp_service_detect_snap()
elif os.getenv("PKG_MARKER") != "SNAP":
gnome_power_detect()
tlp_service_detect()
battery_setup()
conf.notifier.start()
while True:
try:
footer()
gov_check()
cpufreqctl()
distro_info()
sysinfo()
set_autofreq()
countdown(2)
except KeyboardInterrupt: break
conf.notifier.stop()
elif monitor:
# set governor override unless None or invalid
if force is not None:
not_running_daemon_check()
root_check() # Calling root_check before set_override as it will require sudo access
set_override(force) # Calling set override, only if force has some values
if monitor:
config_info_dialog()
root_check()
print('\nNote: You can quit monitor mode by pressing "ctrl+c"')
battery_setup()
battery_get_thresholds()
conf.notifier.start()
if os.getenv("PKG_MARKER") == "SNAP":
if IS_INSTALLED_WITH_SNAP:
gnome_power_detect_snap()
tlp_service_detect_snap()
else:
@ -115,7 +88,7 @@ def main(config, daemon, debug, update, install, remove, live, log, monitor, sta
battery_setup()
battery_get_thresholds()
conf.notifier.start()
if os.getenv("PKG_MARKER") == "SNAP":
if IS_INSTALLED_WITH_SNAP:
gnome_power_detect_snap()
tlp_service_detect_snap()
else:
@ -137,11 +110,101 @@ def main(config, daemon, debug, update, install, remove, live, log, monitor, sta
print()
break
conf.notifier.stop()
elif daemon:
config_info_dialog()
root_check()
file_stats()
if IS_INSTALLED_WITH_SNAP and dcheck == "enabled":
gnome_power_detect_snap()
tlp_service_detect_snap()
elif not IS_INSTALLED_WITH_SNAP:
gnome_power_detect()
tlp_service_detect()
battery_setup()
conf.notifier.start()
while True:
try:
footer()
gov_check()
cpufreqctl()
distro_info()
sysinfo()
set_autofreq()
countdown(2)
except KeyboardInterrupt: break
conf.notifier.stop()
elif install:
root_check()
if IS_INSTALLED_WITH_SNAP:
running_daemon_check()
gnome_power_detect_snap()
tlp_service_detect_snap()
bluetooth_notif_snap()
gov_check()
run("snapctl set daemon=enabled", shell=True)
run("snapctl start --enable auto-cpufreq", shell=True)
else:
running_daemon_check()
gov_check()
deploy_daemon()
deploy_complete_msg()
elif update:
root_check()
custom_dir = "/opt/auto-cpufreq/source"
for arg in sys.argv:
if arg.startswith("--update="):
custom_dir = arg.split("=")[1]
sys.argv.remove(arg)
if "--update" in sys.argv:
update = True
sys.argv.remove("--update")
if len(sys.argv) == 2: custom_dir = sys.argv[1]
if IS_INSTALLED_WITH_SNAP:
print("Detected auto-cpufreq was installed using snap")
# refresh snap directly using this command
# path wont work in this case
print("Please update using snap package manager, i.e: `sudo snap refresh auto-cpufreq`.")
#check for AUR
elif IS_INSTALLED_WITH_AUR: print("Arch-based distribution with AUR support detected. Please refresh auto-cpufreq using your AUR helper.")
else:
is_new_update = check_for_update()
if not is_new_update: return
ans = input("Do you want to update auto-cpufreq to the latest release? [Y/n]: ").strip().lower()
if not os.path.exists(custom_dir): os.makedirs(custom_dir)
if os.path.exists(os.path.join(custom_dir, "auto-cpufreq")): rmtree(os.path.join(custom_dir, "auto-cpufreq"))
if ans in ['', 'y', 'yes']:
remove_daemon()
remove_complete_msg()
new_update(custom_dir)
print("enabling daemon")
run(["auto-cpufreq", "--install"])
print("auto-cpufreq is installed with the latest version")
run(["auto-cpufreq", "--version"])
else: print("Aborted")
elif remove:
root_check()
if IS_INSTALLED_WITH_SNAP:
run("snapctl set daemon=disabled", shell=True)
run("snapctl stop --disable auto-cpufreq", shell=True)
if auto_cpufreq_stats_path.exists():
if auto_cpufreq_stats_file is not None:
auto_cpufreq_stats_file.close()
auto_cpufreq_stats_path.unlink()
# ToDo:
# {the following snippet also used in --update, update it there too(if required)}
# * undo bluetooth boot disable
gnome_power_rm_reminder_snap()
else: remove_daemon()
remove_complete_msg()
elif stats:
not_running_daemon_check()
config_info_dialog()
print('\nNote: You can quit stats mode by pressing "ctrl+c"')
if os.getenv("PKG_MARKER") == "SNAP":
if IS_INSTALLED_WITH_SNAP:
gnome_power_detect_snap()
tlp_service_detect_snap()
else:
@ -149,11 +212,23 @@ def main(config, daemon, debug, update, install, remove, live, log, monitor, sta
tlp_service_detect()
battery_get_thresholds()
read_stats()
elif log: deprecated_log_msg()
elif get_state:
not_running_daemon_check()
override = get_override()
print(override)
elif completions:
if completions == "bash":
print("Run the below command in your current shell!\n")
print("echo 'eval \"$(_AUTO_CPUFREQ_COMPLETE=bash_source auto-cpufreq)\"' >> ~/.bashrc")
print("source ~/.bashrc")
elif completions == "zsh":
print("Run the below command in your current shell!\n")
print("echo 'eval \"$(_AUTO_CPUFREQ_COMPLETE=zsh_source auto-cpufreq)\"' >> ~/.zshrc")
print("source ~/.zshrc")
elif completions == "fish":
print("Run the below command in your current shell!\n")
print("echo '_AUTO_CPUFREQ_COMPLETE=fish_source auto-cpufreq | source' > ~/.config/fish/completions/auto-cpufreq.fish")
else: print("Invalid Option, try bash|zsh|fish as argument to --completions")
elif debug:
# ToDo: add status of GNOME Power Profile service status
config_info_dialog()
@ -172,7 +247,7 @@ def main(config, daemon, debug, update, install, remove, live, log, monitor, sta
print(f"Battery is: {'' if charging() else 'dis'}charging")
print()
app_res_use()
display_load()
get_load()
get_current_gov()
get_turbo()
footer()
@ -185,88 +260,7 @@ def main(config, daemon, debug, update, install, remove, live, log, monitor, sta
footer()
print("If auto-cpufreq helped you out and you find it useful ...\n")
print("Show your appreciation by donating!")
print("https://github.com/AdnanHodzic/auto-cpufreq/#donate")
print(GITHUB+"#donate")
footer()
elif install:
root_check()
if os.getenv("PKG_MARKER") == "SNAP":
running_daemon_check()
gnome_power_detect_snap()
tlp_service_detect_snap()
bluetooth_notif_snap()
gov_check()
run("snapctl set daemon=enabled", shell=True)
run("snapctl start --enable auto-cpufreq", shell=True)
else:
running_daemon_check()
gov_check()
deploy_daemon()
deploy_complete_msg()
elif remove:
root_check()
if os.getenv("PKG_MARKER") == "SNAP":
run("snapctl set daemon=disabled", shell=True)
run("snapctl stop --disable auto-cpufreq", shell=True)
if auto_cpufreq_stats_path.exists():
if auto_cpufreq_stats_file is not None:
auto_cpufreq_stats_file.close()
auto_cpufreq_stats_path.unlink()
# ToDo:
# {the following snippet also used in --update, update it there too(if required)}
# * undo bluetooth boot disable
gnome_power_rm_reminder_snap()
else: remove_daemon()
remove_complete_msg()
elif update:
root_check()
custom_dir = "/opt/auto-cpufreq/source"
for arg in sys.argv:
if arg.startswith("--update="):
custom_dir = arg.split("=")[1]
sys.argv.remove(arg)
if "--update" in sys.argv:
update = True
sys.argv.remove("--update")
if len(sys.argv) == 2: custom_dir = sys.argv[1]
if os.getenv("PKG_MARKER") == "SNAP":
print("Detected auto-cpufreq was installed using snap")
# refresh snap directly using this command
# path wont work in this case
print("Please update using snap package manager, i.e: `sudo snap refresh auto-cpufreq`.")
#check for AUR
elif subprocess.run(["bash", "-c", "command -v pacman >/dev/null 2>&1"]).returncode == 0 and subprocess.run(["bash", "-c", "pacman -Q auto-cpufreq >/dev/null 2>&1"]).returncode == 0:
print("Arch-based distribution with AUR support detected. Please refresh auto-cpufreq using your AUR helper.")
else:
is_new_update = check_for_update()
if not is_new_update: return
ans = input("Do you want to update auto-cpufreq to the latest release? [Y/n]: ").strip().lower()
if not os.path.exists(custom_dir): os.makedirs(custom_dir)
if os.path.exists(os.path.join(custom_dir, "auto-cpufreq")): rmtree(os.path.join(custom_dir, "auto-cpufreq"))
if ans in ['', 'y', 'yes']:
remove_daemon()
remove_complete_msg()
new_update(custom_dir)
print("enabling daemon")
run(["auto-cpufreq", "--install"])
print("auto-cpufreq is installed with the latest version")
run(["auto-cpufreq", "--version"])
else: print("Aborted")
elif completions:
if completions == "bash":
print("Run the below command in your current shell!\n")
print("echo 'eval \"$(_AUTO_CPUFREQ_COMPLETE=bash_source auto-cpufreq)\"' >> ~/.bashrc")
print("source ~/.bashrc")
elif completions == "zsh":
print("Run the below command in your current shell!\n")
print("echo 'eval \"$(_AUTO_CPUFREQ_COMPLETE=zsh_source auto-cpufreq)\"' >> ~/.zshrc")
print("source ~/.zshrc")
elif completions == "fish":
print("Run the below command in your current shell!\n")
print("echo '_AUTO_CPUFREQ_COMPLETE=fish_source auto-cpufreq | source' > ~/.config/fish/completions/auto-cpufreq.fish")
else: print("Invalid Option, try bash|zsh|fish as argument to --completions")
if __name__ == "__main__": main()

View File

@ -1,13 +1,8 @@
#!/usr/bin/env python3
import sys
sys.path.append("../")
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, GLib
from auto_cpufreq.gui.app import ToolWindow
def main():

View File

@ -1,9 +1,8 @@
import os, pyinotify, sys
from configparser import ConfigParser, ParsingError
from auto_cpufreq.utils.config_event_handler import ConfigEventHandler
import pyinotify
from subprocess import run, PIPE
import os
import sys
from auto_cpufreq.config.config_event_handler import ConfigEventHandler
def find_config_file(args_config_file) -> str:
"""
@ -56,16 +55,14 @@ class _Config:
self.watch_manager.add_watch(os.path.dirname(path), mask=mask)
if os.path.isfile(path): self.update_config()
def has_config(self) -> bool:
return os.path.isfile(self.path)
def has_config(self) -> bool: return os.path.isfile(self.path)
def get_config(self) -> ConfigParser:
return self._config
def get_config(self) -> ConfigParser: return self._config
def update_config(self) -> None:
# create new ConfigParser to prevent old data from remaining
self._config = ConfigParser()
try: self._config.read(self.path)
except ParsingError as e: print(f"The following error occured while parsing the config file: \n{e}")
except ParsingError as e: print(f"The following error occured while parsing the config file: \n{repr(e)}")
config = _Config()

View File

@ -0,0 +1,23 @@
from pyinotify import Event, ProcessEvent
class ConfigEventHandler(ProcessEvent):
def __init__(self, config) -> None:
self.config = config
def _process_update(self, event: Event):
if event.pathname.rstrip("~") == self.config.path: self.config.update_config()
# activates when auto-cpufreq config file is modified
def process_IN_MODIFY(self, event: Event) -> None: self._process_update(event)
# activates when auto-cpufreq config file is deleted
def process_IN_DELETE(self, event: Event) -> None: self._process_update(event)
# activates when auto-cpufreq config file is created
def process_IN_CREATE(self, event: Event) -> None: self._process_update(event)
# activates when auto-cpufreq config file is moved from watched directory
def process_IN_MOVED_FROM(self, event: Event) -> None: self._process_update(event)
# activates when auto-cpufreq config file is moved into the watched directory
def process_IN_MOVED_TO(self, event: Event) -> None: self._process_update(event)

File diff suppressed because it is too large Load Diff

12
auto_cpufreq/globals.py Normal file
View File

@ -0,0 +1,12 @@
from os import getenv, path
from subprocess import getoutput
ALL_GOVERNORS = ('performance', 'ondemand', 'conservative', 'schedutil', 'userspace', 'powersave') # from the highest performance to the lowest
AVAILABLE_GOVERNORS = getoutput('cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors').split(' ')
AVAILABLE_GOVERNORS_SORTED = tuple(filter(lambda gov: gov in AVAILABLE_GOVERNORS, ALL_GOVERNORS))
CONSERVATION_MODE_FILE = "/sys/bus/platform/drivers/ideapad_acpi/VPC2004:00/conservation_mode"
GITHUB = "https://github.com/AdnanHodzic/auto-cpufreq"
IS_INSTALLED_WITH_AUR = path.isfile("/etc/arch-release") and bool(getoutput("pacman -Qs auto-cpufreq"))
IS_INSTALLED_WITH_SNAP = getenv("PKG_MARKER") == "SNAP"
POWER_SUPPLY_DIR = "/sys/class/power_supply/"

View File

@ -1,27 +1,22 @@
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gdk, GdkPixbuf, Gio, GLib, Gtk
from gi.repository import Gtk, GLib, Gdk, Gio, GdkPixbuf
import os
import sys
from contextlib import redirect_stdout
from io import StringIO
from subprocess import run, PIPE
import shutil
from subprocess import PIPE, run
from threading import Thread
sys.path.append("../")
from auto_cpufreq.core import is_running, check_for_update, remove_daemon, new_update
from auto_cpufreq.gui.objects import RadioButtonView, SystemStatsLabel, CPUFreqStatsLabel, CurrentGovernorBox, DropDownMenu, DaemonNotRunningView, UpdateDialog
from auto_cpufreq.core import check_for_update, is_running
from auto_cpufreq.globals import GITHUB, IS_INSTALLED_WITH_SNAP
from auto_cpufreq.gui.objects import CPUFreqStatsLabel, CurrentGovernorBox, DaemonNotRunningView, DropDownMenu, RadioButtonView, SystemStatsLabel, UpdateDialog
if os.getenv("PKG_MARKER") == "SNAP":
ICON_FILE = "/snap/auto-cpufreq/current/icon.png"
if IS_INSTALLED_WITH_SNAP:
CSS_FILE = "/snap/auto-cpufreq/current/style.css"
ICON_FILE = "/snap/auto-cpufreq/current/icon.png"
else:
ICON_FILE = "/usr/local/share/auto-cpufreq/images/icon.png"
CSS_FILE = "/usr/local/share/auto-cpufreq/scripts/style.css"
ICON_FILE = "/usr/local/share/auto-cpufreq/images/icon.png"
HBOX_PADDING = 20
PKEXEC_ERROR = "Error executing command as another user: Not authorized\n\nThis incident has been reported.\n"
@ -67,7 +62,7 @@ class ToolWindow(Gtk.Window):
label = Gtk.Label(label="GUI not available due to Snap package confinement limitations.\nPlease install auto-cpufreq using auto-cpufreq-installer\nVisit the GitHub repo for more info")
label.set_justify(Gtk.Justification.CENTER)
button = Gtk.LinkButton.new_with_label(
uri="https://github.com/AdnanHodzic/auto-cpufreq",
uri=GITHUB,
label="GitHub Repo"
)
@ -102,7 +97,7 @@ class ToolWindow(Gtk.Window):
self.add(self.box)
def build(self):
if os.getenv("PKG_MARKER") == "SNAP": self.snap()
if IS_INSTALLED_WITH_SNAP: self.snap()
elif is_running("auto-cpufreq", "--daemon"): self.main()
else: self.daemon_not_running()

View File

@ -1,37 +1,31 @@
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, GdkPixbuf
from gi.repository import GdkPixbuf, Gtk
import sys
import os
import platform as pl
from concurrent.futures import ThreadPoolExecutor
sys.path.append("../../")
from subprocess import getoutput, run, PIPE
from auto_cpufreq.core import sysinfo, distro_info, set_override, get_override, get_formatted_version, dist_name, deploy_daemon, remove_daemon
from io import StringIO
from os.path import isfile
from platform import python_version
from subprocess import getoutput, PIPE, run
from auto_cpufreq.core import distro_info, get_formatted_version, get_override, sysinfo
from auto_cpufreq.globals import GITHUB, IS_INSTALLED_WITH_AUR, IS_INSTALLED_WITH_SNAP
PKEXEC_ERROR = "Error executing command as another user: Not authorized\n\nThis incident has been reported.\n"
auto_cpufreq_stats_path = ("/var/snap/auto-cpufreq/current" if os.getenv("PKG_MARKER") == "SNAP" else "/var/run") + "/auto-cpufreq.stats"
auto_cpufreq_stats_path = ("/var/snap/auto-cpufreq/current" if IS_INSTALLED_WITH_SNAP else "/var/run") + "/auto-cpufreq.stats"
def get_stats():
if os.path.isfile(auto_cpufreq_stats_path):
if isfile(auto_cpufreq_stats_path):
with open(auto_cpufreq_stats_path, "r") as file: stats = [line for line in (file.readlines() [-50:])]
return "".join(stats)
def get_version():
# snap package
if os.getenv("PKG_MARKER") == "SNAP": return getoutput(r"echo \(Snap\) $SNAP_VERSION")
if IS_INSTALLED_WITH_SNAP: return getoutput(r"echo \(Snap\) $SNAP_VERSION")
# aur package
elif dist_name in ["arch", "manjaro", "garuda"]:
aur_pkg_check = run("pacman -Qs auto-cpufreq > /dev/null", shell=True)
if aur_pkg_check == 1: return get_formatted_version()
else: return getoutput("pacman -Qi auto-cpufreq | grep Version")
elif IS_INSTALLED_WITH_AUR: return getoutput("pacman -Qi auto-cpufreq | grep Version")
else:
# source code (auto-cpufreq-installer)
try: return get_formatted_version()
@ -207,8 +201,8 @@ class AboutDialog(Gtk.Dialog):
self.image = Gtk.Image.new_from_pixbuf(img_buffer)
self.title = Gtk.Label(label="auto-cpufreq", name="bold")
self.version = Gtk.Label(label=app_version)
self.python = Gtk.Label(label=f"Python {pl.python_version()}")
self.github = Gtk.Label(label="https://github.com/AdnanHodzic/auto-cpufreq")
self.python = Gtk.Label(label=f"Python {python_version()}")
self.github = Gtk.Label(label=GITHUB)
self.license = Gtk.Label(label="Licensed under LGPL3", name="small")
self.love = Gtk.Label(label="Made with <3", name="small")

View File

@ -1,7 +1,5 @@
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, AppIndicator3 as appindicator
from subprocess import run

View File

@ -1,17 +1,17 @@
# * add status as one of the available options
# * alert user on snap if detected and how to remove first time live/stats message starts
# * if daemon is disabled and auto-cpufreq is removed (snap) remind user to enable it back
from logging import root
import os, sys, click, subprocess
import click
from shutil import which
from subprocess import getoutput, call, run, check_output, DEVNULL
from subprocess import call, DEVNULL, getoutput, STDOUT
from sys import argv
sys.path.append("../")
from auto_cpufreq.core import *
from auto_cpufreq.globals import GITHUB, IS_INSTALLED_WITH_SNAP
from auto_cpufreq.tlp_stat_parser import TLPStatusParser
# app_name var
app_name = "python3 power_helper.py" if sys.argv[0] == "power_helper.py" else "auto-cpufreq"
app_name = "python3 power_helper.py" if argv[0] == "power_helper.py" else "auto-cpufreq"
def header(): print("\n------------------------- auto-cpufreq: Power helper -------------------------\n")
def warning(): print("\n----------------------------------- Warning -----------------------------------\n")
@ -21,19 +21,19 @@ def helper_opts(): print("\nFor full list of options run: python3 power_helper.p
# used to check if binary exists on the system
def does_command_exists(cmd): return which(cmd) is not None
systemctl_exists = does_command_exists("systemctl")
bluetoothctl_exists = does_command_exists("bluetoothctl")
tlp_stat_exists = does_command_exists("tlp-stat")
powerprofilesctl_exists = does_command_exists("powerprofilesctl")
systemctl_exists = does_command_exists("systemctl")
tlp_stat_exists = does_command_exists("tlp-stat")
# detect if gnome power profile service is running
if os.getenv("PKG_MARKER") != "SNAP":
if not IS_INSTALLED_WITH_SNAP:
if systemctl_exists:
try: gnome_power_status = call(["systemctl", "is-active", "--quiet", "power-profiles-daemon"])
except:
print("\nUnable to determine init system")
print("If this causes any problems, please submit an issue:")
print("https://github.com/AdnanHodzic/auto-cpufreq/issues")
print(GITHUB+"/issues")
# alert in case TLP service is running
def tlp_service_detect():
@ -60,10 +60,10 @@ def gnome_power_detect():
print("Detected running GNOME Power Profiles daemon service!")
print("This daemon might interfere with auto-cpufreq and should be disabled.")
print("\nSteps to perform this action using auto-cpufreq: power_helper script:")
print("git clone https://github.com/AdnanHodzic/auto-cpufreq.git")
print(f"git clone {GITHUB}.git")
print("cd auto-cpufreq/auto_cpufreq")
print("python3 power_helper.py --gnome_power_disable")
print("\nReference: https://github.com/AdnanHodzic/auto-cpufreq#configuring-auto-cpufreq")
print(f"\nReference: {GITHUB}#configuring-auto-cpufreq")
# automatically disable gnome power profile service in case it's running during install
def gnome_power_detect_install():
@ -79,15 +79,15 @@ def gnome_power_detect_install():
def gnome_power_detect_snap():
warning()
print("Due to Snap package confinement limitations please consider installing auto-cpufreq using")
print("auto-cpufreq-installer: https://github.com/AdnanHodzic/auto-cpufreq/#auto-cpufreq-installer")
print(f"auto-cpufreq-installer: {GITHUB}#auto-cpufreq-installer")
print()
print("Unable to detect state of GNOME Power Profiles daemon service!")
print("This daemon might interfere with auto-cpufreq and should be disabled.")
print("\nSteps to perform this action using auto-cpufreq: power_helper script:")
print("git clone https://github.com/AdnanHodzic/auto-cpufreq.git")
print(f"git clone {GITHUB}.git")
print("cd auto-cpufreq/auto_cpufreq")
print("python3 power_helper.py --gnome_power_disable")
print("\nReference: https://github.com/AdnanHodzic/auto-cpufreq#configuring-auto-cpufreq")
print(f"\nReference: {GITHUB}#configuring-auto-cpufreq")
# stops gnome >= 40 power profiles (live)
def gnome_power_stop_live():
@ -111,7 +111,7 @@ def gnome_power_svc_enable():
except:
print("\nUnable to enable GNOME power profiles")
print("If this causes any problems, please submit an issue:")
print("https://github.com/AdnanHodzic/auto-cpufreq/issues")
print(GITHUB+"/issues")
# gnome power profiles current status
def gnome_power_svc_status():
@ -122,11 +122,11 @@ def gnome_power_svc_status():
except:
print("\nUnable to see GNOME power profiles status")
print("If this causes any problems, please submit an issue:")
print("https://github.com/AdnanHodzic/auto-cpufreq/issues")
print(GITHUB+"/issues")
# disable bluetooth on boot
def bluetooth_disable():
if os.getenv("PKG_MARKER") == "SNAP": bluetooth_notif_snap()
if IS_INSTALLED_WITH_SNAP: bluetooth_notif_snap()
elif bluetoothctl_exists:
print("* Turn off bluetooth on boot")
btconf = Path("/etc/bluetooth/main.conf")
@ -143,7 +143,7 @@ def bluetooth_disable():
# enable bluetooth on boot
def bluetooth_enable():
if os.getenv("PKG_MARKER") == "SNAP": bluetooth_on_notif_snap()
if IS_INSTALLED_WITH_SNAP: bluetooth_on_notif_snap()
if bluetoothctl_exists:
print("* Turn on bluetooth on boot")
btconf = "/etc/bluetooth/main.conf"
@ -183,10 +183,10 @@ def gnome_power_rm_reminder_snap():
print("Unable to detect state of GNOME Power Profiles daemon service!")
print("Now it's recommended to enable this service.")
print("\nSteps to perform this action using auto-cpufreq: power_helper script:")
print("git clone https://github.com/AdnanHodzic/auto-cpufreq.git")
print(f"git clone {GITHUB}.git")
print("cd auto-cpufreq/auto_cpufreq")
print("python3 power_helper.py --gnome_power_enable")
print("\nReference: https://github.com/AdnanHodzic/auto-cpufreq#configuring-auto-cpufreq")
print(f"\nReference: {GITHUB}#configuring-auto-cpufreq")
def valid_options():
print("--gnome_power_enable\t\tEnable GNOME Power Profiles daemon")
@ -203,7 +203,7 @@ def disable_power_profiles_daemon():
except:
print("\nUnable to disable GNOME power profiles")
print("If this causes any problems, please submit an issue:")
print("https://github.com/AdnanHodzic/auto-cpufreq/issues")
print(GITHUB+"/issues")
# default gnome_power_svc_disable func (balanced)
def gnome_power_svc_disable():
@ -213,8 +213,8 @@ def gnome_power_svc_disable():
try:
# check if snap package installed
snap_pkg_check = call(['snap', 'list', '|', 'grep', 'auto-cpufreq'],
stdout=subprocess.DEVNULL,
stderr=subprocess.STDOUT)
stdout=DEVNULL,
stderr=STDOUT)
# check if snapd is present and if snap package is installed | 0 is success
if not bool(snap_pkg_check):
print("GNOME Power Profiles Daemon is already disabled, it can be re-enabled by running:\n"
@ -262,7 +262,7 @@ def main(
root_check()
header()
if len(sys.argv) == 1: print('Unrecognized option!\n\nRun: "' + app_name + ' --help" for list of available options.')
if len(argv) == 1: print('Unrecognized option!\n\nRun: "' + app_name + ' --help" for list of available options.')
else:
if gnome_power_enable: gnome_power_svc_enable()
elif gnome_power_disable: gnome_power_svc_disable()

View File

@ -1,29 +0,0 @@
import pyinotify
class ConfigEventHandler(pyinotify.ProcessEvent):
def __init__(self, config) -> None:
self.config = config
def _process_update(self, event: pyinotify.Event):
if event.pathname.rstrip("~") == self.config.path:
self.config.update_config()
# activates when auto-cpufreq config file is modified
def process_IN_MODIFY(self, event: pyinotify.Event) -> None:
self._process_update(event)
# activates when auto-cpufreq config file is deleted
def process_IN_DELETE(self, event: pyinotify.Event) -> None:
self._process_update(event)
# activates when auto-cpufreq config file is created
def process_IN_CREATE(self, event: pyinotify.Event) -> None:
self._process_update(event)
# activates when auto-cpufreq config file is moved from watched directory
def process_IN_MOVED_FROM(self, event: pyinotify.Event) -> None:
self._process_update(event)
# activates when auto-cpufreq config file is moved into the watched directory
def process_IN_MOVED_TO(self, event: pyinotify.Event) -> None:
self._process_update(event)

View File

@ -1,23 +1,16 @@
diff --git a/auto_cpufreq/core.py b/auto_cpufreq/core.py
index 99397a9..16869ab 100755
index 6ee9986..5015982 100755
--- a/auto_cpufreq/core.py
+++ b/auto_cpufreq/core.py
@@ -350,29 +350,12 @@ def get_current_gov():
@@ -260,18 +260,12 @@ def get_current_gov():
)
def cpufreqctl():
- """
- deploy cpufreqctl script
- deploy cpufreqctl.auto-cpufreq script
- """
-
- # detect if running on a SNAP
- if os.getenv("PKG_MARKER") == "SNAP":
- pass
- else:
- # deploy cpufreqctl.auto-cpufreq script
- if not os.path.isfile("/usr/local/bin/cpufreqctl.auto-cpufreq"):
- shutil.copy(SCRIPTS_DIR / "cpufreqctl.sh", "/usr/local/bin/cpufreqctl.auto-cpufreq")
-
- if not (IS_INSTALLED_WITH_SNAP or os.path.isfile("/usr/local/bin/cpufreqctl.auto-cpufreq")):
- copy(SCRIPTS_DIR / "cpufreqctl.sh", "/usr/local/bin/cpufreqctl.auto-cpufreq")
+ # scripts are already in the correct place
+ pass
@ -25,55 +18,48 @@ index 99397a9..16869ab 100755
- """
- remove cpufreqctl.auto-cpufreq script
- """
- # detect if running on a SNAP
- if os.getenv("PKG_MARKER") == "SNAP":
- pass
- else:
- if os.path.isfile("/usr/local/bin/cpufreqctl.auto-cpufreq"):
- os.remove("/usr/local/bin/cpufreqctl.auto-cpufreq")
- if not IS_INSTALLED_WITH_SNAP and os.path.isfile("/usr/local/bin/cpufreqctl.auto-cpufreq"):
- os.remove("/usr/local/bin/cpufreqctl.auto-cpufreq")
+ #no need to restore
+ pass
def footer(l=79): print("\n" + "-" * l + "\n")
def footer(l=79):
@@ -400,30 +383,8 @@ def remove_complete_msg():
@@ -287,27 +281,8 @@ def remove_complete_msg():
footer()
def deploy_daemon():
- print("\n" + "-" * 21 + " Deploying auto-cpufreq as a daemon " + "-" * 22 + "\n")
-
- # deploy cpufreqctl script func call
- cpufreqctl()
- cpufreqctl() # deploy cpufreqctl script func call
-
- # turn off bluetooth on boot
- bluetooth_disable()
- bluetooth_disable() # turn off bluetooth on boot
-
- auto_cpufreq_stats_path.touch(exist_ok=True)
-
- print("\n* Deploy auto-cpufreq install script")
- shutil.copy(SCRIPTS_DIR / "auto-cpufreq-install.sh", "/usr/local/bin/auto-cpufreq-install")
- copy(SCRIPTS_DIR / "auto-cpufreq-install.sh", "/usr/local/bin/auto-cpufreq-install")
-
- print("\n* Deploy auto-cpufreq remove script")
- shutil.copy(SCRIPTS_DIR / "auto-cpufreq-remove.sh", "/usr/local/bin/auto-cpufreq-remove")
- copy(SCRIPTS_DIR / "auto-cpufreq-remove.sh", "/usr/local/bin/auto-cpufreq-remove")
-
- # output warning if gnome power profile is running
- gnome_power_detect_install()
- gnome_power_svc_disable()
-
- # output warning if TLP service is detected
- tlp_service_detect()
- tlp_service_detect() # output warning if TLP service is detected
-
- call("/usr/local/bin/auto-cpufreq-install", shell=True)
+ # prevent needless copying and system changes
+ pass
def deploy_daemon_performance():
@@ -463,40 +424,7 @@ def deploy_daemon_performance():
print("\n" + "-" * 21 + " Deploying auto-cpufreq as a daemon (performance) " + "-" * 22 + "\n")
@@ -339,35 +314,7 @@ def deploy_daemon_performance():
# remove auto-cpufreq daemon
def remove_daemon():
-
call("/usr/local/bin/auto-cpufreq-install", shell=True)
-def remove_daemon():
- # check if auto-cpufreq is installed
- if not os.path.exists("/usr/local/bin/auto-cpufreq-remove"):
- print("\nauto-cpufreq daemon is not installed.\n")
@ -81,8 +67,7 @@ index 99397a9..16869ab 100755
-
- print("\n" + "-" * 21 + " Removing auto-cpufreq daemon " + "-" * 22 + "\n")
-
- # turn on bluetooth on boot
- bluetooth_enable()
- bluetooth_enable() # turn on bluetooth on boot
-
- # output warning if gnome power profile is stopped
- gnome_power_rm_reminder()
@ -95,19 +80,15 @@ index 99397a9..16869ab 100755
- os.remove("/usr/local/bin/auto-cpufreq-remove")
-
- # delete override pickle if it exists
- if os.path.exists(governor_override_state):
- os.remove(governor_override_state)
- if os.path.exists(governor_override_state): os.remove(governor_override_state)
-
- # delete stats file
- if auto_cpufreq_stats_path.exists():
- if auto_cpufreq_stats_file is not None:
- auto_cpufreq_stats_file.close()
-
- if auto_cpufreq_stats_file is not None: auto_cpufreq_stats_file.close()
- auto_cpufreq_stats_path.unlink()
-
- # restore original cpufrectl script
- cpufreqctl_restore()
+ pass
- cpufreqctl_restore() # restore original cpufrectl script
+def remove_daemon(): pass
def gov_check():
for gov in AVAILABLE_GOVERNORS: