Skip to content

Commit

Permalink
v2.2.0
Browse files Browse the repository at this point in the history
  • Loading branch information
boramalper committed Nov 13, 2020
1 parent 0722283 commit d0f755f
Show file tree
Hide file tree
Showing 5 changed files with 146 additions and 61 deletions.
78 changes: 55 additions & 23 deletions himawaripy/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,12 @@
from PIL import Image
from dateutil.tz import tzlocal

from .utils import set_background, get_desktop_environment
from himawaripy.utils import set_background, get_desktop_environment

import ssl

# Semantic Versioning: Major, Minor, Patch
HIMAWARIPY_VERSION = (2, 1, 0)
HIMAWARIPY_VERSION = (2, 2, 0)
counter = None
HEIGHT = 550
WIDTH = 550
Expand Down Expand Up @@ -63,7 +63,7 @@ def download_chunk(args):

# If the tile data is 2867 bytes, it is a blank "No Image" tile.
if tiledata.__sizeof__() == 2867:
sys.exit('No image available for {}.'.format(strftime("%Y/%m/%d %H:%M:%S", latest)))
sys.exit("No image available for {}.".format(strftime("%Y/%m/%d %H:%M:%S", latest)))

with counter.get_lock():
counter.value += 1
Expand All @@ -75,29 +75,61 @@ def download_chunk(args):


def parse_args():
parser = argparse.ArgumentParser(description="set (near-realtime) picture of Earth as your desktop background",
epilog="https://labs.boramalper.org/himawaripy")
parser = argparse.ArgumentParser(
description="set (near-realtime) picture of Earth as your desktop background",
epilog="https://labs.boramalper.org/himawaripy",
)

parser.add_argument("--version", action="version", version="%(prog)s {}.{}.{}".format(*HIMAWARIPY_VERSION))

group = parser.add_mutually_exclusive_group()

group.add_argument("--auto-offset", action="store_true", dest="auto_offset", default=False,
help="determine offset automatically")
group.add_argument("-o", "--offset", type=int, dest="offset", default=10,
help="UTC time offset in hours, must be less than or equal to +10")

parser.add_argument("-l", "--level", type=int, choices=[4, 8, 16, 20], dest="level", default=4,
help="increases the quality (and the size) of each tile. possible values are 4, 8, 16, 20")
parser.add_argument("-d", "--deadline", type=int, dest="deadline", default=6,
help="deadline in minutes to download all the tiles, set 0 to cancel")
parser.add_argument("--save-battery", action="store_true", dest="save_battery", default=False,
help="stop refreshing on battery")
parser.add_argument("--output-dir", type=str, dest="output_dir",
help="directory to save the temporary background image",
default=appdirs.user_cache_dir(appname="himawaripy", appauthor=False))
parser.add_argument("--dont-change", action="store_true", dest="dont_change", default=False,
help="don't change the wallpaper (just download it)")
group.add_argument(
"--auto-offset", action="store_true", dest="auto_offset", default=False, help="determine offset automatically"
)
group.add_argument(
"-o",
"--offset",
type=int,
dest="offset",
default=10,
help="UTC time offset in hours, must be less than or equal to +10",
)

parser.add_argument(
"-l",
"--level",
type=int,
choices=[4, 8, 16, 20],
dest="level",
default=4,
help="increases the quality (and the size) of each tile. possible values are 4, 8, 16, 20",
)
parser.add_argument(
"-d",
"--deadline",
type=int,
dest="deadline",
default=6,
help="deadline in minutes to download all the tiles, set 0 to cancel",
)
parser.add_argument(
"--save-battery", action="store_true", dest="save_battery", default=False, help="stop refreshing on battery"
)
parser.add_argument(
"--output-dir",
type=str,
dest="output_dir",
help="directory to save the temporary background image",
default=appdirs.user_cache_dir(appname="himawaripy", appauthor=False),
)
parser.add_argument(
"--dont-change",
action="store_true",
dest="dont_change",
default=False,
help="don't change the wallpaper (just download it)",
)

args = parser.parse_args()

Expand All @@ -119,8 +151,8 @@ def is_discharging():
status = f.readline().strip()

return status == "Discharging"
elif sys.platform == 'darwin':
return b'discharging' in subprocess.check_output(["pmset", "-g", "batt"])
elif sys.platform == "darwin":
return b"discharging" in subprocess.check_output(["pmset", "-g", "batt"])

else:
sys.exit("Battery saving feature works only on linux or mac!\n")
Expand Down
120 changes: 84 additions & 36 deletions himawaripy/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,16 @@ def set_background(file_path):
de = get_desktop_environment()

if de == "mac":
subprocess.call(["osascript", "-e",
'tell application "System Events"\n'
'set theDesktops to a reference to every desktop\n'
'repeat with aDesktop in theDesktops\n'
'set the picture of aDesktop to \"' + file_path + '"\nend repeat\nend tell'])
subprocess.call(
[
"osascript",
"-e",
'tell application "System Events"\n'
"set theDesktops to a reference to every desktop\n"
"repeat with aDesktop in theDesktops\n"
'set the picture of aDesktop to "' + file_path + '"\nend repeat\nend tell',
]
)
else: # Linux
# gsettings requires it.
fetch_envvar("DBUS_SESSION_BUS_ADDRESS")
Expand All @@ -31,34 +36,52 @@ def set_background(file_path):
assert os.system('bash -c "gsettings set org.gnome.desktop.background draw-background true"') == 0
elif de == "mate":
subprocess.call(["gsettings", "set", "org.mate.background", "picture-filename", file_path])
elif de == 'i3':
subprocess.call(['feh', '--bg-max', file_path])
elif de == "i3":
subprocess.call(["feh", "--bg-max", file_path])
elif de == "xfce4":
# Xfce4 displays to change the background of
displays = subprocess.getoutput('xfconf-query --channel xfce4-desktop --list | grep last-image').split()
displays = subprocess.getoutput("xfconf-query --channel xfce4-desktop --list | grep last-image").split()

for display in displays:
subprocess.call(["xfconf-query", "--channel", "xfce4-desktop", "--property", display, "--set", file_path])
subprocess.call(
["xfconf-query", "--channel", "xfce4-desktop", "--property", display, "--set", file_path]
)
elif de == "lxde":
subprocess.call(["pcmanfm", "--set-wallpaper", file_path, "--wallpaper-mode=fit", ])
subprocess.call(
[
"pcmanfm",
"--set-wallpaper",
file_path,
"--wallpaper-mode=fit",
]
)
elif de == "kde":
if plasma_version() > LooseVersion("5.7"):
''' Command per https://github.com/boramalper/himawaripy/issues/57
Sets 'FillMode' to 1, which is "Scaled, Keep Proportions"
Forces 'Color' to black, which sets the background colour.
'''
script = 'var a = desktops();' \
'for (i = 0; i < a.length; i++) {{' \
'd = a[i];d.wallpaperPlugin = "org.kde.image";' \
'd.currentConfigGroup = Array("Wallpaper", "org.kde.image", "General");' \
'd.writeConfig("Image", "file://{}");' \
'd.writeConfig("FillMode", 1);' \
'd.writeConfig("Color", "#000");' \
'}}'
"""Command per https://github.com/boramalper/himawaripy/issues/57
Sets 'FillMode' to 1, which is "Scaled, Keep Proportions"
Forces 'Color' to black, which sets the background colour.
"""
script = (
"var a = desktops();"
"for (i = 0; i < a.length; i++) {{"
'd = a[i];d.wallpaperPlugin = "org.kde.image";'
'd.currentConfigGroup = Array("Wallpaper", "org.kde.image", "General");'
'd.writeConfig("Image", "file://{}");'
'd.writeConfig("FillMode", 1);'
'd.writeConfig("Color", "#000");'
"}}"
)
try:
subprocess.check_output(["qdbus", "org.kde.plasmashell", "/PlasmaShell",
"org.kde.PlasmaShell.evaluateScript", script.format(file_path)])
subprocess.check_output(
[
"qdbus",
"org.kde.plasmashell",
"/PlasmaShell",
"org.kde.PlasmaShell.evaluateScript",
script.format(file_path),
]
)
except subprocess.CalledProcessError as e:
if "Widgets are locked" in e.output.decode("utf-8"):
print("Cannot change the wallpaper while widgets are locked! (unlock the widgets)")
Expand All @@ -67,12 +90,16 @@ def set_background(file_path):
else:
print("Couldn't detect plasmashell 5.7 or higher.")
elif has_program("feh"):
print("Couldn't detect your desktop environment ('{}'), but you have "
"'feh' installed so we will use it...".format(de))
print(
"Couldn't detect your desktop environment ('{}'), but you have "
"'feh' installed so we will use it...".format(de)
)
subprocess.call(["feh", "--bg-max", file_path])
elif has_program("nitrogen"):
print("Couldn't detect your desktop environment ('{}'), but you have "
"'nitrogen' installed so we will use it...".format(de))
print(
"Couldn't detect your desktop environment ('{}'), but you have "
"'nitrogen' installed so we will use it...".format(de)
)
subprocess.call(["nitrogen", "--restore"])
else:
return False
Expand All @@ -97,9 +124,26 @@ def get_desktop_environment():
if desktop_session is not None:
# Easier to match if we don't have to deal with character cases
desktop_session = desktop_session.lower()
if desktop_session in ["gnome", "unity", "cinnamon", "mate", "xfce4", "lxde", "fluxbox",
"blackbox", "openbox", "icewm", "jwm", "afterstep", "trinity", "kde", "pantheon",
"gnome-classic", "i3", "budgie-desktop"]:
if desktop_session in [
"gnome",
"unity",
"cinnamon",
"mate",
"xfce4",
"lxde",
"fluxbox",
"blackbox",
"openbox",
"icewm",
"jwm",
"afterstep",
"trinity",
"kde",
"pantheon",
"gnome-classic",
"i3",
"budgie-desktop",
]:
return desktop_session
## Special cases ##
# Canonical sets $DESKTOP_SESSION to Lubuntu rather than LXDE if using LXDE.
Expand All @@ -122,10 +166,10 @@ def get_desktop_environment():
fetch_envvar("KDE_FULL_SESSION")
fetch_envvar("GNOME_DESKTOP_SESSION_ID")

if os.environ.get('KDE_FULL_SESSION') == 'true':
if os.environ.get("KDE_FULL_SESSION") == "true":
return "kde"
elif os.environ.get('GNOME_DESKTOP_SESSION_ID'):
if "deprecated" not in os.environ.get('GNOME_DESKTOP_SESSION_ID'):
elif os.environ.get("GNOME_DESKTOP_SESSION_ID"):
if "deprecated" not in os.environ.get("GNOME_DESKTOP_SESSION_ID"):
return "gnome2"
# From http://ubuntuforums.org/showthread.php?t=652320
elif is_running("xfce-mcs-manage"):
Expand Down Expand Up @@ -195,7 +239,11 @@ def fetch_envvar(varname):
if varname in os.environ:
return

val = os.popen('bash -c "grep -z ^{}= /proc/$(pgrep -n pulseaudio)/environ | cut -d= -f2-"'.format(varname)).read().strip("\0\n")
val = (
os.popen('bash -c "grep -z ^{}= /proc/$(pgrep -n pulseaudio)/environ | cut -d= -f2-"'.format(varname))
.read()
.strip("\0\n")
)
if val:
print("Fetched env. var. {} as `{}`".format(varname, val))
os.environ[varname] = val
Expand Down
3 changes: 3 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[tool.black]
line-length = 120
target-version = ["py37"]
2 changes: 2 additions & 0 deletions requirements-dev.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
black==20.8b1
twine~=3.2.0
4 changes: 2 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@

setup(
name="himawaripy",
version="2.1.0",
url="http://labs.boramalper.org/himawaripy",
version="2.2.0",
url="https://labs.boramalper.org/himawaripy",
author="Bora M. Alper",
author_email="[email protected]",
license="MIT",
Expand Down

0 comments on commit d0f755f

Please sign in to comment.