├── automathemely ├── bin │ ├── __init__.py │ ├── kde-refresh-gtk2 │ ├── systemd-trigger.sh │ ├── kde-refresh-gtk2.c │ ├── autothscheduler.py │ └── run.py ├── autoth_tools │ ├── __init__.py │ ├── utils.py │ ├── argmanager.py │ ├── updsuntimes.py │ ├── extratools.py │ ├── envspecific.py │ └── settsmanager.py ├── lib │ ├── installation_files │ │ ├── sun-times.timer │ │ ├── autostart.desktop │ │ └── sun-times.service │ ├── automathemely.desktop │ ├── default_user_settings.json │ ├── automathemely_large.svg │ └── automathemely.svg └── __init__.py ├── .gitignore ├── install_scripts ├── preremove.sh ├── .package.sh └── postinst.sh ├── setup.py ├── README.md └── LICENSE /automathemely/bin/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /automathemely/autoth_tools/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /automathemely/bin/kde-refresh-gtk2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/C2N14/AutomaThemely/HEAD/automathemely/bin/kde-refresh-gtk2 -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | venv/ 2 | .idea/ 3 | .vscode/ 4 | releases/ 5 | build/ 6 | *.egg-info/ 7 | *.egg 8 | *__pycache__/ 9 | *.pyc 10 | *.py[cod] 11 | -------------------------------------------------------------------------------- /automathemely/lib/installation_files/sun-times.timer: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=Update automathemely sun times daily 3 | 4 | [Timer] 5 | OnCalendar=daily 6 | Persistent=true 7 | 8 | [Install] 9 | WantedBy=timers.target 10 | -------------------------------------------------------------------------------- /automathemely/lib/installation_files/autostart.desktop: -------------------------------------------------------------------------------- 1 | [Desktop Entry] 2 | Type=Application 3 | Name=AutomaThemely 4 | Comment=Python application for changing between desktop themes periodically. 5 | Exec=/usr/bin/env python3 /bin/autothscheduler.py 6 | Icon=automathemely 7 | Name[en_US]=autostart.desktop 8 | -------------------------------------------------------------------------------- /automathemely/lib/installation_files/sun-times.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=Update automathemely sun times daily 3 | After=network-online.target 4 | Wants=network-online.target 5 | 6 | [Service] 7 | Type=oneshot 8 | ExecStart=/bin/bash /bin/systemd-trigger.sh "/.config/automathemely/sun_times" "/usr/bin/env python3 /autoth_tools/updsuntimes.py" 9 | -------------------------------------------------------------------------------- /automathemely/bin/systemd-trigger.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Compare last modified date of first arg to current date before executing the second arg, this is needed because to 3 | # make sure it runs every boot AND daily, Persistent=true is needed, but it will try to run several times if several 4 | # days have passed since the last boot. 5 | # 6 | # First tried adding it as a one liner to ExecStart but it failed to run stat, cut and date even with /bin/bash -c 7 | if [ "$(stat -c %y "$(echo ~)$1" | cut -f 1 -d " ")" != "$(date +%F)" ]; then 8 | eval $2 9 | fi 10 | -------------------------------------------------------------------------------- /automathemely/lib/automathemely.desktop: -------------------------------------------------------------------------------- 1 | [Desktop Entry] 2 | Type=Application 3 | Name=AutomaThemely 4 | Comment=Python application for changing between desktop themes periodically. 5 | Exec=automathemely --manage 6 | Icon=automathemely 7 | Terminal=false 8 | StartupNotify=false 9 | Actions=Run;Update;Restart; 10 | 11 | [Desktop Action Run] 12 | Exec=automathemely 13 | Name=Run AutomaThemely 14 | 15 | [Desktop Action Update] 16 | Exec=automathemely --update 17 | Name= Update sun times 18 | 19 | [Desktop Action Restart] 20 | Exec=automathemely --restart 21 | Name= Restart the scheduler 22 | -------------------------------------------------------------------------------- /automathemely/bin/kde-refresh-gtk2.c: -------------------------------------------------------------------------------- 1 | #include 2 | //#include 3 | 4 | // This has to be compiled with `pkg-config --cflags --libs gtk+-2.0` 5 | 6 | GdkEventClient createEvent() 7 | { 8 | GdkEventClient event; 9 | event.type = GDK_CLIENT_EVENT; 10 | event.send_event = TRUE; 11 | event.window = NULL; 12 | event.message_type = gdk_atom_intern("_GTK_READ_RCFILES", FALSE); 13 | event.data_format = 8; 14 | 15 | return event; 16 | } 17 | 18 | int main(int argc, char** argv) 19 | { 20 | gtk_init(&argc, &argv); 21 | 22 | GdkEventClient event = createEvent(); 23 | // This function isn't available in PyGObject so that's why we need this additional c program 24 | gdk_event_send_clientmessage_toall((GdkEvent *)&event); 25 | return 0; 26 | } -------------------------------------------------------------------------------- /install_scripts/preremove.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | pkill -f "autothscheduler.py" 4 | 5 | 6 | local_install=false 7 | ## CHECK FOR ROOT PRIVILEGES 8 | if ((${EUID:-0} || "$(id -u)")); then 9 | 10 | if [[ -z "$SUDO_USER" ]]; then 11 | echo "SUDO_USER variable not found, trying to find user manually..." 12 | SUDO_USER=$(logname) 13 | SUDO_UID=$(id -u ${SUDO_USER}) 14 | 15 | if [[ -z "$SUDO_USER" ]]; then 16 | echo "Could not find SUDO_USER, trying to remove local installation..." 17 | local_install=true 18 | fi 19 | 20 | fi 21 | 22 | else 23 | echo "Root privileges not detected, trying to remove local installation..." 24 | local_install=true 25 | 26 | fi 27 | 28 | 29 | if [[ "$local_install" = true ]]; then 30 | systemctl --user stop automathemely.timer 31 | systemctl --user disable automathemely.timer 32 | systemctl --user daemon-reload 33 | 34 | else 35 | # Export some vars required to make some systemd user commands work 36 | export XDG_RUNTIME_DIR="/run/user/${SUDO_UID}" 37 | export DBUS_SESSION_BUS_ADDRESS="unix:path=${XDG_RUNTIME_DIR}/bus" 38 | 39 | sudo -E -u ${SUDO_USER} systemctl --user --global stop automathemely.timer 40 | sudo systemctl --global disable automathemely.timer 41 | sudo -E -u ${SUDO_USER} systemctl --user --global daemon-reload 42 | 43 | fi 44 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | from setuptools import setup 4 | 5 | from automathemely import __version__ as version 6 | 7 | 8 | def get_package_files(directory): 9 | paths = [] 10 | for (path, directories, filenames) in os.walk(directory): 11 | for filename in filenames: 12 | paths.append(os.path.join('..', path, filename)) 13 | return paths 14 | 15 | 16 | with open('README.md') as fh: 17 | long_description = fh.read() 18 | 19 | setup( 20 | name='AutomaThemely', 21 | version=version, 22 | description='Simple, set-and-forget python application for changing between desktop themes according to light and ' 23 | 'dark hours', 24 | long_description=long_description, 25 | author='Adrian Salgado', 26 | author_email='adriansalmar@gmail.com', 27 | url='https://github.com/C2N14/AutomaThemely', 28 | license='GPLv3', 29 | packages=['automathemely', 'automathemely.bin', 'automathemely.autoth_tools'], 30 | python_requires='>=3.5', 31 | install_requires=['requests', 'astral', 'pytz', 'tzlocal', 'schedule'], 32 | include_package_data=True, 33 | package_data={ 34 | 'automathemely': get_package_files('automathemely/lib') 35 | + ['../automathemely/bin/systemd-trigger.sh'] + ['../automathemely/bin/kde-refresh-gtk2']}, 36 | data_files=[ 37 | ('share/icons/hicolor/scalable/apps', ['automathemely/lib/automathemely.svg']), 38 | ('share/applications', ['automathemely/lib/automathemely.desktop']) 39 | ], 40 | entry_points={ 41 | 'console_scripts': [ 42 | 'automathemely=automathemely.bin.run:main' 43 | ], 44 | }, 45 | ) 46 | -------------------------------------------------------------------------------- /install_scripts/.package.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if_not_dir_create () { 4 | if [ ! -d "$1" ]; then 5 | mkdir -p "$1" 6 | fi 7 | } 8 | 9 | declare -a outputs=("deb" "rpm" "sh") 10 | declare -a pypacks=("astral" "requests" "tz" "tzlocal" "schedule") 11 | declare -a otherdeps=("python3-pip") 12 | declare -a python_versions=("3.5" "3.6") 13 | 14 | declare -a original_files=(*) 15 | 16 | deps="" 17 | for p in "${pypacks[@]}" 18 | do 19 | deps="$deps-d python3-$p " 20 | done 21 | 22 | for d in "${otherdeps[@]}" 23 | do 24 | deps="$deps-d $d " 25 | done 26 | 27 | for pyth_v in "${python_versions[@]}"; do 28 | # NO_DEPS PACKAGING 29 | for out in "${outputs[@]}" 30 | do 31 | fpm -s python -t "${out}" -f -n 'automathemely' --python-bin python${pyth_v} --python-pip pip3 \ 32 | --python-package-name-prefix python3 --no-python-dependencies --after-install postinst.sh \ 33 | --before-remove preremove.sh ../setup.py 34 | done 35 | 36 | for file in *; do 37 | if [[ ! " ${original_files[@]} " =~ " ${file} " ]]; then 38 | mv "$file" "no_deps-${file}" 39 | fi 40 | done 41 | 42 | # DEPS PACKAGING 43 | for out in "${outputs[@]}" 44 | do 45 | fpm -s python -t "${out}" -f -n 'automathemely' --python-bin python${pyth_v} --python-pip pip3 \ 46 | --python-package-name-prefix python3 --no-python-dependencies ${deps}--after-install postinst.sh \ 47 | --before-remove preremove.sh ../setup.py 48 | done 49 | 50 | for file in *; do 51 | if [[ ! " ${original_files[@]} " =~ " ${file} " ]]; then 52 | mv "$file" "python${pyth_v}-${file}" 53 | fi 54 | done 55 | 56 | version="$(echo python${pyth_v}-automathemely*.deb | grep -o -P '(?<=_).*(?=_)')" 57 | 58 | if [ "$version" != "" ] 59 | then 60 | if_not_dir_create "../releases/python${pyth_v}/v$version" 61 | mv *automathemely* "../releases/python${pyth_v}/v$version" 62 | fi 63 | done -------------------------------------------------------------------------------- /automathemely/__init__.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from pathlib import Path 3 | from sys import stdout, stderr 4 | from automathemely.autoth_tools.utils import get_local, notify 5 | 6 | _ROOT = str(Path(__file__).resolve().parent) 7 | __version__ = "1.3.0-dev1" 8 | 9 | 10 | # Move/rename older local config directory name to the new lowercase one 11 | if Path.home().joinpath('.config', 'AutomaThemely').is_dir(): 12 | import shutil 13 | shutil.move(str(Path.home().joinpath('.config', 'AutomaThemely')), get_local()) 14 | 15 | # Create user config dir if it doesn't exist already 16 | Path(get_local()).mkdir(parents=True, exist_ok=True) 17 | 18 | 19 | # Custom Handler to pass logs as notifications 20 | class NotifyHandler(logging.StreamHandler): 21 | def emit(self, record): 22 | message = self.format(record) 23 | notify(message) 24 | 25 | 26 | # noinspection SpellCheckingInspection 27 | default_simple_format = '%(levelname)s: %(message)s' 28 | # noinspection SpellCheckingInspection 29 | timed_details_format = '(%(asctime)s) (%(filename)s:%(funcName)s:%(lineno)s) %(levelname)s: %(message)s' 30 | 31 | # Setup logging levels/handlers 32 | main_file_handler = logging.FileHandler(get_local('automathemely.log'), mode='w') 33 | updsun_file_handler = logging.FileHandler(get_local('.updsuntimes.log'), mode='w') 34 | scheduler_file_handler = logging.FileHandler(get_local('.autothscheduler.log'), mode='w') 35 | info_or_lower_handler = logging.StreamHandler(stdout) 36 | info_or_lower_handler.setLevel(logging.DEBUG) 37 | info_or_lower_handler.addFilter(lambda log: log.levelno <= logging.INFO) 38 | warning_or_higher_handler = logging.StreamHandler(stderr) 39 | warning_or_higher_handler.setLevel(logging.WARNING) 40 | # This will be added in run.py if notifications are enabled 41 | # TODO: Figure out a better way to handle notifications that is as flexible as this that doesn't spam the user in case 42 | # one of the imported libraries malfunctions and decides to also use this root logger 43 | notifier_handler = NotifyHandler() 44 | notifier_handler.setLevel(logging.INFO) 45 | 46 | # Setup root logger 47 | # noinspection SpellCheckingInspection 48 | logging.basicConfig( 49 | # filename=get_local('automathemely.log'), 50 | # filemode='w', 51 | # level=logging.DEBUG, 52 | level=logging.DEBUG, 53 | handlers=(main_file_handler, 54 | info_or_lower_handler, 55 | warning_or_higher_handler, 56 | # notifier_handler 57 | ), 58 | # format='%(levelname)s (%(name)s - %(funcname)s): %(message)s' 59 | format=default_simple_format 60 | ) 61 | -------------------------------------------------------------------------------- /automathemely/autoth_tools/utils.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | import collections 3 | 4 | 5 | # PATH RELATED FUNCTIONS 6 | def get_resource(path=''): 7 | from automathemely import _ROOT 8 | return str(Path(_ROOT).joinpath('lib', path)) 9 | 10 | 11 | def get_bin(path=''): 12 | from automathemely import _ROOT 13 | return str(Path(_ROOT).joinpath('bin', path)) 14 | 15 | 16 | def get_local(path=''): 17 | return str(Path.home().joinpath('.config', 'automathemely', path)) 18 | 19 | 20 | def get_root(path=''): 21 | from automathemely import _ROOT 22 | return str(Path(_ROOT).joinpath(path)) 23 | 24 | 25 | # DICT RELATED FUNCTIONS 26 | def read_dict(dic, keys): 27 | for k in keys: 28 | try: 29 | dic = dic[k] 30 | except KeyError: 31 | return 32 | return dic 33 | 34 | 35 | def write_dic(dic, keys, value): 36 | for key in keys[:-1]: 37 | dic = dic.setdefault(key, {}) 38 | dic[keys[-1]] = value 39 | 40 | 41 | def update_dict(d, u): 42 | for k, v in u.items(): 43 | if isinstance(v, collections.Mapping): 44 | d[k] = update_dict(d.get(k, {}), v) 45 | else: 46 | d[k] = v 47 | return d 48 | 49 | 50 | # MISC FUNCTIONS 51 | def notify(message, title='AutomaThemely'): 52 | import gi 53 | gi.require_version('Notify', '0.7') 54 | from gi.repository import Notify, GLib 55 | 56 | if not Notify.is_initted(): 57 | Notify.init('AutomaThemely') 58 | 59 | n = Notify.Notification.new(title, message, get_resource('automathemely.svg')) 60 | try: # I don't even know... https://bugzilla.redhat.com/show_bug.cgi?id=1582833 61 | n.show() 62 | except GLib.GError as e: 63 | if str(e) != 'g-dbus-error-quark: Unexpected reply type (16)' \ 64 | and str(e) != 'g-dbus-error-quark: GDBus.Error:org.freedesktop.DBus.Error.NoReply: Message recipient ' \ 65 | 'disconnected from message bus without replying (4)': 66 | raise e 67 | 68 | 69 | def pgrep(process_names, use_full=False): 70 | from subprocess import run, DEVNULL 71 | command = ['pgrep'] 72 | if use_full: 73 | command.append('-f') 74 | for p_name in process_names: 75 | p_command = command + [p_name] 76 | p = run(p_command, stdout=DEVNULL) 77 | if p.returncode == 0: 78 | return True 79 | 80 | 81 | def verify_desktop_session(wait=False): 82 | import time 83 | while True: 84 | # noinspection SpellCheckingInspection 85 | if pgrep(['gnome-session', 'plasmashell', 'cinnamon-sessio', 'xfce4-session']): 86 | if not wait: 87 | return True 88 | break 89 | else: 90 | if not wait: 91 | return False 92 | time.sleep(1) 93 | -------------------------------------------------------------------------------- /automathemely/bin/autothscheduler.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import logging 3 | import time 4 | from datetime import datetime 5 | 6 | from schedule import Scheduler, CancelJob 7 | 8 | from automathemely import info_or_lower_handler, warning_or_higher_handler, scheduler_file_handler, timed_details_format 9 | from automathemely.autoth_tools.utils import get_local 10 | 11 | logger = logging.getLogger('autothscheduler.py') 12 | logger.propagate = False 13 | 14 | logger.addHandler(scheduler_file_handler) 15 | logger.addHandler(info_or_lower_handler) 16 | logger.addHandler(warning_or_higher_handler) 17 | 18 | for handler in logger.handlers[:]: 19 | handler.setFormatter(logging.Formatter(timed_details_format)) 20 | 21 | 22 | def get_next_run(): 23 | import pickle 24 | import tzlocal 25 | import pytz 26 | try: 27 | with open(get_local('sun_times'), 'rb') as file: 28 | sunrise, sunset = pickle.load(file) 29 | except FileNotFoundError: 30 | import sys 31 | logger.error('Could not find times file, exiting...') 32 | sys.exit() 33 | 34 | now = datetime.now(pytz.utc).astimezone(tzlocal.get_localzone()).time() 35 | sunrise, sunset = (sunrise.astimezone(tzlocal.get_localzone()).time(), 36 | sunset.astimezone(tzlocal.get_localzone()).time()) 37 | 38 | if sunrise < now < sunset: 39 | return ':'.join(str(sunset).split(':')[:-1]) 40 | else: 41 | return ':'.join(str(sunrise).split(':')[:-1]) 42 | 43 | 44 | def run_automathemely(): 45 | from automathemely.autoth_tools.utils import verify_desktop_session 46 | # You can't change the theme if the desktop session is not active (E. g. when you close a laptop's lid) 47 | verify_desktop_session(True) 48 | 49 | from subprocess import check_output, PIPE 50 | try: 51 | check_output('automathemely', stderr=PIPE) 52 | except Exception as e: 53 | logger.exception('Exception while running AutomaThemely', exc_info=e) 54 | 55 | return CancelJob 56 | 57 | 58 | class SafeScheduler(Scheduler): 59 | def __init__(self, reschedule_on_failure=False): 60 | self.reschedule_on_failure = reschedule_on_failure 61 | super().__init__() 62 | 63 | def _run_job(self, job): 64 | # noinspection PyBroadException 65 | try: 66 | super()._run_job(job) 67 | except Exception as e: 68 | logger.exception('Exception while running AutomaThemely', exc_info=e) 69 | job.last_run = datetime.now() 70 | # job._schedule_next_run() 71 | 72 | 73 | scheduler = SafeScheduler() 74 | 75 | while True: 76 | scheduler.every().day.at(get_next_run()).do(run_automathemely()) 77 | 78 | while True: 79 | if not scheduler.jobs: 80 | logger.info('Running...') 81 | break 82 | scheduler.run_pending() 83 | time.sleep(1) 84 | -------------------------------------------------------------------------------- /automathemely/lib/default_user_settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "1.3.0-dev1", 3 | "desktop_environment": "custom", 4 | "themes": { 5 | "gnome": { 6 | "light": { 7 | "gtk": "", 8 | "icons": "", 9 | "shell": "" 10 | }, 11 | "dark": { 12 | "gtk": "", 13 | "icons": "", 14 | "shell": "" 15 | } 16 | }, 17 | "kde": { 18 | "light": { 19 | "lookandfeel": "", 20 | "gtk": "" 21 | }, 22 | "dark": { 23 | "lookandfeel": "", 24 | "gtk": "" 25 | } 26 | }, 27 | "xfce": { 28 | "light": { 29 | "gtk": "", 30 | "icons": "" 31 | }, 32 | "dark": { 33 | "gtk": "", 34 | "icons": "" 35 | } 36 | }, 37 | "cinnamon": { 38 | "light": { 39 | "gtk": "", 40 | "desktop": "", 41 | "icons": "" 42 | }, 43 | "dark": { 44 | "gtk": "", 45 | "desktop": "", 46 | "icons": "" 47 | } 48 | } 49 | }, 50 | "offset": { 51 | "sunrise": 0, 52 | "sunset": 0 53 | }, 54 | "location": { 55 | "auto_enabled": true, 56 | "manual": { 57 | "city": "", 58 | "region": "", 59 | "latitude": 0.0, 60 | "longitude": 0.0, 61 | "time_zone": "" 62 | } 63 | }, 64 | "misc": { 65 | "notifications": true 66 | }, 67 | "extras": { 68 | "atom": { 69 | "enabled": false, 70 | "themes": { 71 | "light": { 72 | "theme": "", 73 | "syntax": "" 74 | }, 75 | "dark": { 76 | "theme": "", 77 | "syntax": "" 78 | } 79 | } 80 | }, 81 | "vscode": { 82 | "enabled": false, 83 | "themes": { 84 | "light": "", 85 | "dark": "" 86 | }, 87 | "custom_config_dir": "" 88 | }, 89 | "scripts": { 90 | "sunrise": { 91 | "1": "", 92 | "2": "", 93 | "3": "", 94 | "4": "", 95 | "5": "" 96 | }, 97 | "sunset": { 98 | "1": "", 99 | "2": "", 100 | "3": "", 101 | "4": "", 102 | "5": "" 103 | } 104 | } 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /install_scripts/postinst.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | packdir="$(python3 -m pip show automathemely | grep -oP "^Location: \K.*")/automathemely" 4 | 5 | if_not_dir_create () { 6 | if [[ ! -d "$1" ]]; then 7 | mkdir -p "$1" 8 | fi 9 | } 10 | 11 | 12 | local_install=false 13 | ## CHECK FOR ROOT PRIVILEGES 14 | if ((${EUID:-0} || "$(id -u)")); then 15 | 16 | if [[ -z "$SUDO_USER" ]]; then 17 | echo "SUDO_USER variable not found, trying to find user manually..." 18 | SUDO_USER=$(logname) 19 | SUDO_UID=$(id -u ${SUDO_USER}) 20 | 21 | if [[ -z "$SUDO_USER" ]]; then 22 | echo "Could not find SUDO_USER, falling back to local only installation..." 23 | local_install=true 24 | fi 25 | 26 | fi 27 | 28 | else 29 | echo "Root privileges not detected, falling back to local only installation..." 30 | local_install=true 31 | 32 | fi 33 | 34 | 35 | ## SET RELEVANT VARIABLES 36 | if [[ "$local_install" = true ]]; then 37 | autostart_path="$HOME/.config/autostart" 38 | systemd_user_path="$HOME/.config/systemd/user" 39 | echo "NOTE: AutomaThemely is disabled from autostarting by default on local installation" 40 | 41 | else 42 | autostart_path="/etc/xdg/autostart" 43 | systemd_user_path="/usr/lib/systemd/user" 44 | 45 | fi 46 | 47 | 48 | ## MOVE FILES TO LOCATIONS 49 | # Autostart on user log in 50 | if_not_dir_create "$autostart_path" 51 | cp "$packdir/installation_files/autostart.desktop" "$autostart_path/automathemely.desktop" 52 | sed -i "s||$packdir|g" "$autostart_path/automathemely.desktop" 53 | 54 | # Timer & service units 55 | if_not_dir_create "$systemd_user_path" 56 | cp "$packdir/installation_files/sun-times.timer" "$systemd_user_path/automathemely.timer" 57 | cp "$packdir/installation_files/sun-times.service" "$systemd_user_path/automathemely.service" 58 | sed -i "s||$packdir|g" "$systemd_user_path/automathemely.service" 59 | 60 | 61 | ## ENABLE SYSTEMD 62 | if [[ "$local_install" = true ]]; then 63 | systemctl --user daemon-reload 64 | systemctl --user enable automathemely.timer 65 | systemctl --user start automathemely.timer 66 | 67 | else 68 | # Export some vars required to make some systemd user commands work 69 | export XDG_RUNTIME_DIR="/run/user/${SUDO_UID}" 70 | export DBUS_SESSION_BUS_ADDRESS="unix:path=${XDG_RUNTIME_DIR}/bus" 71 | 72 | sudo -E -u ${SUDO_USER} systemctl --user --global daemon-reload 73 | sudo systemctl --global enable automathemely.timer 74 | sudo -E -u ${SUDO_USER} systemctl --user --global start automathemely.timer 75 | 76 | fi 77 | 78 | 79 | ## REMOVE OBSOLETE STUFF 80 | # Crontab removal 81 | # If crontabs are not installed carries on 82 | (crontab -u ${SUDO_USER} -l | awk ' !/sunrise_change_theme/ && !/sunset_change_theme/ && !/update_sunhours_daily/ && !/update_sunhours_reboot/ { print }' | crontab -u ${SUDO_USER} -) || true 83 | 84 | -------------------------------------------------------------------------------- /automathemely/lib/automathemely_large.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | image/svg+xml 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /automathemely/lib/automathemely.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | image/svg+xml 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | ![AutomaThemely icon](automathemely/lib/automathemely_large.svg) 3 | 4 | # AutomaThemely 5 | 6 | Simple, set-and-forget python application for changing between desktop themes according to light and dark hours 7 | 8 | ![AutomaThemly Screenshot](https://user-images.githubusercontent.com/29585778/50742182-de28f880-11c4-11e9-8039-4bfd20426a21.png) 9 | 10 | 11 | ## Current supported desktop environments 12 | 13 | Right now, these desktop environments are supported natively: 14 | 15 | * GNOME and other GNOME based or similar such as Unity 16 | * KDE Plasma 17 | * XFCE 18 | * Cinnamon 19 | 20 | Additionally, wether your DE is listed above or not, you can also create and add your own scripts. 21 | 22 | Thus you can add support it even if not listed above (although if you'd like to see it integrated in a later version you can always make a suggestion by [oppening an issue](https://github.com/C2N14/AutomaThemely/issues)). 23 | 24 | ## Getting Started 25 | 26 | ### Prerequisites 27 | 28 | * Python 3.5+ 29 | * GTK 3.10+ 30 | * pip3 (will be installed if package with dependencies is installed, otherwise it must be manually installed. More details below) 31 | 32 | ### Installing 33 | 34 | #### Releases 35 | 36 | Go to [releases](https://github.com/C2N14/AutomaThemely/releases) and download whichever package suits your needs 37 | 38 | Because of the several python versions different distros have, and the current state and limitations of the packager used, here are my recommendations for the following distros: 39 | 40 | | Distro | Recommendation | 41 | | --- | --- | 42 | | Ubuntu 16.04 | Manually install all the python dependencies with pip3 and install the python 3.5 no dependencies package | 43 | | Ubuntu 18.04 | Just install the regular python 3.6 package and all the dependencies should be available | 44 | | Other distros | Check your python version, and if it is equal or above 3.5 but not listed in the releases page you can try [packaging it yourself](https://github.com/C2N14/AutomaThemely/wiki/Packaging-it-yourself) 45 | 46 | #### Packages 47 | 48 | Some distros, however, may have their own maintainers: 49 | 50 | | Distro | Package name/Link | 51 | | --- | --- | 52 | | Arch Linux | [`automathemely`](https://aur.archlinux.org/packages/automathemely/) 53 | 54 | ### Running 55 | 56 | Once installed, either run the settings manager by clicking normally on the icon or through the terminal and configure as needed: 57 | 58 | ```bash 59 | automathemely --manage 60 | ``` 61 | 62 | Or you can run once without any parameters to generate a settings file and manually edit the file in `/home/USER/.config/automathemely` 63 | 64 | You can also tweak any setting you want with the help of `--list` and `--setting`: 65 | 66 | ```bash 67 | # To show all the available options 68 | automathemely --list 69 | # For example: 70 | automathemely --setting desktop_environment=gnome 71 | automathemely --setting themes.gnome.light.gtk=Adwaita 72 | ``` 73 | 74 | Finally, you can either log out and back in or start the scheduler manually: 75 | 76 | ```bash 77 | # (Re)start the scheduler 78 | automathemely --restart 79 | ``` 80 | 81 | And that's it! 82 | 83 | 84 | In the case of it failing to do its job (please report on [issues](https://github.com/C2N14/AutomaThemely/issues)) you can always try to restart the scheduler or run it manually to try to fix it by running `automathemely` or right clicking the icon and selecting "Run AutomaThemely" 85 | 86 | ## Notes 87 | 88 | * This program assumes that a day in your location has both sunrise and sunset in the same 0 to 24 hr day span, and if you decide to set a custom time offset make sure both of these events still occur within this span 89 | * This program requires an active internet connection **ONLY** if you set *Auto Location* on (it uses your ip to determine your geolocation), otherwise you can manually set your location and you won't need it. 90 | * Currently to switch GNOME Shell themes, GNOME Tweaks and the GNOME User Themes extension have to be installed and enabled 91 | * Tested with (Ku/Xu/U)buntu 18.04 & Ubuntu 16.04 92 | * Yeah, yeah, I know that icon is an eyesore but I'm no designer so it'll have to do until a better one is made ¯\\\_(ツ)_/¯ 93 | * **For more detailed info, refer to the [FAQ](https://github.com/C2N14/AutomaThemely/wiki/FAQ)** 94 | 95 | ## License 96 | 97 | This project is licensed under the GPLv3 License - see [LICENSE](LICENSE) for details 98 | -------------------------------------------------------------------------------- /automathemely/autoth_tools/argmanager.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import argparse 3 | import json 4 | import logging 5 | import pickle as pkl 6 | 7 | from automathemely.autoth_tools.utils import get_local, read_dict, write_dic 8 | 9 | logger = logging.getLogger(__name__) 10 | 11 | parser = argparse.ArgumentParser() 12 | options = parser.add_mutually_exclusive_group() 13 | options.add_argument('-l', '--list', help='list all current settings', action='store_true', default=False) 14 | options.add_argument('-s', '--setting', help="change a specific setting (e.g. key.subkey=value)") 15 | options.add_argument('-m', '--manage', help='easier to use settings manager GUI', action='store_true', 16 | default=False) 17 | options.add_argument('-u', '--update', help='update the sunrise and sunset\'s times manually', action='store_true', 18 | default=False) 19 | options.add_argument('-r', '--restart', 20 | help='(re)start the scheduler script if it were to not start or stop unexpectedly', 21 | action='store_true', default=False) 22 | 23 | 24 | # For --list arg 25 | def print_list(d, indent=0): 26 | for key, value in d.items(): 27 | print('{}{}'.format('\t' * indent, key), end='') 28 | if isinstance(value, dict): 29 | print('.') 30 | print_list(value, indent + 1) 31 | else: 32 | print(' = {}'.format(value)) 33 | 34 | 35 | # ARGUMENTS FUNCTION 36 | def main(us_se): 37 | args = parser.parse_args() 38 | 39 | # LIST 40 | if args.list: 41 | logger.info('Printing current settings...') 42 | print('') 43 | print_list(us_se) 44 | return 45 | 46 | # SET 47 | elif args.setting: 48 | if not args.setting.count('=') == 1: 49 | logger.error('Invalid string (None or more than one "=" signs)') 50 | return 51 | 52 | setts = args.setting.split('=') 53 | to_set_key = setts[0].strip() 54 | to_set_val = setts[1].strip() 55 | 56 | if to_set_key == '': 57 | logger.error('Invalid string (Empty key)') 58 | elif to_set_key[-1] == '.': 59 | logger.error('Invalid string (Key ends in dot)') 60 | if not to_set_val: 61 | logger.error('Invalid string (Empty value)') 62 | elif to_set_val.lower() in ['t', 'true']: 63 | to_set_val = True 64 | elif to_set_val.lower() in ['f', 'false']: 65 | to_set_val = False 66 | else: 67 | try: 68 | to_set_val = int(to_set_val) 69 | except ValueError: 70 | try: 71 | to_set_val = float(to_set_val) 72 | except ValueError: 73 | pass 74 | 75 | if to_set_key.count('.') > 0: 76 | key_list = [s.strip() for s in to_set_key.split('.')] 77 | else: 78 | key_list = [to_set_key] 79 | 80 | if read_dict(us_se, key_list) is not None: 81 | write_dic(us_se, key_list, to_set_val) 82 | 83 | with open(get_local('user_settings.json'), 'w') as file: 84 | json.dump(us_se, file, indent=4) 85 | 86 | # Warning if user disables auto by --setting 87 | if 'enabled' in to_set_key and not to_set_val: 88 | logger.warning('Remember to set all the necessary values with either --settings or --manage') 89 | logger.info('Successfully set key "{}" as "{}"'.format(to_set_key, to_set_val)) 90 | exit() 91 | 92 | else: 93 | logger.error('Key "{}" not found'.format(to_set_key)) 94 | 95 | return 96 | 97 | # MANAGE 98 | elif args.manage: 99 | from . import settsmanager 100 | # From here on the manager takes over 'til exit 101 | settsmanager.main(us_se) 102 | return 103 | 104 | # UPDATE 105 | elif args.update: 106 | from . import updsuntimes 107 | output = updsuntimes.main(us_se) 108 | if output: 109 | with open(get_local('sun_hours.time'), 'wb') as file: 110 | pkl.dump(output, file, protocol=pkl.HIGHEST_PROTOCOL) 111 | logger.info('Sun hours successfully updated') 112 | return 113 | 114 | # RESTART 115 | elif args.restart: 116 | from automathemely.autoth_tools.utils import pgrep, get_bin 117 | from subprocess import Popen, DEVNULL 118 | if pgrep(['autothscheduler.py'], use_full=True): 119 | Popen(['pkill', '-f', 'autothscheduler.py']).wait() 120 | Popen(['python3', get_bin('autothscheduler.py')], start_new_session=True, stdout=DEVNULL, stderr=DEVNULL) 121 | logger.info('Restarted the scheduler') 122 | -------------------------------------------------------------------------------- /automathemely/autoth_tools/updsuntimes.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import logging 3 | from datetime import timedelta 4 | from time import sleep 5 | 6 | import pytz 7 | import tzlocal 8 | from astral import Location 9 | 10 | from automathemely.autoth_tools.utils import get_local, verify_desktop_session 11 | 12 | logger = logging.getLogger(__name__) 13 | 14 | 15 | def get_loc_from_ip(): 16 | import requests 17 | 18 | # Try to reach ipinfo a max of 15 times, if no connection or html response not OK log and wait 19 | con_err_msg = 'Can\'t reach https://ipinfo.io/ (Network may be down). Waiting 5 minutes to try again...' 20 | for i in range(15): 21 | try: 22 | g = requests.get('https://ipinfo.io/json') 23 | except (requests.exceptions.ConnectionError, ConnectionAbortedError, 24 | ConnectionRefusedError, ConnectionResetError): 25 | logger.warning(con_err_msg) 26 | sleep(300) 27 | else: 28 | if not g.status_code == 200: 29 | logger.warning(con_err_msg) 30 | sleep(300) 31 | else: 32 | return g 33 | 34 | return 35 | 36 | 37 | def main(us_se): 38 | if 'location' not in us_se: 39 | logger.error('Invalid config file') 40 | return 41 | 42 | if us_se['location']['auto_enabled']: 43 | loc = get_loc_from_ip() 44 | if loc: 45 | loc = loc.json() 46 | else: 47 | logger.error('Couldn\'t connect to ipinfo, giving up') 48 | return 49 | 50 | loc['latitude'], loc['longitude'] = (float(x) for x in loc['loc'].strip().split(',')) 51 | loc['time_zone'] = tzlocal.get_localzone().zone 52 | 53 | else: 54 | for k, v in us_se['location']['manual'].items(): 55 | try: 56 | val = v.strip() 57 | except AttributeError: 58 | pass 59 | else: 60 | if not val: 61 | logger.error('Auto location is not enabled and some manual values are missing') 62 | return 63 | loc = us_se['location']['manual'] 64 | 65 | try: 66 | location = Location() 67 | location.name = loc['city'] 68 | location.region = loc['region'] 69 | location.latitude = loc['latitude'] 70 | location.longitude = loc['longitude'] 71 | location.timezone = loc['time_zone'] 72 | except ValueError as e: 73 | logger.error(str(e)) 74 | return 75 | 76 | sunrise = location.sun()['sunrise'].replace(second=0) + timedelta(minutes=us_se['offset']['sunrise']) 77 | sunset = location.sun()['sunset'].replace(second=0) + timedelta(minutes=us_se['offset']['sunset']) 78 | 79 | # Convert to UTC for storage 80 | return sunrise.astimezone(pytz.utc), sunset.astimezone(pytz.utc) 81 | 82 | 83 | # This should only be called when running through systemd 84 | if __name__ == '__main__': 85 | import json 86 | import pickle as pkl 87 | import logging 88 | 89 | # When importing automathemely we inherit the root logger, so we need to configure it for our purposes 90 | from automathemely import main_file_handler, notifier_handler, updsun_file_handler, \ 91 | default_simple_format, timed_details_format 92 | 93 | # I know there also is logging.root, but I found it has some weird behaviours 94 | root_logger = logging.getLogger() 95 | 96 | # We don't need these two 97 | root_logger.removeHandler(main_file_handler) 98 | root_logger.removeHandler(notifier_handler) 99 | # Log here instead 100 | root_logger.addHandler(updsun_file_handler) 101 | 102 | # Format the remaining handlers to display time 103 | for handler in root_logger.handlers[:]: 104 | handler.setFormatter(logging.Formatter(timed_details_format)) 105 | 106 | # This logger is specifically for displaying a notification if something went wrong 107 | run_as_main_logger = logging.getLogger('updsuntimes.py') 108 | 109 | notifier_handler.setLevel(logging.WARNING) 110 | notifier_handler.setFormatter(logging.Formatter(default_simple_format)) 111 | run_as_main_logger.addHandler(notifier_handler) 112 | 113 | with open(get_local('user_settings.json'), 'r') as f: 114 | user_settings = json.load(f) 115 | 116 | output = main(user_settings) 117 | if output: 118 | with open(get_local('sun_times'), 'wb') as file: 119 | pkl.dump(output, file, protocol=pkl.HIGHEST_PROTOCOL) 120 | else: 121 | if verify_desktop_session(): 122 | run_as_main_logger.warning('There were some errors while updating the sunrise and sunset times, check {} ' 123 | 'for more details'.format(get_local('.updsuntimes.log'))) 124 | -------------------------------------------------------------------------------- /automathemely/bin/run.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import json 3 | import logging 4 | import pickle as pkl 5 | import shutil 6 | import sys 7 | from datetime import datetime 8 | from os import chdir, getuid 9 | from pathlib import Path 10 | 11 | import pytz 12 | import tzlocal 13 | 14 | logger = logging.getLogger(__name__) 15 | 16 | 17 | def check_root(): # Prevent from being run as root for security and compatibility reasons 18 | if getuid() == 0: 19 | logger.critical('This shouldn\'t be run as root unless told otherwise!') 20 | sys.exit() 21 | 22 | 23 | def main(): 24 | 25 | check_root() 26 | 27 | import automathemely 28 | 29 | from automathemely.autoth_tools import argmanager, extratools, envspecific, updsuntimes 30 | 31 | from automathemely import __version__ as version 32 | from automathemely.autoth_tools.utils import get_resource, get_local, update_dict 33 | 34 | # Set workspace as the directory of the script 35 | workspace = Path(__file__).resolve().parent 36 | chdir(str(workspace)) 37 | sys.path.append('..') 38 | 39 | first_time_run = False 40 | 41 | # Test for settings file and if it doesn't exist copy it from defaults 42 | if not Path(get_local('user_settings.json')).is_file(): 43 | shutil.copy2(get_resource('default_user_settings.json'), get_local('user_settings.json')) 44 | # By default notifications are enabled 45 | from automathemely import notifier_handler 46 | logging.getLogger().addHandler(notifier_handler) 47 | logger.info('No valid config file found, creating one...') 48 | first_time_run = True 49 | 50 | try: 51 | with open(get_local('user_settings.json'), 'r') as f: 52 | user_settings = json.load(f) 53 | except json.decoder.JSONDecodeError: 54 | user_settings = dict() 55 | 56 | # If settings files versions don't match (in case of an update for instance), overwrite values of 57 | # default_settings with user_settings and use that instead 58 | 59 | logger.debug('Program version = {}'.format(version)) 60 | logger.debug('File version = {}'.format(str(user_settings['version']))) 61 | if 'version' not in user_settings or str(user_settings['version']) != version: 62 | with open(get_resource('default_user_settings.json'), 'r') as f: 63 | default_settings = json.load(f) 64 | 65 | from pkg_resources import parse_version 66 | 67 | # Hardcoded attempt to try to import old structure to new structure... 68 | if parse_version(str(user_settings['version'])) <= parse_version('1.2'): 69 | logger.debug('Lower version!') 70 | user_settings['themes']['gnome'] = dict() 71 | user_settings['themes']['gnome']['light'], user_settings['themes']['gnome']['dark'] = dict(), dict() 72 | user_settings['themes']['gnome']['light']['gtk'] = user_settings['themes'].pop('light', '') 73 | user_settings['themes']['gnome']['dark']['gtk'] = user_settings['themes'].pop('dark', '') 74 | 75 | user_settings = update_dict(default_settings, user_settings) 76 | user_settings['version'] = version 77 | 78 | if user_settings['misc']['notifications']: 79 | # Not exactly sure why this is needed but alright... 80 | automathemely.notifier_handler.setFormatter(logging.Formatter(automathemely.default_simple_format)) 81 | # Add the notification handler to the root logger 82 | logging.getLogger().addHandler(automathemely.notifier_handler) 83 | 84 | # If any argument is given, pass it/them to the arg manager module 85 | if len(sys.argv) > 1: 86 | automathemely.autoth_tools.argmanager.main(user_settings) 87 | return 88 | 89 | # We don't want to proceed until we have given the user the chance to review its settings 90 | if first_time_run: 91 | return 92 | 93 | if not Path(get_local('sun_times')).is_file(): 94 | logger.info('No valid times file found, creating one...') 95 | output = updsuntimes.main(user_settings) 96 | if output: 97 | with open(get_local('sun_times'), 'wb') as file: 98 | pkl.dump(output, file, protocol=pkl.HIGHEST_PROTOCOL) 99 | 100 | local_tz = tzlocal.get_localzone() 101 | 102 | with open(get_local('sun_times'), 'rb') as file: 103 | sunrise, sunset = pkl.load(file) 104 | 105 | # Convert to local timezone and ignore date 106 | now = datetime.now(pytz.utc).astimezone(local_tz).time() 107 | sunrise, sunset = sunrise.astimezone(local_tz).time(), sunset.astimezone(local_tz).time() 108 | 109 | if sunrise < now < sunset: 110 | t_color = 'light' 111 | else: 112 | t_color = 'dark' 113 | 114 | logger.info('Switching to {} themes...'.format(t_color)) 115 | 116 | # Change desktop environment theme 117 | desk_env = user_settings['desktop_environment'] 118 | if desk_env != 'custom': 119 | for t_type in user_settings['themes'][desk_env][t_color]: 120 | theme = user_settings['themes'][desk_env][t_color][t_type] 121 | envspecific.set_theme(desk_env, t_type, theme) 122 | 123 | # Run user scripts 124 | s_time = 'sunrise' if t_color == 'light' else 'sunset' 125 | extratools.run_scripts(user_settings['extras']['scripts'][s_time], 126 | notifications_enabled=user_settings['misc']['notifications']) 127 | 128 | # Change extra themes 129 | for k, v in user_settings['extras'].items(): 130 | if k != 'scripts' and v['enabled']: 131 | extratools.set_extra_theme(user_settings, k, t_color) 132 | 133 | 134 | if __name__ == '__main__': 135 | main() 136 | -------------------------------------------------------------------------------- /automathemely/autoth_tools/extratools.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import json 3 | import os 4 | from pathlib import Path 5 | from subprocess import check_output, CalledProcessError 6 | 7 | import logging 8 | logger = logging.getLogger(__name__) 9 | 10 | 11 | # For getting vscode themes 12 | def scan_vscode_extensions(path): 13 | t_list = [] 14 | try: 15 | for k in next(os.walk(path))[1]: 16 | with Path(path).joinpath(k, 'package.json').open() as f: 17 | data = json.load(f) 18 | if 'themes' in data['contributes']: 19 | for i in data['contributes']['themes']: 20 | if 'id' in i: 21 | t_list.append(i['id']) 22 | elif 'label' in i: 23 | t_list.append(i['label']) 24 | except StopIteration: 25 | pass 26 | 27 | list.sort(t_list) 28 | themes = [] 29 | for name in t_list: 30 | themes.append((name,)) 31 | return themes 32 | 33 | 34 | # Should be delayed and avoided as much as possible... 35 | def get_installed_extra_themes(extra): 36 | if extra == 'atom': 37 | try: 38 | atom_packs = check_output('apm list --themes --bare', shell=True).decode('utf-8') 39 | except CalledProcessError: 40 | return 41 | 42 | atom_packs = atom_packs.split('\n') 43 | for i, v in enumerate(atom_packs): 44 | atom_packs[i] = v.split('@')[0] 45 | atom_packs = list(filter(None, atom_packs)) 46 | list.sort(atom_packs) 47 | themes = [] 48 | syntaxes = [] 49 | for v in atom_packs: 50 | if 'syntax' in v: 51 | syntaxes.append((v,)) 52 | else: 53 | themes.append((v,)) 54 | return {'themes': themes, 'syntaxes': syntaxes} 55 | 56 | if extra == 'vscode': 57 | 58 | # All possible paths that I know of that can contain VSCode extensions 59 | vscode_extensions_paths = ['/snap/vscode/current/usr/share/code/resources/app/extensions', 60 | '/usr/share/code/resources/app/extensions', 61 | str(Path.home().joinpath('.vscode', 'extensions')), 62 | '/usr/lib/extensions', 63 | '/opt/visual-studio-code/resources/app/extensions'] 64 | vscode_themes = [] 65 | for p in vscode_extensions_paths: 66 | vscode_themes += scan_vscode_extensions(p) 67 | 68 | if not vscode_themes: 69 | return 70 | 71 | else: 72 | return {'themes': vscode_themes} 73 | 74 | 75 | def set_extra_theme(us_se, extra, theme_type): 76 | import fileinput 77 | import sys 78 | if extra == 'atom': 79 | 80 | target_file = Path.home().joinpath('.atom', 'config.cson') 81 | if not target_file.is_file(): 82 | logger.error('Atom config file not found') 83 | return 84 | 85 | lines_below_keyword = 0 86 | for line in fileinput.input(str(target_file), inplace=True): 87 | # First look for line with the keyword "themes", then write lines 88 | if line.strip().startswith('themes:'): 89 | sys.stdout.write(line) 90 | lines_below_keyword += 1 91 | 92 | elif lines_below_keyword == 1: 93 | # Make sure it has the same spaces as the original file 94 | preceding_spaces = ' ' * (len(line) - len(line.lstrip(' '))) 95 | print(preceding_spaces + '"' + us_se['extras']['atom']['themes'][theme_type]['theme'] + '"') 96 | lines_below_keyword += 1 97 | 98 | elif lines_below_keyword == 2: 99 | # Make sure it has the same spaces as the original file 100 | preceding_spaces = ' ' * (len(line) - len(line.lstrip(' '))) 101 | print(preceding_spaces + '"' + us_se['extras']['atom']['themes'][theme_type]['syntax'] + '"') 102 | lines_below_keyword += 1 103 | 104 | else: 105 | sys.stdout.write(line) 106 | 107 | elif extra == 'vscode': 108 | target_file = Path.home().joinpath('.config', 'Code', 'User', 'settings.json') 109 | if us_se['extras']['vscode']['custom_config_dir']: 110 | if Path(us_se['extras']['vscode']['custom_config_dir']).joinpath('settings.json').is_file(): 111 | target_file = Path(us_se['extras']['vscode']['custom_config_dir']).joinpath('settings.json') 112 | else: 113 | logger.error('Invalid VSCode config directory, falling back to default') 114 | 115 | if not target_file.parent.is_dir(): 116 | logger.error('VSCode config directory not found') 117 | return 118 | 119 | # Sometimes the settings file is not present until the user changes a setting 120 | if target_file.is_file(): 121 | with target_file.open() as f: 122 | p = json.load(f) 123 | else: 124 | p = dict() 125 | 126 | p['workbench.colorTheme'] = us_se['extras']['vscode']['themes'][theme_type] 127 | 128 | with target_file.open(mode='w') as f: 129 | json.dump(p, f, indent=4) 130 | 131 | 132 | def run_scripts(scripts, notifications_enabled): 133 | from automathemely import notifier_handler 134 | from subprocess import run 135 | 136 | # Temporarily remove notifier handler to not spam user of failed scripts 137 | logging.getLogger().removeHandler(notifier_handler) 138 | 139 | error_message = None 140 | for n, script in scripts.items(): 141 | if not script: 142 | continue 143 | elif not Path(script).is_file(): 144 | logger.error('Script file {} not found'.format(n)) 145 | error_message = 'One or more of the script files was/were not found' 146 | else: 147 | try: 148 | run([script], check=True) 149 | except Exception as e: 150 | logger.exception('Error while running {}'.format(script), exc_info=e) 151 | error_message = 'One or more of the script files failed to run' 152 | 153 | # Add it back 154 | if notifications_enabled: 155 | logging.getLogger().addHandler(notifier_handler) 156 | 157 | if error_message: 158 | logger.warning(error_message) 159 | -------------------------------------------------------------------------------- /automathemely/autoth_tools/envspecific.py: -------------------------------------------------------------------------------- 1 | from os import walk 2 | from collections import defaultdict 3 | from pathlib import Path 4 | 5 | import logging 6 | 7 | logger = logging.getLogger(__name__) 8 | 9 | # GTK, Cinnamon's desktop and GNOME shell themes all share the same dirs, but have different structures and conditions 10 | HOME = Path.home() 11 | PATH_CONSTANTS = { 12 | 'general-themes': ( 13 | '/usr/share/themes/', 14 | str(HOME.joinpath('.local/share/themes/')), 15 | str(HOME.joinpath('.themes/')) 16 | ), 17 | 'icons-themes': ( 18 | '/usr/share/icons/', 19 | str(HOME.joinpath('.local/share/icons/')), 20 | str(HOME.joinpath('.icons/')) 21 | ), 22 | 'lookandfeel-themes': ( 23 | '/usr/share/plasma/look-and-feel/', 24 | str(HOME.joinpath('.local/share/plasma/look-and-feel/')) 25 | ), 26 | 'shell-user-extensions': str(HOME.joinpath('.local/share/gnome-shell/extensions/')), 27 | 'kde-gtk-config': { 28 | 'gtk3': str(HOME.joinpath('.config/gtk-3.0/settings.ini')), 29 | 'gtk2': str(HOME.joinpath('.gtkrc-2.0')) 30 | }, 31 | 'special-paths': { 32 | 'gtk': ('/snap/communitheme/current/share/themes',) 33 | } 34 | } 35 | SUPPORTED_DESKENVS = ('gnome', 'kde', 'xfce', 'cinnamon') 36 | 37 | # Just a nitpick for displaying them correctly in logs and notifications 38 | UPPERCASE_NAMES = ('gnome', 'kde', 'xfce', 'gtk') 39 | CAPITALIZED_NAMES = ('cinnamon', 'shell', 'desktop') 40 | MISC_NAMES = { 41 | 'lookandfeel': 'Look and Feel' 42 | } 43 | 44 | 45 | def correct_name_case(name): 46 | if name in UPPERCASE_NAMES: 47 | return name.upper() 48 | elif name in CAPITALIZED_NAMES: 49 | return name.capitalize() 50 | elif name in MISC_NAMES: 51 | return MISC_NAMES[name] 52 | else: 53 | return name 54 | 55 | 56 | # NOTE: Lists must have the same type of content for this to work 57 | def sort_remove_dupes(lis): 58 | lis = list(set(lis)) 59 | 60 | if len(lis) > 0: 61 | if isinstance(lis[0], str): 62 | return sorted(lis, key=str.lower) 63 | 64 | elif isinstance(lis[0], tuple): 65 | return sorted(lis, key=lambda s: s[0].lower()) 66 | 67 | return sorted(lis) 68 | 69 | 70 | def walk_filter_dirs(dirs, filtering_func, return_parent=False): 71 | filtered_dirs = list() 72 | for directory in dirs: 73 | scan = next(walk(directory), None) 74 | if scan: 75 | for subdir in scan[1]: 76 | if filtering_func(scan[0], subdir): 77 | if return_parent: 78 | filtered_dirs.append((subdir, scan[0])) 79 | else: 80 | filtered_dirs.append(subdir) 81 | 82 | return filtered_dirs 83 | 84 | 85 | def get_installed_themes(desk_env): 86 | types = defaultdict(bool) 87 | themes = defaultdict(list) 88 | 89 | # All supported desk envs target GTK 90 | types['gtk'] = True 91 | 92 | if desk_env in ('gnome', 'xfce', 'cinnamon'): 93 | types['icons'] = True 94 | 95 | if desk_env == 'gnome': 96 | types['shell'] = True 97 | 98 | elif desk_env == 'kde': 99 | types['lookandfeel'] = True 100 | 101 | elif desk_env == 'custom': 102 | return 103 | 104 | elif desk_env not in SUPPORTED_DESKENVS: 105 | raise Exception('Invalid Desktop Environment "{}"'.format(desk_env)) 106 | 107 | # Actually start scanning for themes 108 | if types['gtk']: 109 | t_list = walk_filter_dirs(PATH_CONSTANTS['general-themes'] + PATH_CONSTANTS['special-paths']['gtk'], 110 | lambda parent, t: Path(parent).joinpath(t).glob('gtk-3.*/gtk.css') 111 | and t.lower() != 'default') 112 | themes['gtk'] = [(t,) for t in sort_remove_dupes(t_list)] 113 | 114 | if types['icons']: 115 | t_list = walk_filter_dirs(PATH_CONSTANTS['icons-themes'], lambda parent, t: Path(parent) 116 | .joinpath(t, 'index.theme').is_file() and t.lower() != 'default') 117 | themes['icons'] = [(t,) for t in sort_remove_dupes(t_list)] 118 | 119 | if types['desktop']: 120 | # I guess a hidden default? 121 | t_list = ['cinnamon'] 122 | t_list += walk_filter_dirs(PATH_CONSTANTS['general-themes'], lambda parent, t: Path(parent) 123 | .joinpath(t, 'cinnamon').is_dir()) 124 | themes['desktop'] = [(t,) for t in sort_remove_dupes(t_list)] 125 | 126 | if types['lookandfeel']: 127 | import configparser 128 | import json 129 | t_list = walk_filter_dirs(PATH_CONSTANTS['lookandfeel-themes'], lambda parent, t: Path(parent) 130 | .joinpath(t, 'metadata.desktop').is_file() or Path(parent) 131 | .joinpath(t, 'metadata.json').is_file(), return_parent=True) 132 | t_list = sort_remove_dupes(t_list) 133 | 134 | for t in t_list: 135 | parent_dir = t[1] 136 | theme = t[0] 137 | # Prioritize .desktop metadata files to .json ones just like systemsettings 138 | if Path(parent_dir).joinpath(theme, 'metadata.desktop').is_file(): 139 | # if os.path.isfile('{}{}/metadata.desktop'.format(t[1], t[0])): 140 | metadata = configparser.ConfigParser(strict=False) 141 | metadata.read(str(Path(parent_dir).joinpath(theme, 'metadata.desktop'))) 142 | t_name = metadata['Desktop Entry']['Name'] 143 | 144 | # Has to be JSON because it was already filtered before 145 | else: 146 | with Path(parent_dir).joinpath(theme, 'metadata.json').open() as f: 147 | metadata = json.load(f) 148 | t_name = metadata['KPlugin']['Name'] 149 | 150 | themes['lookandfeel'].append((t[0], t_name)) 151 | 152 | if types['shell']: 153 | # This is explained in the function below 154 | t_list = ['default'] 155 | t_list += walk_filter_dirs(PATH_CONSTANTS['general-themes'], lambda parent, t: Path(parent) 156 | .joinpath(t, 'gnome-shell', 'gnome-shell.css').is_file() and t.lower() != 'default') 157 | 158 | themes['shell'] = [(t,) for t in sort_remove_dupes(t_list)] 159 | 160 | return themes 161 | 162 | 163 | def set_theme(desk_env, t_type, theme): 164 | if desk_env not in SUPPORTED_DESKENVS: 165 | raise Exception('Invalid desktop environment!') 166 | 167 | elif not theme: 168 | logger.error('{}\'s {} theme not set '.format(correct_name_case(desk_env), correct_name_case(t_type))) 169 | return 170 | 171 | if t_type in ['gtk', 'icons']: 172 | from gi.repository import Gio 173 | if desk_env == 'cinnamon': 174 | gsettings_string = 'org.cinnamon.desktop.interface' 175 | else: 176 | gsettings_string = 'org.gnome.desktop.interface' 177 | 178 | gsettings = Gio.Settings.new(gsettings_string) 179 | 180 | # Safety fallback, shouldn't happen 181 | else: 182 | gsettings = None 183 | 184 | if t_type == 'gtk': 185 | 186 | # Easy peasy 187 | # For GNOME and Cinnamon 188 | gsettings['gtk-theme'] = theme 189 | 190 | # For XFCE 191 | if desk_env == 'xfce': 192 | from subprocess import run, CalledProcessError 193 | try: 194 | # noinspection SpellCheckingInspection 195 | run(['xfconf-query', '-c', 'xsettings', '-p', '/Net/ThemeName', '-s', theme]) 196 | except CalledProcessError: 197 | logger.error('Could not apply GTK theme') 198 | return 199 | 200 | # Switching GTK themes in KDE is a little bit more complicated than the others... 201 | # For KDE 202 | elif desk_env == 'kde': 203 | from subprocess import run 204 | import configparser 205 | import fileinput 206 | import sys 207 | from automathemely.autoth_tools.utils import get_bin 208 | 209 | # Set GTK3 theme 210 | # This would usually be done with kwriteconfig but since there is no way to notify GTK3 apps that the 211 | # theme has changed in KDE like with GTK2 anyway we might as well do it this way 212 | parser = configparser.ConfigParser(strict=False) 213 | # Prevent changing the key's case 214 | parser.optionxform = lambda option: option 215 | parser.read(PATH_CONSTANTS['kde-gtk-config']['gtk3']) 216 | 217 | parser['Settings']['gtk-theme-name'] = theme 218 | with open(PATH_CONSTANTS['kde-gtk-config']['gtk3'], 'w') as f: 219 | parser.write(f, space_around_delimiters=False) 220 | 221 | # Search for gtk2 config file in theme dir in PATH_CONSTANTS dirs 222 | # As if it wasn't messy enough already... 223 | match = walk_filter_dirs(PATH_CONSTANTS['general-themes'], lambda parent_dir, t: Path(parent_dir) 224 | .joinpath(t).glob('gtk-2.*/gtkrc') and t.lower() != 'default', return_parent=True) 225 | 226 | if not match: 227 | logger.warning('The selected GTK theme does not contain a GTK2 theme, so some applications may ' 228 | 'look odd') 229 | else: 230 | # If there are several themes with the same name in different directories, only get the first one 231 | # to match according to the dirs hierarchy in PATH_CONSTANTS 232 | theme_parent = match[0][1] 233 | 234 | if not Path(PATH_CONSTANTS['kde-gtk-config']['gtk2']).is_file(): 235 | logger.warning('GTK2 config file not found, set a theme from System Settings at least once and ' 236 | 'try again') 237 | 238 | # Write GTK2 config 239 | else: 240 | line_replaced, previous_is_autogen_comment = False, False 241 | for line in fileinput.input(PATH_CONSTANTS['kde-gtk-config']['gtk2'], inplace=True): 242 | 243 | if line.startswith('# Configs for GTK2 programs'): 244 | previous_is_autogen_comment = True 245 | sys.stdout.write(line) 246 | 247 | # Even in kde-config-gtk they don't seem to agree if this may not actually be needed, but 248 | # just in case here it is 249 | elif line.startswith('include'): 250 | print('include "{}"'.format(str(Path(theme_parent).joinpath(theme, 'gtk-2.0', 'gtkrc')))) 251 | 252 | # This is the one that matters 253 | elif line.startswith('gtk-theme-name='): 254 | print('gtk-theme-name="{}"'.format(theme)) 255 | line_replaced = True 256 | 257 | else: 258 | if previous_is_autogen_comment and not line.startswith('# Edited by AutomaThemely'): 259 | print('# Edited by AutomaThemely') 260 | previous_is_autogen_comment = False 261 | sys.stdout.write(line) 262 | 263 | if not line_replaced: 264 | logger.warning('GTK2 config file is invalid, set a theme from System Settings at least ' 265 | 'once and try again') 266 | else: 267 | # Send signal to GTK2 apps to refresh their themes 268 | run([get_bin('kde-refresh-gtk2')]) 269 | 270 | elif t_type == 'icons': 271 | 272 | # For GNOME and Cinnamon 273 | gsettings['icon-theme'] = theme 274 | 275 | # For XFCE 276 | if desk_env == 'xfce': 277 | from subprocess import run, CalledProcessError 278 | try: 279 | # noinspection SpellCheckingInspection 280 | run(['xfconf-query', '-c', 'xsettings', '-p', '/Net/IconThemeName', '-s', theme]) 281 | except CalledProcessError: 282 | logger.error('Could not apply icons theme') 283 | return 284 | 285 | elif t_type == 'shell': 286 | # This is WAY out of my level, I'll just let the professionals handle this one... 287 | try: 288 | import gtweak 289 | except ImportError: 290 | logger.error('GNOME Tweaks not installed') 291 | return 292 | 293 | from gtweak.gshellwrapper import GnomeShellFactory 294 | from gtweak.defs import GSETTINGS_SCHEMA_DIR, LOCALE_DIR 295 | # This could probably be implemented in house but since we're already importing from gtweak I guess it'll stay 296 | # this way for now 297 | from gtweak.gsettings import GSettingsSetting 298 | 299 | gtweak.GSETTINGS_SCHEMA_DIR = GSETTINGS_SCHEMA_DIR 300 | gtweak.LOCALE_DIR = LOCALE_DIR 301 | shell = GnomeShellFactory().get_shell() 302 | shell_theme_name = 'user-theme@gnome-shell-extensions.gcampax.github.com' 303 | shell_theme_schema = 'org.gnome.shell.extensions.user-theme' 304 | shell_theme_schema_dir = Path(PATH_CONSTANTS['shell-user-extensions']).joinpath(shell_theme_name, 'schemas') 305 | 306 | if not shell: 307 | logger.error('GNOME Shell not running') 308 | return 309 | else: 310 | # noinspection PyBroadException 311 | try: 312 | shell_extensions = shell.list_extensions() 313 | except Exception: 314 | logger.error('GNOME Shell extensions could not be loaded') 315 | return 316 | else: 317 | # noinspection PyBroadException 318 | try: 319 | if shell_theme_name in shell_extensions and shell_extensions[shell_theme_name]['state'] == 1: 320 | # If shell user-theme was installed locally e. g. through extensions.gnome.org 321 | if Path(shell_theme_schema_dir).is_dir(): 322 | user_shell_settings = GSettingsSetting(shell_theme_schema, 323 | schema_dir=str(shell_theme_schema_dir)) 324 | # If it was installed as a system extension 325 | else: 326 | user_shell_settings = GSettingsSetting(shell_theme_schema) 327 | else: 328 | logger.error('GNOME Shell user theme extension not enabled') 329 | return 330 | except Exception: 331 | logger.error('Could not load GNOME Shell user theme extension') 332 | return 333 | else: 334 | # To set the default theme you have to input an empty string, but since that won't work with the 335 | # Setting Manager's ComboBoxes we set it by this placeholder name 336 | if theme == 'default': 337 | theme = '' 338 | 339 | # Set the GNOME Shell theme 340 | user_shell_settings.set_string('name', theme) 341 | 342 | elif t_type == 'lookandfeel': 343 | from subprocess import run, CalledProcessError 344 | try: 345 | # noinspection SpellCheckingInspection 346 | run(['lookandfeeltool', '-a', '{}'.format(theme)], check=True) 347 | except CalledProcessError: 348 | logger.error('Could not apply Look and Feel theme') 349 | return 350 | 351 | elif t_type == 'desktop': 352 | from gi.repository import Gio 353 | cinnamon_settings = Gio.Settings.new('org.cinnamon.theme') 354 | cinnamon_settings['name'] = theme 355 | -------------------------------------------------------------------------------- /automathemely/autoth_tools/settsmanager.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import gi 3 | 4 | gi.require_version('Gtk', '3.0') 5 | 6 | # noinspection PyPep8 7 | from gi.repository import Gtk, Gio 8 | # noinspection PyPep8 9 | from automathemely.autoth_tools.utils import get_resource, get_local, read_dict, write_dic 10 | # noinspection PyPep8 11 | from automathemely.autoth_tools import extratools, envspecific 12 | # noinspection PyPep8 13 | import json 14 | 15 | # noinspection PyPep8 16 | import logging 17 | logger = logging.getLogger(__name__) 18 | 19 | 20 | def split_id_delimiter(obj_id): 21 | obj_id = obj_id.lstrip('*') 22 | if '~' in obj_id: 23 | return obj_id.split('~') 24 | else: 25 | return obj_id, None 26 | 27 | 28 | # Handle unexpected or invalid values in user_settings 29 | def try_or_default_type(val, try_type): 30 | try: 31 | return try_type(val) 32 | except ValueError: 33 | if try_type == str: 34 | return '' 35 | elif try_type == int: 36 | return 0 37 | elif try_type == float: 38 | return 0.0 39 | elif try_type == bool: 40 | return False 41 | else: 42 | return None 43 | 44 | 45 | def isfloat(value): 46 | try: 47 | float(value) 48 | return True 49 | except ValueError: 50 | return False 51 | 52 | 53 | # noinspection PyUnusedLocal 54 | def get_object_data(obj, *args): 55 | if isinstance(obj, Gtk.ComboBoxText): 56 | return obj.get_active_id() if obj.get_active_id() != 'none' else '' 57 | elif isinstance(obj, Gtk.Switch): 58 | return obj.get_active() 59 | elif isinstance(obj, Gtk.SpinButton): 60 | return obj.get_value_as_int() 61 | elif isinstance(obj, Gtk.Entry): 62 | text = obj.get_text() 63 | if obj.get_name() == 'float_only' and isfloat(text): 64 | return float(text) 65 | else: 66 | return text 67 | 68 | 69 | def scan_comboboxtext_descendants(obj, match): 70 | try: 71 | children = obj.get_children() 72 | except AttributeError: 73 | return 74 | else: 75 | if children: 76 | comboboxtexts = [] 77 | for child in children: 78 | scan = scan_comboboxtext_descendants(child, match) 79 | if scan: 80 | comboboxtexts.extend(scan) 81 | return comboboxtexts 82 | elif isinstance(obj, Gtk.ComboBoxText) and match in Gtk.Buildable.get_name(obj): 83 | return [obj] 84 | 85 | 86 | def display_row_separators(row, before): 87 | # This was added in GTK 3.14, but since it really doesn't make much of a difference and is purely aesthetic, and 88 | # prevents it from running on GTK 3.10 lets just set this when it is possible but not enforce it 89 | # noinspection PyBroadException 90 | try: 91 | row.set_activatable(False) 92 | row.set_selectable(False) 93 | except: 94 | pass 95 | 96 | if before: 97 | row.set_header(Gtk.Separator()) 98 | 99 | 100 | def get_last_visible_row(max_number_of_rows, listbox_id, builder): 101 | for i in range(max_number_of_rows, 1, -1): 102 | entry = builder.get_object('{}.{}'.format(listbox_id, str(i))) 103 | row = entry.get_parent().get_parent() 104 | 105 | if row.get_visible(): 106 | return i 107 | 108 | return 1 109 | 110 | 111 | ######## 112 | # This is a kind of weird system, but bear with me... 113 | # 114 | # GTk.Buildable.get_name() gets what is displayed as WIDGET ID in Glade 115 | # obj.get_name() gets what is displayed as WIDGET NAME in Glade 116 | # 117 | # In data containing widgets (ID starts with an *): 118 | 119 | # The widget ID is used for widget OUTPUT, i.e. value or PATH it is related to in user_settings, if there is a 120 | # delimiter (~) it will also indicate which part of the GUI it affects (its SUBORDINATE), like in enabler Switches 121 | # 122 | # The widget NAME is used for special attributes dependant on the type of 123 | # widget, such as if it is float only in Entries or what it will be populated with in ComboBoxTexts 124 | ######## 125 | 126 | # noinspection PyUnusedLocal 127 | class App(Gtk.Application): 128 | 129 | def __init__(self, us_se): 130 | super().__init__(application_id="com.github.c2n14.automathemely", 131 | flags=Gio.ApplicationFlags.FLAGS_NONE) 132 | 133 | self.main_window = None 134 | self.us_se = us_se 135 | 136 | # BASIC Gtk.Application FUNCTIONS 137 | # noinspection PyAttributeOutsideInit 138 | def do_startup(self): 139 | Gtk.Application.do_startup(self) 140 | self.builder = Gtk.Builder() 141 | self.builder.add_from_file(get_resource('manager_gui.glade')) 142 | self.builder.set_application(self) 143 | self.builder.connect_signals(self) 144 | 145 | # This does not get initialized until needed 146 | self.extras = dict() 147 | 148 | self.system_themes = envspecific.get_installed_themes(self.us_se['desktop_environment']) 149 | 150 | self.listen_changes = False 151 | self.saved_settings = False 152 | self.entries_error = list() 153 | self.changed = list() 154 | 155 | # Override the quit menu 156 | action = Gio.SimpleAction.new("quit", None) 157 | action.connect("activate", self.on_confirm_exit) 158 | self.add_action(action) 159 | 160 | # noinspection PyAttributeOutsideInit 161 | def do_activate(self): 162 | # Called on primary instance activation 163 | # Kinda like do_startup but after the window is displayed 164 | if not self.main_window: 165 | self.main_window = self.builder.get_object('main_window') 166 | self.main_window.set_application(self) 167 | self.main_window.set_title('AutomaThemely Settings') 168 | self.main_window.set_icon_from_file(get_resource('automathemely.svg')) 169 | 170 | sub_w_list = ['confirm_dialog', 'error_dialog'] 171 | self.sub_windows = dict() 172 | for w in sub_w_list: 173 | self.sub_windows[w] = self.builder.get_object(w) 174 | self.sub_windows[w].set_transient_for(self.main_window) 175 | 176 | self.setup_all() 177 | self.listen_changes = True 178 | 179 | self.main_window.present() 180 | 181 | def do_shutdown(self): 182 | Gtk.Application.do_shutdown(self) 183 | 184 | # Dump file 185 | if self.changed and self.saved_settings: 186 | with open(get_local('user_settings.json'), 'w') as file: 187 | json.dump(self.us_se, file, indent=4) 188 | exit_message = 'Successfully saved settings' 189 | else: 190 | exit_message = 'No changes were made' 191 | 192 | logger.info(exit_message) 193 | 194 | # MISC 195 | # Called on primary activation 196 | def setup_all(self): 197 | for obj in self.builder.get_objects(): 198 | try: 199 | obj_id = Gtk.Buildable.get_name(obj) 200 | except TypeError: 201 | continue 202 | 203 | # Filter out non-relevant objects 204 | if '___object_' not in obj_id: 205 | 206 | # These don't contain data 207 | if isinstance(obj, Gtk.LinkButton): 208 | obj.set_label("HINT: You can get most of this info at https://ipinfo.io/json") 209 | 210 | elif isinstance(obj, Gtk.ListBox): 211 | obj.set_header_func(display_row_separators) 212 | 213 | # These DO contain data 214 | elif obj_id.startswith('*'): 215 | obj_path, obj_sub = split_id_delimiter(obj_id) 216 | obj_attr = obj.get_name() 217 | keys = obj_path.split('.') 218 | val = read_dict(self.us_se, keys) 219 | 220 | # Has to go before entry because a SpinButton is also an entry... 221 | if isinstance(obj, Gtk.SpinButton): 222 | obj.configure(Gtk.Adjustment(value=try_or_default_type(val, int), lower=-999, upper=999, 223 | step_increment=1, page_increment=5, page_size=0), 1, 0) 224 | 225 | elif isinstance(obj, Gtk.Entry): 226 | obj.set_text(try_or_default_type(val, str)) 227 | 228 | elif isinstance(obj, Gtk.Switch): 229 | if try_or_default_type(val, bool): 230 | obj.set_active(True) 231 | else: 232 | obj.set_active(False) 233 | if obj_sub: 234 | self.on_container_toggle(obj) 235 | 236 | # Most of this method has been moved to populate_themes_cboxts 237 | elif isinstance(obj, Gtk.ComboBoxText): 238 | if obj_attr == 'desk_envs': 239 | # Special try or default 240 | if not try_or_default_type(val, str): 241 | val = 'custom' 242 | obj.set_active_id(try_or_default_type(val, str)) 243 | 244 | # Hardcoded setup scripts listboxes after their entries have already been setup 245 | scripts_listboxes = ['scripts_sunrise_listbox', 'scripts_sunset_listbox'] 246 | for listbox in scripts_listboxes: 247 | listbox_type = listbox.split('_')[1] 248 | 249 | for i in range(5, 1, -1): 250 | entry = self.builder.get_object('*extras.scripts.{}.{}'.format(listbox_type, str(i))) 251 | entry_text = entry.get_text() 252 | 253 | if entry_text: 254 | break 255 | else: 256 | listbox_row = entry.get_parent().get_parent() 257 | listbox_row.set_visible(False) 258 | 259 | # Artificially call function when pages are switched to enable or disable addrow_button according to row limit 260 | self.on_change_scripts_page() 261 | 262 | def populate_themes_cboxt(self, cboxt): 263 | # If ComboBoxText has an active id it has already been populated 264 | if cboxt.get_active_id(): 265 | return 266 | 267 | cboxt_id = Gtk.Buildable.get_name(cboxt) 268 | cboxt_path = split_id_delimiter(cboxt_id)[0] 269 | cboxt_attr = cboxt.get_name() 270 | 271 | val = read_dict(self.us_se, cboxt_path.split('.')) 272 | themes = [] 273 | 274 | if cboxt_id.startswith('*themes'): 275 | theme_type = cboxt_attr.split('-')[2] 276 | 277 | if not self.system_themes or theme_type not in self.system_themes: 278 | tmp = cboxt.get_children() 279 | cboxt.set_sensitive(False) 280 | return 281 | else: 282 | themes = self.system_themes[theme_type] 283 | 284 | elif cboxt_id.startswith('*extras'): 285 | cboxt_split = cboxt_attr.split('-') 286 | theme_type = cboxt_split[1] 287 | extra_type = cboxt_split[2] 288 | 289 | if theme_type not in self.extras[extra_type]: 290 | cboxt.set_sensitive(False) 291 | else: 292 | themes = self.extras[extra_type][theme_type] 293 | 294 | for theme in themes: 295 | t_id = theme[0] 296 | if len(theme) > 1: 297 | t_name = theme[1] 298 | else: 299 | t_name = t_id[0].upper() + t_id[1:] 300 | cboxt.append(t_id, t_name) 301 | 302 | active_id = try_or_default_type(val, str) 303 | if active_id: 304 | cboxt.set_active_id(active_id) 305 | else: 306 | # So it doesn't continue populating repeated options on non-set CBoxTs 307 | cboxt.set_active_id('none') 308 | 309 | # HANDLERS 310 | # noinspection PyAttributeOutsideInit 311 | def on_update_deskenv(self, cboxt, *args): 312 | cboxt_val = cboxt.get_active_id() 313 | 314 | self.system_themes = envspecific.get_installed_themes(cboxt_val) 315 | 316 | revealer = self.builder.get_object('deskenvs_revealer') 317 | notebooks = self.builder.get_object('deskenvs_box').get_children() 318 | 319 | if cboxt_val == 'custom': 320 | revealer.set_reveal_child(False) 321 | else: 322 | # Populate CBoxTs before displaying 323 | env_notebook = self.builder.get_object(cboxt_val) 324 | env_cboxts = scan_comboboxtext_descendants(env_notebook, cboxt_val) 325 | 326 | for env_box in env_cboxts: 327 | self.populate_themes_cboxt(env_box) 328 | 329 | revealer.set_reveal_child(True) 330 | 331 | for obj in notebooks: 332 | if Gtk.Buildable.get_name(obj) == cboxt_val: 333 | obj.set_visible(True) 334 | else: 335 | obj.set_visible(False) 336 | 337 | def on_container_toggle(self, switch, *args): 338 | switch_id = Gtk.Buildable.get_name(switch) 339 | container = split_id_delimiter(switch_id)[1] 340 | switch_attr = switch.get_name() 341 | 342 | container_obj = self.builder.get_object(container) 343 | 344 | if switch_attr == 'inverse': 345 | disable = True 346 | else: 347 | disable = False 348 | 349 | if switch.get_active(): 350 | container_obj.set_sensitive(not disable) 351 | else: 352 | container_obj.set_sensitive(disable) 353 | 354 | # To reduce start time (specially because some take a long time to setup, looking at you Atom ლ(ಠ益ಠლ)), 355 | # extras' CBoxTs are populated only if they are enabled to begin with or if they are enabled while it is running 356 | def on_enable_extra(self, switch, *args): 357 | if switch.get_active(): 358 | switch_id = Gtk.Buildable.get_name(switch) 359 | switch_path, container = split_id_delimiter(switch_id) 360 | extra_type = switch_path.split('.')[1] 361 | 362 | # This is the culprit 363 | self.extras[extra_type] = extratools.get_installed_extra_themes(extra_type) 364 | 365 | if self.extras[extra_type]: 366 | extras_cboxts = scan_comboboxtext_descendants(self.builder.get_object(container), extra_type) 367 | for extra_cboxt in extras_cboxts: 368 | self.populate_themes_cboxt(extra_cboxt) 369 | else: 370 | switch.set_active(False) 371 | switch.set_sensitive(False) 372 | return 373 | 374 | # These three functions related to scripts are kinda not great, and will probably change a lot in future revisions 375 | # because they were mostly an afterthought 376 | def on_remove_scripts_row(self, button, *args): 377 | button_id = Gtk.Buildable.get_name(button) 378 | sub_entry = split_id_delimiter(button_id)[1] 379 | listbox_type = sub_entry.split('.')[2] 380 | row_number = int(sub_entry.split('.')[-1]) 381 | 382 | max_number_of_rows = 5 383 | last_row = get_last_visible_row(max_number_of_rows, '*extras.scripts.{}'.format(listbox_type), self.builder) 384 | 385 | if row_number == last_row: 386 | entry = self.builder.get_object('*extras.scripts.{}.{}'.format(listbox_type, str(row_number))) 387 | entry.set_text('') 388 | 389 | if row_number > 1: 390 | row = entry.get_parent().get_parent() 391 | row.set_visible(False) 392 | 393 | else: 394 | for i in range(row_number, last_row): 395 | origin_entry = self.builder.get_object('*extras.scripts.{}.{}'.format(listbox_type, str(i + 1))) 396 | origin_row = origin_entry.get_parent().get_parent() 397 | destination_entry = self.builder.get_object('*extras.scripts.{}.{}'.format(listbox_type, str(i))) 398 | 399 | destination_entry.set_text(origin_entry.get_text()) 400 | 401 | if i + 1 == last_row: 402 | origin_entry.set_text('') 403 | origin_row.set_visible(False) 404 | 405 | add_button = self.builder.get_object('rowadd_button') 406 | add_button.set_sensitive(True) 407 | 408 | def on_add_scripts_row(self, button, *args): 409 | active_listbox_page = self.builder.get_object('scripts_notebook').get_current_page() 410 | 411 | if active_listbox_page == 0: 412 | listbox_type = 'sunrise' 413 | else: 414 | listbox_type = 'sunset' 415 | 416 | max_number_of_rows = 5 417 | last_row = get_last_visible_row(max_number_of_rows, '*extras.scripts.{}'.format(listbox_type), self.builder) 418 | 419 | next_row = self.builder.get_object('*extras.scripts.{}.{}'.format(listbox_type, str(last_row + 1))) \ 420 | .get_parent().get_parent() 421 | 422 | next_row.set_visible(True) 423 | 424 | if last_row + 1 == max_number_of_rows: 425 | button.set_sensitive(False) 426 | 427 | def on_change_scripts_page(self, notebook=None, *args): 428 | if notebook: 429 | active_listbox_page = notebook.get_current_page() 430 | 431 | # Get the opposite tab, because signal is emitted before switching 432 | if active_listbox_page == 0: 433 | listbox_type = 'sunset' 434 | else: 435 | listbox_type = 'sunrise' 436 | 437 | # If called from setup the statement above does not hold 438 | else: 439 | listbox_type = 'sunrise' 440 | 441 | max_number_of_rows = 5 442 | last_row = get_last_visible_row(max_number_of_rows, '*extras.scripts.{}'.format(listbox_type), self.builder) 443 | 444 | add_button = self.builder.get_object('rowadd_button') 445 | if last_row == max_number_of_rows: 446 | add_button.set_sensitive(False) 447 | else: 448 | add_button.set_sensitive(True) 449 | 450 | def on_any_change(self, emitter, *args): 451 | if self.listen_changes: 452 | emitter_path = split_id_delimiter(Gtk.Buildable.get_name(emitter))[0] 453 | if get_object_data(emitter) != read_dict(self.us_se, emitter_path.split('.')): 454 | if not (emitter in self.changed): 455 | self.changed.append(emitter) 456 | else: 457 | if emitter in self.changed: 458 | self.changed.remove(emitter) 459 | 460 | def on_float_entry_change(self, emitter, *args): 461 | text = emitter.get_text() 462 | if not text.strip() or not isfloat(text): 463 | emitter.set_icon_from_stock(0, 'gtk-dialog-error') 464 | emitter.set_icon_tooltip_text(0, 'Input should not be empty and contain only valid decimal (float) numbers') 465 | if emitter not in self.entries_error: 466 | self.entries_error.append(emitter) 467 | elif emitter.get_icon_stock(0) == 'gtk-dialog-error': 468 | emitter.set_icon_from_stock(0, None) 469 | if emitter in self.entries_error: 470 | self.entries_error.remove(emitter) 471 | 472 | def on_confirm_exit(self, *args): 473 | if self.changed: 474 | response = self.sub_windows['confirm_dialog'].run() 475 | # This should be destroy() but for some reason it won't work again once it's called 476 | self.sub_windows['confirm_dialog'].hide() 477 | if response == Gtk.ResponseType.YES: 478 | self.quit() 479 | elif response == Gtk.ResponseType.NO: 480 | self.on_save_settings() 481 | return True 482 | else: 483 | self.quit() 484 | 485 | # noinspection PyAttributeOutsideInit 486 | def on_save_settings(self, *args): 487 | if self.entries_error: 488 | self.sub_windows['error_dialog'].run() 489 | # This should also be destroy() 490 | self.sub_windows['error_dialog'].hide() 491 | else: 492 | for change_obj in self.changed: 493 | change_path = split_id_delimiter(Gtk.Buildable.get_name(change_obj))[0] 494 | write_dic(self.us_se, change_path.split('.'), get_object_data(change_obj)) 495 | self.saved_settings = True 496 | self.quit() 497 | 498 | 499 | def main(user_settings): 500 | app = App(user_settings) 501 | app.run() 502 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | AutomaThemely Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | 676 | --------------------------------------------------------------------------------