Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Code cleanup #155

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "pokemon-terminal",
"version": "1.1.0",
"version": "1.2.0",
"description": "Pokemon terminal themes",
"bin": {
"pokemon": "pokemon",
Expand Down
1 change: 0 additions & 1 deletion pokemonterminal/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,5 @@
Supports iTerm2, Terminology, Tilix and ConEmu.
"""


__version__ = "1.1.0"
__author__ = "LazoCoder"
29 changes: 14 additions & 15 deletions pokemonterminal/command_flags.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import sys as sys
import argparse
import pokemonterminal.filters as filters
from pokemonterminal.database import Database
import sys

from pokemonterminal import filters
from pokemonterminal.database import Database

parser = argparse.ArgumentParser(
description='Set a pokemon to the current terminal background or '
'wallpaper',
'wallpaper',
epilog='Not setting any filters will get a completely random pokemon')

_filters_group = parser.add_argument_group(
'Filters', 'Arguments used to filter the list of pokemons with '
'various conditions that then will be picked')
'various conditions that then will be picked')
_filters_group.add_argument(
'-n',
'--name',
Expand All @@ -30,7 +30,7 @@
'-l',
'--light',
help='Filter out the pokemons darker (lightness threshold lower) ' +
'then 0.xx (default is 0.7)',
'then 0.xx (default is 0.7)',
default=0.7,
const=0.7,
metavar='0.xx',
Expand All @@ -41,7 +41,7 @@
'-d',
'--dark',
help='Filter out the pokemons lighter (lightness threshold higher) ' +
'then 0.xx (default is 0.42)',
'then 0.xx (default is 0.42)',
default=0.42,
const=0.42,
metavar='0.xx',
Expand Down Expand Up @@ -74,37 +74,36 @@
'-ss',
'--slideshow',
help='Instead of simply choosing a random pokemon ' +
'from the filtered list, starts a slideshow (with X minutes ' +
'of delay between pokemon) in the background with the ' +
'pokemon that matched the filters',
'from the filtered list, starts a slideshow (with X minutes ' +
'of delay between pokemon) in the background with the ' +
'pokemon that matched the filters',
const=10.0, nargs='?', type=float, metavar='X')


is_slideshow = '-ss' in sys.argv or '--slideshow' in sys.argv
_misc_group.add_argument(
'-w',
'--wallpaper',
help='Changes the desktop wallpaper instead of the terminal '
'background',
'background',
action='store_true')
_misc_group.add_argument(
'-v', '--verbose', help='Enables verbose output', action='store_true')
_misc_group.add_argument(
'-dr',
'--dry-run',
help='Implies -v and doesn\'t actually changes either wallpaper '
'or background after the pokemon has been chosen',
'or background after the pokemon has been chosen',
action='store_true')
either = parser.add_mutually_exclusive_group()
either.add_argument(
'-c',
'--clear',
help='Clears the current pokemon from terminal '
'background and quits.',
'background and quits.',
action='store_true')
either.add_argument(
'id',
help='Specify the wanted pokemon ID or the exact (case insensitive)' +
' name',
' name',
nargs='?',
default=0, const=0)
2 changes: 1 addition & 1 deletion pokemonterminal/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ def __load_data(self):
pkmn_type_snd, dark_threshold)
self.__pokemon_type_dictionary[pkmn_type].append(pokemon)
if pkmn_type_snd != '':
self.__pokemon_type_dictionary[pkmn_type_snd]\
self.__pokemon_type_dictionary[pkmn_type_snd] \
.append(pokemon)
self.__pokemon_list.append(pokemon)
self.__pokemon_dictionary[pokemon.get_name()] = pokemon
Expand Down
3 changes: 2 additions & 1 deletion pokemonterminal/filters.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from argparse import Action

from pokemonterminal.database import Database, Pokemon


Expand Down Expand Up @@ -52,7 +53,7 @@ class TypeFilter(Filter):

def matches(self, pokemon: Pokemon, value: list):
return pokemon.get_pkmn_type() in value or \
pokemon.get_pkmn_type_secondary() in value
pokemon.get_pkmn_type_secondary() in value


class NonExtrasFilter(Filter):
Expand Down
8 changes: 2 additions & 6 deletions pokemonterminal/main.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,14 @@
#!/usr/bin/env python3.6
"""The main module that brings everything together."""

import os
import random
import sys
from multiprocessing import Process
from pathlib import Path

from . import scripter, slideshow
from pokemonterminal.command_flags import parser, is_slideshow
from pokemonterminal.command_flags import is_slideshow, parser
from pokemonterminal.database import Database
from pokemonterminal.filters import Filter
from pokemonterminal.platform import PlatformNamedEvent

from . import scripter, slideshow


def main(argv=None):
Expand Down
2 changes: 1 addition & 1 deletion pokemonterminal/platform/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@
else:
from .named_event.posix import PosixNamedEvent as platform_event

PlatformNamedEvent = platform_event
PlatformNamedEvent = platform_event
1 change: 1 addition & 0 deletions pokemonterminal/platform/named_event/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from abc import ABC, abstractmethod


class NamedEvent(ABC):
"""
Interface representing an operating system event object with a name.
Expand Down
7 changes: 4 additions & 3 deletions pokemonterminal/platform/named_event/posix.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import os
import sys
import time
from pathlib import PosixPath

from . import NamedEvent
from pathlib import PosixPath


class PosixNamedEvent(NamedEvent):
"""
Expand Down Expand Up @@ -31,6 +31,7 @@ def __has_open_file_handles(path: PosixPath) -> bool:
# TODO
raise NotImplementedError("macOS doesn't have /proc")

@staticmethod
def exists(name: str) -> bool:
p = PosixNamedEvent.__build_fifo_path(name)
if not p.is_fifo():
Expand All @@ -45,7 +46,7 @@ def __init__(self, name: str):
os.mkfifo(p)

self.__path = p
self.__fifo = os.open(p, os.O_NONBLOCK) # Keep a handle to the FIFO for exists() to detect us
self.__fifo = os.open(p, os.O_NONBLOCK) # Keep a handle to the FIFO for exists() to detect us
self.__fifo_in = None
self.__fifo_out = None
self.__name = name
Expand Down
5 changes: 4 additions & 1 deletion pokemonterminal/platform/named_event/win.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from . import NamedEvent


class WindowsNamedEvent(NamedEvent):
"""
Named events using the native Windows APIs
Expand All @@ -21,8 +22,10 @@ def __raise_last_error():
err_no = ctypes.GetLastError()
raise WindowsError(err_no, ctypes.FormatError(err_no))

@staticmethod
def exists(name: str) -> bool:
event = ctypes.windll.kernel32.OpenEventW(WindowsNamedEvent.__SYNCHRONIZE | WindowsNamedEvent.__EVENT_MODIFY_STATE, False, name)
event = ctypes.windll.kernel32.OpenEventW(
WindowsNamedEvent.__SYNCHRONIZE | WindowsNamedEvent.__EVENT_MODIFY_STATE, False, name)
if event == 0:
if ctypes.GetLastError() == WindowsNamedEvent.__ERROR_FILE_NOT_FOUND:
return False
Expand Down
13 changes: 10 additions & 3 deletions pokemonterminal/slideshow.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,27 @@
import multiprocessing
import random
import sys
from threading import Thread

from .platform import PlatformNamedEvent
from threading import Thread


def __print_fork(pid, length, delay):
print(f"Starting slideshow with {length} Pokemons and a delay of {delay} minutes.")
print(f"Forked process to background with PID {pid}.")
print("You can stop it with 'pokemon -c'. (add '-w' if this is a wallpaper slideshow)")


def __event_listener(event):
event.wait()


def __get_listener_thread(event):
t = Thread(target=__event_listener, args=(event, ), daemon=True)
t = Thread(target=__event_listener, args=(event,), daemon=True)
t.start()
return t


def __slideshow_worker(filtered, delay, changer_func, event_name):
with PlatformNamedEvent(event_name) as e:
t = __get_listener_thread(e)
Expand All @@ -33,14 +37,17 @@ def __slideshow_worker(filtered, delay, changer_func, event_name):
changer_func(next_pkmn.get_path())
t.join(delay * 60)


def start(filtered, delay, changer_func, event_name):
p = multiprocessing.Process(target=__slideshow_worker, args=(filtered, delay, changer_func, event_name, ), daemon=True)
p = multiprocessing.Process(target=__slideshow_worker, args=(filtered, delay, changer_func, event_name,),
daemon=True)
p.start()
__print_fork(p.pid, len(filtered), delay)
# HACK remove multiprocessing's exit handler to prevent it killing our child.
atexit.unregister(multiprocessing.util._exit_function)
sys.exit(0)


def stop(event_name):
with PlatformNamedEvent(event_name) as e:
e.signal()
3 changes: 2 additions & 1 deletion pokemonterminal/terminal/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import os
import importlib
import inspect
import os

from .adapters import TerminalProvider


Expand Down
1 change: 1 addition & 0 deletions pokemonterminal/terminal/adapters/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from abc import ABC, abstractmethod


class TerminalProvider(ABC):
"""
Interface representing all the different terminal emulators supported
Expand Down
6 changes: 5 additions & 1 deletion pokemonterminal/terminal/adapters/conemu.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,24 @@

class ConEmuProvider(_TProv):

@staticmethod
def is_compatible() -> bool:
return "CONEMUPID" in os.environ

@staticmethod
def __run_command(command: str):
output = subprocess.check_output(f"ConEmuC -GuiMacro {command}", shell=True).decode(sys.stdout.encoding)
if output != 'OK':
print(output)

@staticmethod
def change_terminal(path: str):
# ConEmuC supports its own character escaping, so escape the backslashes just to be sure
ConEmuProvider.__run_command('SetOption("Background Image", "{}")'.format(path.replace("\\", "\\\\")))

@staticmethod
def clear():
ConEmuProvider.__run_command('SetOption("Background Image", "")')

def __str__():
def __repr__(self):
return "ConEmu"
8 changes: 6 additions & 2 deletions pokemonterminal/terminal/adapters/iterm.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,23 +12,27 @@ class ItermProvider(_TProv):
\tend tell
end tell"""

@staticmethod
def is_compatible() -> bool:
return "ITERM_PROFILE" in os.environ

@staticmethod
def __run_osascript(stream):
p = subprocess.Popen(["osascript"], stdout=subprocess.PIPE,
stdin=subprocess.PIPE)
p.stdin.write(stream)
p.communicate()
p.stdin.close()

@staticmethod
def change_terminal(path: str):
stdin = ItermProvider.__osa_script_fmt.format(path)
ItermProvider.__run_osascript(str.encode(stdin))

@staticmethod
def clear():
stdin = ItermProvider.__osa_script_fmt.format("")
ItermProvider.__run_osascript(str.encode(stdin))

def __str__():
return "iTerm 2"
def __repr__(self):
return "iTerm 2"
7 changes: 5 additions & 2 deletions pokemonterminal/terminal/adapters/terminology.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,17 @@


class TerminologyProvider(_TProv):
@staticmethod
def is_compatible() -> bool:
return environ.get("TERMINOLOGY") == '1'

@staticmethod
def change_terminal(path: str):
run(["tybg", path], check=True)

@staticmethod
def clear():
run("tybg", check=True)

def __str__():
return "Terminology"
def __repr__(self):
return "Terminology"
5 changes: 4 additions & 1 deletion pokemonterminal/terminal/adapters/tilix.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,17 @@ class TilixProvider(_TProv):
__setting_key = "com.gexperts.Tilix.Settings"
__setting_field = "background-image"

@staticmethod
def is_compatible() -> bool:
return "TILIX_ID" in environ

@staticmethod
def change_terminal(path: str):
run(["gsettings", "set", TilixProvider.__setting_key, TilixProvider.__setting_field, path], check=True)

@staticmethod
def clear():
run(["gsettings", "reset", TilixProvider.__setting_key, TilixProvider.__setting_field], check=True)

def __str__():
def __repr__(self):
return "Tilix"
3 changes: 2 additions & 1 deletion pokemonterminal/wallpaper/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import os
import importlib
import inspect
import os

from .adapters import WallpaperProvider


Expand Down
1 change: 1 addition & 0 deletions pokemonterminal/wallpaper/adapters/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from abc import ABC, abstractmethod


class WallpaperProvider(ABC):
"""
Interface representing all the different desktop environments supported
Expand Down
Loading