Something went wrong. Try again.
simple timer i use for studying
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432"""Main window: timer state machine, controls and alerts."""
import mathimport os
from gi.repository import Adw, Gdk, Gio, GLib, Gtk
from .aod import AodControllerfrom .dial import SCALE_SPECS, Dial, step_secondsfrom .settings import SCALES
PRESET_MINUTES = (5, 10, 15, 25, 45, 60)TICK_MS = 33ALARM_MAX_SECONDS = 60SCROLL_SETTLE_MS = 500CHROME_HIDE_SECONDS = 3HEADER_HEIGHT = 48 # content extends under the header; keep the dial clear of itALERT_SOUND = "sounds/freedesktop/stereo/alarm-clock-elapsed.oga"FIVE_MINUTES = 300SOUND_DIR = os.path.join(os.path.dirname(__file__), "..", "data", "sounds")
def format_remaining(seconds): total = math.ceil(seconds) hours, rest = divmod(total, 3600) minutes, secs = divmod(rest, 60) if hours: return f"{hours}:{minutes:02d}:{secs:02d}" return f"{minutes:02d}:{secs:02d}"
def find_alert_sound(): for directory in GLib.get_system_data_dirs(): path = GLib.build_filenamev([directory, ALERT_SOUND]) if GLib.file_test(path, GLib.FileTest.EXISTS): return path return None
def _build_menu(): menu = Gio.Menu() set_time = Gio.Menu() for minutes in PRESET_MINUTES: set_time.append(f"{minutes} minutes", f"win.preset({minutes})") menu.append_submenu("Set Time", set_time) face = Gio.Menu() for minutes in SCALES: face.append(f"{minutes} minute face", f"win.scale::{minutes}") menu.append_submenu("Face Scale", face) menu.append("Set Task…", "win.task") footer = Gio.Menu() footer.append("Preferences", "app.preferences") footer.append("About Time Timer", "app.about") menu.append_section(None, footer) return menu
class TimerWindow(Adw.ApplicationWindow): def __init__(self, app, settings): super().__init__(application=app, title="Time Timer") self.settings = settings self._total = 0.0 # seconds chosen by the user for the current countdown self._remaining = 0.0 # seconds left while not running self._end = 0 # monotonic µs at which a running timer finishes self._running = False self._ringing_since = 0 # monotonic µs when the alarm started, 0 if silent self._halfway_sent = False self._five_sent = False self._task = "" self._tick_id = 0 self._hide_id = 0 self._settle_id = 0 self._player = None self._effects = {} # cached short sound effects by file name
self._build_ui() self._add_actions() settings.connect("changed", self._on_setting_changed) self._aod = AodController(self) self.connect("close-request", self._on_close_request) self._add_activity_tracking() self._apply_scale() self._apply_color() self._apply_readout() self._refresh()
# --- UI construction -------------------------------------------------
def _build_ui(self): self.set_default_size(420, 520) self.set_size_request(360, 360)
self._title = Adw.WindowTitle(title="", subtitle="") menu_button = Gtk.MenuButton( icon_name="open-menu-symbolic", menu_model=_build_menu(), primary=True ) menu_button.set_tooltip_text("Main Menu") header = Adw.HeaderBar(title_widget=self._title) header.pack_end(menu_button)
self.dial = Dial() self.dial.connect("seconds-chosen", lambda _d, s: self._choose(s)) self.dial.connect("adjusted", lambda _d, delta: self._adjust(delta)) self.dial.connect("released", lambda _d: self._start()) self.dial.connect("tapped", lambda _d: self._clear())
self._readout = Gtk.Label(label="00:00") self._readout.add_css_class("title-2") self._readout.add_css_class("numeric")
self._stop_button = Gtk.Button( label="Stop alarm", action_name="win.clear", halign=Gtk.Align.CENTER, visible=False ) self._stop_button.add_css_class("destructive-action") self._stop_button.add_css_class("pill")
content = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10, valign=Gtk.Align.CENTER) content.set_margin_start(12) content.set_margin_end(12) content.set_margin_top(HEADER_HEIGHT) content.set_margin_bottom(16) content.append(self.dial) content.append(self._readout) content.append(self._stop_button)
self._view = Adw.ToolbarView( content=content, top_bar_style=Adw.ToolbarStyle.FLAT, extend_content_to_top_edge=True ) self._view.add_top_bar(header) self.set_content(self._view)
motion = Gtk.EventControllerMotion() motion.connect("motion", lambda *_: self._show_chrome()) self.add_controller(motion)
def _add_actions(self): clear = Gio.SimpleAction.new("clear", None) clear.connect("activate", lambda *_: self._clear()) self.add_action(clear)
adjust = Gio.SimpleAction.new("adjust", GLib.VariantType.new("i")) adjust.connect("activate", lambda _a, p: self._adjust_key(p.get_int32())) self.add_action(adjust)
preset = Gio.SimpleAction.new("preset", GLib.VariantType.new("i")) preset.connect("activate", lambda _a, p: self._apply_preset(p.get_int32())) self.add_action(preset)
self._scale_action = Gio.SimpleAction.new_stateful( "scale", GLib.VariantType.new("s"), GLib.Variant.new_string(str(self.settings.get("scale"))), ) self._scale_action.connect( "activate", lambda _a, p: self.settings.set("scale", int(p.get_string())) ) self.add_action(self._scale_action)
task = Gio.SimpleAction.new("task", None) task.connect("activate", lambda *_: self._edit_task()) self.add_action(task)
def _on_close_request(self, _window): self._aod.shutdown() return False
def _add_activity_tracking(self): """Feed input in this window to the idle monitor (used when the desktop has none).""" motion = Gtk.EventControllerMotion(propagation_phase=Gtk.PropagationPhase.CAPTURE) motion.connect("motion", self._on_activity) keys = Gtk.EventControllerKey(propagation_phase=Gtk.PropagationPhase.CAPTURE) keys.connect("key-pressed", self._on_activity) for controller in (motion, keys): self.add_controller(controller)
def _on_activity(self, *_): self._aod.note_activity() return False
@property def aod_eligible(self): """Overlays are allowed only while a countdown runs.""" return self._running and self.settings.get("aod")
# --- Timer model -----------------------------------------------------
@property def _span(self): return SCALE_SPECS[self.settings.get("scale")].span
def _remaining_now(self): if self._running: return max((self._end - GLib.get_monotonic_time()) / 1e6, 0.0) return self._remaining
def _apply_preset(self, minutes): if minutes * 60 > self._span: self.settings.set("scale", min(s for s in SCALES if s >= minutes)) self._set_seconds(minutes * 60) self._start()
def _set_seconds(self, seconds): """Show a new duration without running it; call _start() to begin.""" seconds = min(max(seconds, 0), self._span) self._silence_alarm() self._cancel_settle() self._running = False self._total = self._remaining = float(seconds) self._halfway_sent = self._five_sent = False self._aod.evaluate() self._refresh()
def _choose(self, seconds): self._set_seconds(seconds) self.dial.show_value(seconds)
def _shift_held(self): keyboard = self.get_display().get_default_seat().get_keyboard() return bool(keyboard.get_modifier_state() & Gdk.ModifierType.SHIFT_MASK)
def _adjust_key(self, direction): """+/- keys: one numbered step, or one fine step while Shift is held.""" step = step_seconds(self.settings.get("scale"), self._shift_held()) self._adjust(direction * step)
def _adjust(self, delta): """Move to the next multiple of |delta| (scroll, +/-); the countdown restarts once input settles.""" step = abs(delta) units = self._remaining_now() / step steps = math.floor(units + 1e-6) + 1 if delta > 0 else math.ceil(units - 1e-6) - 1 self._set_seconds(max(steps, 0) * step) self.dial.show_value(int(self._total)) self._settle_id = GLib.timeout_add(SCROLL_SETTLE_MS, self._on_settled)
def _on_settled(self): self._settle_id = 0 self._start() return False
def _cancel_settle(self): if self._settle_id: GLib.source_remove(self._settle_id) self._settle_id = 0
def _start(self): self._cancel_settle() if self._remaining <= 0: return self._end = GLib.get_monotonic_time() + int(self._remaining * 1e6) self._running = True self.dial.start_pulse() if self.settings.get("sound"): self._play_effect("start.wav") self._start_ticking() self._show_chrome() self._refresh()
def _clear(self): """Drop the timer: wedge to 0, countdown and alarm stopped, with feedback.""" if self._total <= 0 and not self._ringing_since: return self._set_seconds(0) self.dial.show_cleared() self.dial.start_bump() if self.settings.get("sound"): self._play_effect("clear.wav")
# --- Ticking ---------------------------------------------------------
def _start_ticking(self): if not self._tick_id: self._tick_id = GLib.timeout_add(TICK_MS, self._on_tick)
def _on_tick(self): now = GLib.get_monotonic_time() if self._running: remaining = self._remaining_now() if remaining <= 0: self._finish(now) else: self._check_warnings(remaining) ringing = bool(self._ringing_since) if ringing and now - self._ringing_since > ALARM_MAX_SECONDS * 1e6: self._silence_alarm() ringing = False if ringing: self.dial.update(flash=0.5 + 0.5 * math.sin(now / 1e6 * math.tau * 1.5)) elif self.dial.state.flash: self.dial.update(flash=0.0) self._refresh() if self._running or ringing: return True self._tick_id = 0 return False
def _finish(self, now): self._running = False self._remaining = 0.0 self._ringing_since = now self._aod.evaluate() self.present() self._show_chrome() body = self._task or "Your timer has finished." self._notify("timer-done", "Time's up", body, Gio.NotificationPriority.HIGH) if self.settings.get("sound"): self._play_alert()
def _silence_alarm(self): if not self._ringing_since: return self._ringing_since = 0 if self._player: self._player.pause() self._player = None self.get_application().withdraw_notification("timer-done") self.dial.update(flash=0.0)
def _check_warnings(self, remaining): if ( self.settings.get("halfway_warning") and not self._halfway_sent and self._total >= 120 and remaining <= self._total / 2 ): self._halfway_sent = True self._notify("timer-halfway", "Halfway there", self._remaining_text(remaining)) if ( self.settings.get("five_minute_warning") and not self._five_sent and self._total > FIVE_MINUTES and remaining <= FIVE_MINUTES ): self._five_sent = True self._notify("timer-five", "5 minutes left", self._remaining_text(remaining))
def _remaining_text(self, remaining): left = f"About {math.ceil(remaining / 60)} min left" return f"{self._task}: {left}" if self._task else left
def _notify(self, ident, title, body, priority=Gio.NotificationPriority.LOW): notification = Gio.Notification.new(title) notification.set_body(body) notification.set_priority(priority) self.get_application().send_notification(ident, notification)
def _play_effect(self, name): media = self._effects.get(name) if media is None: media = self._effects[name] = Gtk.MediaFile.new_for_filename( os.path.join(SOUND_DIR, name) ) media.seek(0) media.play()
def _play_alert(self): path = find_alert_sound() if path: self._player = Gtk.MediaFile.new_for_filename(path) self._player.set_loop(True) self._player.play() else: Gdk.Display.get_default().beep()
# --- Task label ------------------------------------------------------
def _edit_task(self): entry = Gtk.Entry( text=self._task, placeholder_text="What am I doing?", max_length=60, activates_default=True, ) dialog = Adw.AlertDialog(heading="Task", body="Shown on the dial so you remember what this time is for.") dialog.set_extra_child(entry) dialog.add_response("cancel", "Cancel") dialog.add_response("set", "Set") dialog.set_response_appearance("set", Adw.ResponseAppearance.SUGGESTED) dialog.set_default_response("set") dialog.connect( "response", lambda _d, response: response == "set" and self._set_task(entry.get_text().strip()), ) dialog.present(self) entry.grab_focus()
def _set_task(self, text): self._task = text self._title.set_title(text) self.dial.update(label=text)
# --- View updates ----------------------------------------------------
def _refresh(self): remaining = self._remaining_now() self.dial.update(fraction=remaining / self._span) self._readout.set_label(format_remaining(remaining)) self._stop_button.set_visible(bool(self._ringing_since))
def _show_chrome(self): """Reveal the header; while a countdown runs it fades away again.""" if self._hide_id: GLib.source_remove(self._hide_id) self._hide_id = 0 self._view.set_reveal_top_bars(True) if self._running: self._hide_id = GLib.timeout_add_seconds(CHROME_HIDE_SECONDS, self._hide_chrome)
def _hide_chrome(self): self._hide_id = 0 self._view.set_reveal_top_bars(False) return False
def _apply_scale(self): scale = self.settings.get("scale") self._scale_action.set_state(GLib.Variant.new_string(str(scale))) self.dial.update(scale=scale) if self._total > self._span or self._remaining_now() > self._span: self._set_seconds(self._span)
def _apply_color(self): self.dial.update(color=self.settings.get("color"))
def _apply_readout(self): self._readout.set_visible(self.settings.get("show_readout"))
def _on_setting_changed(self, _settings, key): if key == "scale": self._apply_scale() elif key == "color": self._apply_color() elif key == "show_readout": self._apply_readout()