Skip to content

Commit

Permalink
black: format the world
Browse files Browse the repository at this point in the history
  • Loading branch information
deltragon committed Jul 26, 2024
1 parent eeb0958 commit 773d44d
Show file tree
Hide file tree
Showing 23 changed files with 1,464 additions and 1,037 deletions.
81 changes: 52 additions & 29 deletions safeeyes/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
from safeeyes.safeeyes import SAFE_EYES_VERSION
from safeeyes.rpc import RPCClient

gettext.install('safeeyes', utility.LOCALE_PATH)
gettext.install("safeeyes", utility.LOCALE_PATH)


def __running():
Expand All @@ -52,9 +52,8 @@ def __running():
else:
# In older versions cmdline was a list object
cmd_line = proc.cmdline
if (
('python3' in cmd_line[0] or 'python' in cmd_line[0])
and ('safeeyes' in cmd_line[1] or 'safeeyes' in cmd_line)
if ("python3" in cmd_line[0] or "python" in cmd_line[0]) and (
"safeeyes" in cmd_line[1] or "safeeyes" in cmd_line
):
process_count += 1
if process_count > 1:
Expand All @@ -71,40 +70,60 @@ def main():
Start the Safe Eyes.
"""
system_locale = gettext.translation(
'safeeyes',
"safeeyes",
localedir=utility.LOCALE_PATH,
languages=[utility.system_locale(), 'en_US'],
fallback=True
languages=[utility.system_locale(), "en_US"],
fallback=True,
)
system_locale.install()
try:
# locale.bindtextdomain is required for Glade files
locale.bindtextdomain('safeeyes', utility.LOCALE_PATH)
locale.bindtextdomain("safeeyes", utility.LOCALE_PATH)
except AttributeError:
logging.warning(
'installed python\'s gettext module does not support locale.bindtextdomain. locale.bindtextdomain is required for Glade files' # noqa: E501
"installed python's gettext module does not support locale.bindtextdomain. locale.bindtextdomain is required for Glade files" # noqa: E501
)

parser = argparse.ArgumentParser(prog='safeeyes', description=_('description'))
parser = argparse.ArgumentParser(prog="safeeyes", description=_("description"))
group = parser.add_mutually_exclusive_group()
group.add_argument('-a', '--about', help=_('show the about dialog'), action='store_true')
group.add_argument(
'-d',
'--disable',
help=_('disable the currently running safeeyes instance'),
action='store_true'
"-a", "--about", help=_("show the about dialog"), action="store_true"
)
group.add_argument(
"-d",
"--disable",
help=_("disable the currently running safeeyes instance"),
action="store_true",
)
group.add_argument(
"-e",
"--enable",
help=_("enable the currently running safeeyes instance"),
action="store_true",
)
group.add_argument(
"-q",
"--quit",
help=_("quit the running safeeyes instance and exit"),
action="store_true",
)
group.add_argument(
"-s", "--settings", help=_("show the settings dialog"), action="store_true"
)
group.add_argument(
"-t", "--take-break", help=_("Take a break now").lower(), action="store_true"
)
parser.add_argument(
"--debug", help=_("start safeeyes in debug mode"), action="store_true"
)
parser.add_argument(
"--status",
help=_("print the status of running safeeyes instance and exit"),
action="store_true",
)
group.add_argument('-e', '--enable', help=_('enable the currently running safeeyes instance'), action='store_true')
group.add_argument('-q', '--quit', help=_('quit the running safeeyes instance and exit'), action='store_true')
group.add_argument('-s', '--settings', help=_('show the settings dialog'), action='store_true')
group.add_argument('-t', '--take-break', help=_('Take a break now').lower(), action='store_true')
parser.add_argument('--debug', help=_('start safeeyes in debug mode'), action='store_true')
parser.add_argument(
'--status',
help=_('print the status of running safeeyes instance and exit'),
action='store_true'
"--version", action="version", version="%(prog)s " + SAFE_EYES_VERSION
)
parser.add_argument('--version', action='version', version='%(prog)s ' + SAFE_EYES_VERSION)
args = parser.parse_args()

# Initialize the logging
Expand All @@ -116,10 +135,14 @@ def main():
logging.info("Safe Eyes is already running")
if not config.get("use_rpc_server", True):
# RPC sever is disabled
print(_('Safe Eyes is running without an RPC server. Turn it on to use command-line arguments.'))
print(
_(
"Safe Eyes is running without an RPC server. Turn it on to use command-line arguments."
)
)
sys.exit(0)
return
rpc_client = RPCClient(config.get('rpc_port'))
rpc_client = RPCClient(config.get("rpc_port"))
if args.about:
rpc_client.show_about()
elif args.disable:
Expand All @@ -140,14 +163,14 @@ def main():
sys.exit(0)
else:
if args.status:
print(_('Safe Eyes is not running'))
print(_("Safe Eyes is not running"))
sys.exit(0)
elif not args.quit:
logging.info("Starting Safe Eyes")
safe_eyes = SafeEyes(system_locale, config, args)
safe_eyes.start()


if __name__ == '__main__':
signal.signal(signal.SIGINT, signal.SIG_DFL) # Handle Ctrl + C
if __name__ == "__main__":
signal.signal(signal.SIGINT, signal.SIG_DFL) # Handle Ctrl + C
main()
102 changes: 63 additions & 39 deletions safeeyes/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,20 +64,22 @@ def __init__(self, context):
self.waiting_condition = threading.Condition()
self.lock = threading.Lock()
self.context = context
self.context['skipped'] = False
self.context['postponed'] = False
self.context['skip_button_disabled'] = False
self.context['postpone_button_disabled'] = False
self.context['state'] = State.WAITING
self.context["skipped"] = False
self.context["postponed"] = False
self.context["skip_button_disabled"] = False
self.context["postpone_button_disabled"] = False
self.context["state"] = State.WAITING

def initialize(self, config):
"""
Initialize the internal properties from configuration
"""
logging.info("Initialize the core")
self.pre_break_warning_time = config.get('pre_break_warning_time')
self.pre_break_warning_time = config.get("pre_break_warning_time")
self.break_queue = BreakQueue(config, self.context)
self.default_postpone_duration = config.get('postpone_duration') * 60 # Convert to seconds
self.default_postpone_duration = (
config.get("postpone_duration") * 60
) # Convert to seconds
self.postpone_duration = self.default_postpone_duration

def start(self, next_break_time=-1, reset_breaks=False):
Expand Down Expand Up @@ -110,16 +112,16 @@ def stop(self, is_resting=False):
# Stop the break thread
self.waiting_condition.acquire()
self.running = False
if self.context['state'] != State.QUIT:
self.context['state'] = State.RESTING if (is_resting) else State.STOPPED
if self.context["state"] != State.QUIT:
self.context["state"] = State.RESTING if (is_resting) else State.STOPPED
self.waiting_condition.notify_all()
self.waiting_condition.release()

def skip(self):
"""
User skipped the break using Skip button
"""
self.context['skipped'] = True
self.context["skipped"] = True

def postpone(self, duration=-1):
"""
Expand All @@ -130,7 +132,7 @@ def postpone(self, duration=-1):
else:
self.postpone_duration = self.default_postpone_duration
logging.debug("Postpone the break for %d seconds", self.postpone_duration)
self.context['postponed'] = True
self.context["postponed"] = True

def get_break_time(self, break_type=None):
"""
Expand All @@ -139,8 +141,9 @@ def get_break_time(self, break_type=None):
break_obj = self.break_queue.get_break(break_type)
if not break_obj:
return False
time = self.scheduled_next_break_time + \
datetime.timedelta(minutes=break_obj.time - self.break_queue.get_break().time)
time = self.scheduled_next_break_time + datetime.timedelta(
minutes=break_obj.time - self.break_queue.get_break().time
)
return time

def take_break(self, break_type=None):
Expand All @@ -149,7 +152,7 @@ def take_break(self, break_type=None):
"""
if self.break_queue.is_empty():
return
if not self.context['state'] == State.WAITING:
if not self.context["state"] == State.WAITING:
return
utility.start_thread(self.__take_break, break_type=break_type)

Expand All @@ -163,7 +166,7 @@ def __take_break(self, break_type=None):
"""
Show the next break screen
"""
logging.info('Take a break due to external request')
logging.info("Take a break due to external request")

with self.lock:
if not self.running:
Expand Down Expand Up @@ -193,31 +196,43 @@ def __scheduler_job(self):
current_time = datetime.datetime.now()
current_timestamp = current_time.timestamp()

if self.context['state'] == State.RESTING and self.paused_time > -1:
if self.context["state"] == State.RESTING and self.paused_time > -1:
# Safe Eyes was resting
paused_duration = int(current_timestamp - self.paused_time)
self.paused_time = -1
if paused_duration > self.break_queue.get_break(BreakType.LONG_BREAK).duration:
logging.info('Skip next long break due to the pause %ds longer than break duration', paused_duration)
if (
paused_duration
> self.break_queue.get_break(BreakType.LONG_BREAK).duration
):
logging.info(
"Skip next long break due to the pause %ds longer than break duration",
paused_duration,
)
# Skip the next long break
self.break_queue.reset()

if self.context['postponed']:
if self.context["postponed"]:
# Previous break was postponed
logging.info('Prepare for postponed break')
logging.info("Prepare for postponed break")
time_to_wait = self.postpone_duration
self.context['postponed'] = False
self.context["postponed"] = False
elif current_timestamp < self.scheduled_next_break_timestamp:
# Non-standard break was set.
time_to_wait = round(self.scheduled_next_break_timestamp - current_timestamp)
time_to_wait = round(
self.scheduled_next_break_timestamp - current_timestamp
)
self.scheduled_next_break_timestamp = -1
else:
# Use next break, convert to seconds
time_to_wait = self.break_queue.get_break().time * 60

self.scheduled_next_break_time = current_time + datetime.timedelta(seconds=time_to_wait)
self.context['state'] = State.WAITING
utility.execute_main_thread(self.__fire_on_update_next_break, self.scheduled_next_break_time)
self.scheduled_next_break_time = current_time + datetime.timedelta(
seconds=time_to_wait
)
self.context["state"] = State.WAITING
utility.execute_main_thread(
self.__fire_on_update_next_break, self.scheduled_next_break_time
)

# Wait for the pre break warning period
logging.info("Waiting for %d minutes until next break", (time_to_wait / 60))
Expand All @@ -239,15 +254,17 @@ def __fire_pre_break(self):
"""
Show the notification and start the break after the notification.
"""
self.context['state'] = State.PRE_BREAK
self.context["state"] = State.PRE_BREAK
if not self.on_pre_break.fire(self.break_queue.get_break()):
# Plugins wanted to ignore this break
self.__start_next_break()
return
utility.start_thread(self.__wait_until_prepare)

def __wait_until_prepare(self):
logging.info("Wait for %d seconds before the break", self.pre_break_warning_time)
logging.info(
"Wait for %d seconds before the break", self.pre_break_warning_time
)
# Wait for the pre break warning period
self.__wait_for(self.pre_break_warning_time)
if not self.running:
Expand All @@ -265,12 +282,14 @@ def __fire_start_break(self):
# Plugins want to ignore this break
self.__start_next_break()
return
if self.context['postponed']:
if self.context["postponed"]:
# Plugins want to postpone this break
self.context['postponed'] = False
self.context["postponed"] = False
# Update the next break time
self.scheduled_next_break_time = self.scheduled_next_break_time + \
datetime.timedelta(seconds=self.postpone_duration)
self.scheduled_next_break_time = (
self.scheduled_next_break_time
+ datetime.timedelta(seconds=self.postpone_duration)
)
self.__fire_on_update_next_break(self.scheduled_next_break_time)
# Wait in user thread
utility.start_thread(self.__postpone_break)
Expand All @@ -282,28 +301,33 @@ def __start_break(self):
"""
Start the break screen.
"""
self.context['state'] = State.BREAK
self.context["state"] = State.BREAK
break_obj = self.break_queue.get_break()
countdown = break_obj.duration
total_break_time = countdown

while countdown and self.running and not self.context['skipped'] and not self.context['postponed']:
while (
countdown
and self.running
and not self.context["skipped"]
and not self.context["postponed"]
):
seconds = total_break_time - countdown
self.on_count_down.fire(countdown, seconds)
time.sleep(1) # Sleep for 1 second
time.sleep(1) # Sleep for 1 second
countdown -= 1
utility.execute_main_thread(self.__fire_stop_break)

def __fire_stop_break(self):
# Loop terminated because of timeout (not skipped) -> Close the break alert
if not self.context['skipped'] and not self.context['postponed']:
if not self.context["skipped"] and not self.context["postponed"]:
logging.info("Break is terminated automatically")
self.on_stop_break.fire()

# Reset the skipped flag
self.context['skipped'] = False
self.context['skip_button_disabled'] = False
self.context['postpone_button_disabled'] = False
self.context["skipped"] = False
self.context["skip_button_disabled"] = False
self.context["postpone_button_disabled"] = False
self.__start_next_break()

def __wait_for(self, duration):
Expand All @@ -315,7 +339,7 @@ def __wait_for(self, duration):
self.waiting_condition.release()

def __start_next_break(self):
if not self.context['postponed']:
if not self.context["postponed"]:
self.break_queue.next()

if self.running:
Expand Down
Loading

0 comments on commit 773d44d

Please sign in to comment.