Skip to content

Instantly share code, notes, and snippets.

@tdgroot
Created September 20, 2024 06:07
Show Gist options
  • Save tdgroot/0659ae7efb1f95f580a74984b67b36d6 to your computer and use it in GitHub Desktop.
Save tdgroot/0659ae7efb1f95f580a74984b67b36d6 to your computer and use it in GitHub Desktop.
GNOME automatic dark mode
#!/usr/bin/env python3
import gi
from gi.repository import Gio
import datetime
import json
import os
import requests
from pathlib import Path
from astral import Observer
from astral.sun import sun
AUTODARK_CACHE_PATH = Path(os.environ["HOME"] + "/.cache/autodark")
def enable_darkmode():
desktop_settings = Gio.Settings.new("org.gnome.desktop.interface")
if desktop_settings.get_string("color-scheme") != "prefer-dark":
desktop_settings.set_string("color-scheme", "prefer-dark")
def disable_darkmode():
desktop_settings = Gio.Settings.new("org.gnome.desktop.interface")
target = "default" # default or prefer-light
if desktop_settings.get_string("color-scheme") != target:
desktop_settings.set_string("color-scheme", target)
def get_ipinfo():
IPINFO_CACHE_PATH = AUTODARK_CACHE_PATH / "ipinfo.json"
try:
resp = requests.get("https://ipinfo.io/")
resp.raise_for_status()
result = resp.json()
with open(IPINFO_CACHE_PATH, "w") as f:
print(f"Writing to {IPINFO_CACHE_PATH}")
json.dump(result, f)
except requests.exceptions.RequestException:
with open(IPINFO_CACHE_PATH) as f:
result = json.load(f)
return result
def get_current_location():
return get_ipinfo()["loc"].split(",")
def main():
os.makedirs(AUTODARK_CACHE_PATH, exist_ok=True)
print("Fetching location...")
lat, lon = get_current_location()
print("Location: ", lat, lon)
print("Calculating sunset...")
location = Observer(lat, lon)
s = sun(location, date=datetime.date.today())
sunrise_utc = s["sunrise"]
sunset_utc = s["sunset"]
print("Sunrise (utc): ", sunrise_utc)
print("Sunset (utc): ", sunset_utc)
sunrise_local = sunrise_utc.astimezone()
sunset_local = sunset_utc.astimezone()
now_local = datetime.datetime.now().astimezone()
print("Sunrise (local): ", sunrise_local)
print("Sunset (local): ", sunset_local)
print("Now: ", now_local)
target_dark = sunset_local - datetime.timedelta(hours=1)
target_light = sunrise_local + datetime.timedelta(hours=1)
print("Target dark: ", target_dark)
print("Target light: ", target_light)
if now_local > target_dark or now_local < target_light:
print("It's dark")
enable_darkmode()
else:
print("It's light")
disable_darkmode()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment