Skip to content

Commit

Permalink
Merge pull request #129
Browse files Browse the repository at this point in the history
Code style pre-commit hooks
  • Loading branch information
spyoungtech committed Nov 10, 2021
2 parents cd32d35 + e5d0446 commit e481bae
Show file tree
Hide file tree
Showing 33 changed files with 471 additions and 452 deletions.
9 changes: 9 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,12 @@ repos:
- id: check-yaml
- id: end-of-file-fixer
- id: trailing-whitespace
- id: double-quote-string-fixer
- repo: https://github.com/psf/black
rev: '21.10b0'
hooks:
- id: black
args:
- "-S"
- "-l"
- "120"
2 changes: 1 addition & 1 deletion README.md
1 change: 1 addition & 0 deletions ahk/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from ahk.autohotkey import AHK, ActionChain, AsyncAHK
from ahk.keyboard import Hotkey

__all__ = ['AHK']
11 changes: 9 additions & 2 deletions ahk/autohotkey.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ class AHK(WindowMixin, MouseMixin, KeyboardMixin, ScreenMixin, SoundMixin, Regis

pass


#
class AsyncAHK(
AsyncMouseMixin,
Expand All @@ -32,7 +33,7 @@ class AsyncAHK(
AsyncScreenMixin,
AsyncSoundMixin,
AsyncRegistryMixin,
AsyncGUIMixin
AsyncGUIMixin,
):
...

Expand Down Expand Up @@ -66,5 +67,11 @@ def sleep(self, n):
:return:
"""
n = n * 1000 # convert to milliseconds
script = self.render_template('base.ahk', body=f'Sleep {n}', directives={'#Persistent',})
script = self.render_template(
'base.ahk',
body=f'Sleep {n}',
directives={
'#Persistent',
},
)
self.run_script(script)
40 changes: 21 additions & 19 deletions ahk/daemon.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,24 @@
import queue
import atexit


def escape(s):
s = s.replace('\n', '`n')
return s


class STOP:
"""A sentinel value"""

...


class AHKDaemon(AHK):
proc: subprocess.Popen
_template_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'templates')
_template = os.path.join(_template_path, 'daemon.ahk')
_template_overrides = os.listdir(f'{_template_path}/daemon')

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.queue = queue.Queue()
Expand All @@ -35,13 +40,10 @@ def __init__(self, *args, **kwargs):

def _run(self):
if self._is_running:
raise RuntimeError("Already running")
raise RuntimeError('Already running')
self._is_running = True
runargs = [self.executable_path, self._template]
proc = subprocess.Popen(runargs,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
proc = subprocess.Popen(runargs, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
self.proc = proc
atexit.register(self.proc.terminate)

Expand Down Expand Up @@ -94,14 +96,14 @@ def render_template(self, template_name, directives=None, blocking=True, **kwarg

def run_script(self, script_text: str, decode=True, blocking=True, **runkwargs):
if not blocking:
warnings.warn("blocking=False in daemon mode is not supported", stacklevel=3)
warnings.warn('blocking=False in daemon mode is not supported', stacklevel=3)
if not self._is_running:
raise RuntimeError("Not running! Must call .start() first!")
raise RuntimeError('Not running! Must call .start() first!')
script_text = script_text.replace('#NoEnv', '', 1)
with self.run_lock:
for line in script_text.split('\n'):
line = line.strip()
if not line or line.startswith("FileAppend"):
if not line or line.startswith('FileAppend'):
continue
self.queue.put_nowait(line.encode('utf-8'))
self.queue.join()
Expand All @@ -118,14 +120,14 @@ def type(self, s, *args, **kwargs):
s = escape(s)
self.send(s, *args, **kwargs)

def show_tooltip(self, text: str, second=None, x="", y="", id="", blocking=True):
def show_tooltip(self, text: str, second=None, x='', y='', id='', blocking=True):
return super().show_tooltip(text, second=second, x=x, y=y, id=id, blocking=blocking)

def hide_tooltip(self, id):
return super().show_tooltip(text='', second='', x='', y='', id=id)

def hide_traytip(self):
self.run_script("HideTrayTip")
self.run_script('HideTrayTip')

@staticmethod
def escape_sequence_replace(s):
Expand All @@ -138,6 +140,7 @@ class AsyncAHKDaemon(AsyncAHK):
_template_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'templates')
_template = os.path.join(_template_path, 'daemon.ahk')
_template_overrides = os.listdir(f'{_template_path}/daemon')

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.queue = asyncio.Queue()
Expand All @@ -152,13 +155,12 @@ def __init__(self, *args, **kwargs):

async def _run(self):
if self._is_running:
raise RuntimeError("Already running")
raise RuntimeError('Already running')
self._is_running = True
runargs = [self.executable_path, self._template]
proc = await asyncio.subprocess.create_subprocess_exec(*runargs,
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE)
proc = await asyncio.subprocess.create_subprocess_exec(
*runargs, stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
)
self.proc = proc

async def _get_command(self):
Expand Down Expand Up @@ -212,12 +214,12 @@ def render_template(self, template_name, directives=None, blocking=True, **kwarg

async def a_run_script(self, script_text: str, decode=True, blocking=True, **runkwargs):
if not self._is_running:
raise RuntimeError("Not running! Must await .start() first!")
raise RuntimeError('Not running! Must await .start() first!')
script_text = script_text.replace('#NoEnv', '', 1)
async with self.run_lock:
for line in script_text.split('\n'):
line = line.strip()
if not line or line.startswith("FileAppend"):
if not line or line.startswith('FileAppend'):
continue
self.queue.put_nowait(line.encode('utf-8'))
await self.queue.join()
Expand All @@ -234,14 +236,14 @@ async def type(self, s, *args, **kwargs):
s = escape(s)
await self.send(s, *args, **kwargs)

def show_tooltip(self, text: str, second=None, x="", y="", id="", blocking=True):
def show_tooltip(self, text: str, second=None, x='', y='', id='', blocking=True):
return super().show_tooltip(text, second=second, x=x, y=y, id=id, blocking=blocking)

def hide_tooltip(self, id):
return super().show_tooltip(text='', second='', x='', y='', id=id)

async def hide_traytip(self):
await self.run_script("HideTrayTip")
await self.run_script('HideTrayTip')

@staticmethod
def escape_sequence_replace(s):
Expand Down
6 changes: 4 additions & 2 deletions ahk/directives.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@ class DirectiveMeta(type):
Overrides __str__ so directives with no arguments can be used without instantiation
Overrides __hash__ to make objects 'unique' based upon a hash of the str representation
"""

def __str__(cls):
return f"#{cls.__name__}"
return f'#{cls.__name__}'

def __hash__(self):
return hash(str(self))
Expand All @@ -26,6 +27,7 @@ class Directive(SimpleNamespace, metaclass=DirectiveMeta):
They are designed to be hashable and comparable with string equivalent of AHK directive.
Directives that don't require arguments do not need to be instantiated.
"""

def __init__(self, **kwargs):
super().__init__(name=self.name, **kwargs)
self._kwargs = kwargs
Expand All @@ -39,7 +41,7 @@ def __str__(self):
arguments = ' '.join(str(value) for key, value in self._kwargs.items())
else:
arguments = ''
return f"#{self.name} {arguments}".rstrip()
return f'#{self.name} {arguments}'.rstrip()

def __eq__(self, other):
return str(self) == other
Expand Down
14 changes: 7 additions & 7 deletions ahk/gui.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ def __init__(self, *args, **kwargs):
self.window_encoding = kwargs.pop('window_encoding', None)
super().__init__(*args, **kwargs)

def show_tooltip(self, text: str, second=1.0, x="", y="", id="", blocking=True):
def show_tooltip(self, text: str, second=1.0, x='', y='', id='', blocking=True):
"""Show ToolTip
https://www.autohotkey.com/docs/commands/ToolTip.htm
Expand All @@ -29,10 +29,10 @@ def show_tooltip(self, text: str, second=1.0, x="", y="", id="", blocking=True):
:raises ValueError: ID must be between [1, 20]
"""
if id and not (1 <= int(id) <= 20):
raise ValueError("ID value must be between [1, 20]")
raise ValueError('ID value must be between [1, 20]')

encoded_text = "% " + "".join([f"Chr({hex(ord(char))})" for char in text])
script = self.render_template("gui/tooltip.ahk", text=encoded_text, second=second, x=x, y=y, id=id)
encoded_text = '% ' + ''.join([f'Chr({hex(ord(char))})' for char in text])
script = self.render_template('gui/tooltip.ahk', text=encoded_text, second=second, x=x, y=y, id=id)
return self.run_script(script, blocking=blocking) or None

def _show_traytip(
Expand All @@ -56,11 +56,11 @@ def _show_traytip(
:type large_icon: bool, optional
"""

encoded_title = "% " + "".join([f"Chr({hex(ord(char))})" for char in title])
encoded_text = "% " + "".join([f"Chr({hex(ord(char))})" for char in text])
encoded_title = '% ' + ''.join([f'Chr({hex(ord(char))})' for char in title])
encoded_text = '% ' + ''.join([f'Chr({hex(ord(char))})' for char in text])
option = type_id + (16 if slient else 0) + (32 if large_icon else 0)
script = self.render_template(
"gui/traytip.ahk", title=encoded_title, text=encoded_text, second=second, option=option
'gui/traytip.ahk', title=encoded_title, text=encoded_text, second=second, option=option
)
return self.run_script(script, blocking=blocking) or None

Expand Down
Loading

0 comments on commit e481bae

Please sign in to comment.