diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f686aa2..377849f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -24,7 +24,8 @@ jobs: - name: Build run: | uv sync --locked --group build - uv run --locked pyinstaller --onefile --windowed --name getthefish-gui src/getthefish/gui/main_window.py + uv run --locked python -m getthefish.gui.icon build/getthefish.ico + uv run --locked pyinstaller --onefile --windowed --name getthefish-gui --icon build/getthefish.ico src/getthefish/gui/main_window.py - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: exe diff --git a/README.md b/README.md index 72b997d..aa5be5a 100644 --- a/README.md +++ b/README.md @@ -3,8 +3,9 @@ [![CI](../../actions/workflows/ci.yml/badge.svg)](../../actions/workflows/ci.yml) An automated fishing tool. It casts the line, finds the bobber by its colour, -watches it for a bite and reels the fish in. A small PySide6 GUI lets you pick -the bobber colour and the search area directly on screen. +watches it for a bite and reels the fish in. A PySide6 GUI lets you pick the +bobber colour and the search area directly on screen, shows each round live and +keeps statistics. A compact view fits beside the game in windowed mode. > **Note:** The tool moves the mouse and reads the screen. Only use it where > automation is allowed by the game's terms of service. @@ -53,12 +54,32 @@ getthefish --help # options: --config PATH, --verbose In the GUI: - **Set Area** – drag a rectangle over the water where the bobber lands. Esc or right-click cancels. -- **Select Color** – click on the bobber in the frozen screenshot. Esc cancels. +- **Pick Color** – click on the bobber in the frozen screenshot; a magnifier next to the cursor + shows the exact pixel and its value. Esc cancels. - **Cast Key** – the key the *Fishing* spell is on in your action bar (default `0`). Names follow pyautogui: `0`–`9`, `a`–`z`, `f1`–`f12`, `num0`–`num9`, … - **Threshold Bobber / Threshold Catch** – per-channel RGB tolerance for finding the bobber and for detecting a bite. - **Jump to Bobber** – keep the cursor on the bobber while waiting; otherwise it returns to where it was after reeling in. - **Start / Stop** – run the fishing loop in the background. +- **Status LED** – next to the title: Casting, Searching bobber, Waiting for bite, Bite! Reeling + in, then the result of the round (Caught, Missed, No bobber). +- **Last rounds** – the last 30 rounds as dots: green caught, orange missed, red no bobber. + Many orange dots usually mean *Threshold Catch* is too high, many red ones that the colour, + *Threshold Bobber* or the area does not fit. +- **Bite Meter** – live graph of how much the watched pixel changes. The dashed line is + *Threshold Catch*; click or drag in the graph to move it. Thresholds stay editable while + fishing so you can tune them live. +- **Statistics** – casts, catches, misses, catch rate, fish per hour and fishing time for the + *Session* (since the program started, over all Start/Stop runs), *Today* and *Total*. + Daily numbers are kept in `stats.json` next to `config.json`. +- **Log** – the latest messages; enable *Verbose Log* for every search and bite detail. +- **Compact / Expand** – a small view with Start/Stop, stats and the bite meter, meant to sit + beside the game in windowed mode. Start switches to it automatically and the previous view + returns when the session ends. Each view remembers its own window position. +- **Dark / Light** – switches the colour theme (the first start follows the system setting). + +Keep this window out of the fishing area: the cast clicks into the area to focus the game, so +a window covering it swallows the click. Start refuses to run while the window overlaps it. To stop the headless version press **Ctrl+C**. In both modes moving the mouse into a screen corner triggers the emergency stop. @@ -73,6 +94,10 @@ Settings are saved automatically to a per-user file: | macOS | `~/Library/Application Support/getthefish/config.json` | | Linux | `$XDG_CONFIG_HOME/getthefish/config.json` (default `~/.config/...`) | +The same folder holds `getthefish.log`, the daily statistics (`stats.json`) and +the window preferences (`window.ini`: theme, view, window positions). The +*Open Config/Logs Folder* button opens it. + Set `GETTHEFISH_CONFIG` or pass `--config` to use another file. A `config.json` from older versions in the current directory is imported automatically on first start. See [`config.example.json`](config.example.json). @@ -104,7 +129,7 @@ by the right-click. ## Troubleshooting -Enable **verbose** in the GUI (or run `getthefish -v`) and check the log file +Enable **Verbose Log** in the GUI (or run `getthefish -v`) and check the log file `getthefish.log` in the same folder as `config.json`. Each cast logs, for example: ``` @@ -113,6 +138,10 @@ Watching pixel 643, 217 with colour (74, 40, 13) No bite within 20s: largest colour change was 41, threshold_catch is 60 ``` +- **Nothing is cast, then "Bobber not found" three times** – something covers + the top-left corner of the area, where the cast clicks to focus the game + (often this window). Move it beside the game; Start checks this for its own + window. - **Set the area over water only.** Dark wood (boat), the character and UI bars contain the same dark red/brown as the bobber; if they are inside the area the bot locks onto them and never sees a bite. @@ -137,8 +166,12 @@ src/getthefish/ ├── detection.py # pure numpy colour detection ├── devices.py # screen capture (mss) and mouse (pyautogui) adapters ├── logs.py # console + log file setup +├── tally.py # statistics and the per-day history (stats.json) └── gui/ - ├── main_window.py # PySide6 GUI + ├── main_window.py # main window, colour picker and area selector + ├── widgets.py # status LED, bite meter, round history, log bridge + ├── theme.py # light and dark theme + ├── icon.py # application icon (also writes the .ico for the exe) ├── main.ui # Qt Designer source └── ui_main.py # generated from main.ui tests/ # pytest suite (no real screen or mouse needed) @@ -161,6 +194,12 @@ CI runs them on Windows for every push and pull request. Pushing a tag like `uv.lock` is the committed, cross-platform dependency lockfile. +After editing `main.ui` in Qt Designer, regenerate the Python code: + +```bash +uv run pyside6-uic src/getthefish/gui/main.ui -o src/getthefish/gui/ui_main.py +``` + ## License MIT – see [LICENSE](LICENSE). diff --git a/src/getthefish/bot.py b/src/getthefish/bot.py index 16fce12..edf5c24 100644 --- a/src/getthefish/bot.py +++ b/src/getthefish/bot.py @@ -7,7 +7,8 @@ import threading import time from collections.abc import Callable -from dataclasses import dataclass +from dataclasses import dataclass, replace +from enum import StrEnum from getthefish.config import FishConfig, Point from getthefish.detection import find_color @@ -44,6 +45,47 @@ class Stats: misses: int = 0 +class Phase(StrEnum): + """The step of a round the fishing loop is in.""" + + CASTING = "casting" + SEARCHING = "searching" + WAITING = "waiting" + REELING = "reeling" + + +@dataclass(frozen=True) +class PhaseChanged: + phase: Phase + + +@dataclass(frozen=True) +class BobberFound: + """The bobber landed at ``position``; ``watch`` is the pixel observed for a bite.""" + + position: Point + watch: Point + + +@dataclass(frozen=True) +class BiteSample: + """Largest per-channel change of the watched pixel since the bobber landed.""" + + change: int + + +@dataclass(frozen=True) +class RoundFinished: + """One round is over: True (caught), False (missed) or None (no bobber / error).""" + + result: bool | None + stats: Stats + + +Event = PhaseChanged | BobberFound | BiteSample | RoundFinished +"""Live data for a UI; sent from the fishing thread.""" + + class GetTheFish: """Runs the fishing loop until :meth:`stop` is called or it gives up. @@ -58,6 +100,7 @@ def __init__( timing: Timing | None = None, on_status: Callable[[str], None] | None = None, rng: random.Random | None = None, + on_event: Callable[[Event], None] | None = None, ) -> None: self.config = config self.screen = screen @@ -65,6 +108,7 @@ def __init__( self.timing = timing or Timing() self.stats = Stats() self._on_status = on_status + self.on_event = on_event self._rng = rng or random.Random() # noqa: S311 - timing jitter, not crypto self._stop = threading.Event() @@ -83,6 +127,10 @@ def _status(self, text: str, *, verbose_only: bool = False) -> None: if self._on_status is not None: self._on_status(text) + def _emit(self, event: Event) -> None: + if self.on_event is not None: + self.on_event(event) + def _sleep(self, delay: Range | float) -> bool: """Interruptible sleep. Returns False if stop was requested.""" seconds = self._rng.uniform(*delay) if isinstance(delay, tuple) else delay @@ -95,6 +143,7 @@ def cast(self) -> None: is the GUI right after clicking Start. Left-click on water is harmless in the game (right-click could trigger click-to-move). """ + self._emit(PhaseChanged(Phase.CASTING)) self.mouse.move_to(self.config.start_pos) self.mouse.left_click() self.mouse.press(self.config.cast_key) @@ -102,6 +151,7 @@ def cast(self) -> None: def find_bobber(self) -> Point | None: """Search the configured area; returns absolute screen coordinates.""" + self._emit(PhaseChanged(Phase.SEARCHING)) left, top, right, bottom = self.config.search_area for attempt in range(1, self.config.max_attempts + 1): self._status( @@ -135,6 +185,7 @@ def wait_for_bite(self, watch: Point) -> bool: while time.monotonic() < deadline: current = self._pixel(watch) change = max(abs(a - b) for a, b in zip(current, initial, strict=True)) + self._emit(BiteSample(change)) if change > self.config.threshold_catch: self._status( f"Bite: colour {initial} -> {current} (change {change} > " @@ -168,12 +219,17 @@ def fish_once(self) -> bool | None: if bobber is None: return None watch = Point(bobber.x + BITE_WATCH_OFFSET.x, bobber.y + BITE_WATCH_OFFSET.y) + self._emit(BobberFound(bobber, watch)) + self._emit(PhaseChanged(Phase.WAITING)) if self.config.jump_to_bobber: self.mouse.move_to(watch) if not self.wait_for_bite(watch): + if not self.is_running: + return False self.stats.misses += 1 self._status("No bite, recasting", verbose_only=True) return False + self._emit(PhaseChanged(Phase.REELING)) if not self._sleep(self.timing.before_catch): return False self.reel_in(watch) @@ -198,6 +254,7 @@ def run(self) -> None: except Exception as e: logger.exception("Unexpected error in fishing round") result, problem = None, f"Error: {e}" + self._emit(RoundFinished(result, replace(self.stats))) if result is not None: failures = 0 self._sleep(self.timing.after_round) diff --git a/src/getthefish/gui/icon.py b/src/getthefish/gui/icon.py new file mode 100644 index 0000000..99a5586 --- /dev/null +++ b/src/getthefish/gui/icon.py @@ -0,0 +1,89 @@ +"""The application icon, drawn in code so the window, the taskbar and the exe share one source. + +``python -m getthefish.gui.icon OUT.ico`` writes it as a multi-size Windows icon (used by the +release build for the exe). +""" + +from __future__ import annotations + +import struct +import sys +from pathlib import Path + +from PySide6.QtCore import QBuffer, QByteArray, QIODevice, QPointF, QRectF, Qt +from PySide6.QtGui import QColor, QGuiApplication, QIcon, QImage, QLinearGradient, QPainter, QPixmap + +SIZES = (16, 24, 32, 48, 64, 128, 256) + + +def render(size: int) -> QImage: + """The icon at ``size`` x ``size`` pixels, drawn on a 64-unit grid.""" + image = QImage(size, size, QImage.Format.Format_ARGB32_Premultiplied) + image.fill(Qt.GlobalColor.transparent) + p = QPainter(image) + p.setRenderHint(QPainter.RenderHint.Antialiasing) + p.scale(size / 64, size / 64) + + background = QLinearGradient(0, 2, 0, 62) + background.setColorAt(0, QColor("#4f8cff")) + background.setColorAt(1, QColor("#1d4ed8")) + p.setPen(Qt.PenStyle.NoPen) + p.setBrush(background) + p.drawRoundedRect(QRectF(2, 2, 60, 60), 14, 14) + + white = QColor("white") + p.setBrush(white) + p.drawEllipse(QRectF(10, 25, 34, 20)) # body + p.drawPolygon([QPointF(40, 35), QPointF(54, 25), QPointF(51, 35), QPointF(54, 45)]) # tail + p.setBrush(QColor("#1d4ed8")) + p.drawEllipse(QPointF(19, 33), 2.4, 2.4) # eye + bubble = QColor(255, 255, 255, 170) + p.setBrush(bubble) + p.drawEllipse(QPointF(15, 18), 2.6, 2.6) + p.drawEllipse(QPointF(21, 12), 1.7, 1.7) + p.end() + return image + + +def app_icon() -> QIcon: + icon = QIcon() + for size in SIZES: + icon.addPixmap(QPixmap.fromImage(render(size))) + return icon + + +def _png(image: QImage) -> bytes: + data = QByteArray() + buffer = QBuffer(data) + buffer.open(QIODevice.OpenModeFlag.WriteOnly) + image.save(buffer, "PNG") # type: ignore[call-overload] # stubs say bytes, runtime wants str + return bytes(data.data()) + + +def ico_bytes(sizes: tuple[int, ...] = SIZES) -> bytes: + """A Windows .ico with one PNG-compressed image per size.""" + images = [_png(render(size)) for size in sizes] + header = struct.pack("= 256 else size # 0 means 256 in the ICO directory + entries += struct.pack(" int: + if len(argv) != 2: + print("usage: python -m getthefish.gui.icon OUT.ico", file=sys.stderr) + return 2 + app = QGuiApplication.instance() or QGuiApplication([argv[0], "-platform", "offscreen"]) + assert app is not None + out = Path(argv[1]) + out.parent.mkdir(parents=True, exist_ok=True) + out.write_bytes(ico_bytes()) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/src/getthefish/gui/main.ui b/src/getthefish/gui/main.ui index 18c3a54..add843a 100644 --- a/src/getthefish/gui/main.ui +++ b/src/getthefish/gui/main.ui @@ -1,4 +1,4 @@ - + MainWindow @@ -6,312 +6,1025 @@ 0 0 - 319 - 274 + 1000 + 600 GetTheFish - + + + 8 + + + 12 + + + 12 + + + 12 + + + 12 + - - - - - - - Start: - - - - - - - - - - - - - - End - - - - - - - - - - - - - - Fishing Area - - - - - - - - - - - Bobber Color - - - - - - - - 0 - 0 - - - - - 20 - 20 - - - - - 20 - 20 - - - - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - - - - - - - Qt::Vertical - - - QSizePolicy::Fixed - - - - 20 - 5 - - - - + + + 8 + - + - Threshold Bobber - - - - - - - - 0 - 0 - - - - - 120 - 0 - - - - - 120 - 16777215 - + GetTheFish - - - Threshold Catch - - + - - - - 0 - 0 - + + + Qt::Orientation::Horizontal - + - 120 + 10 0 - - - 120 - 16777215 - - - + - + - Cast Key - - - - - - - - 0 - 0 - + Light - - - 60 - 0 - - - - - 60 - 16777215 - + + Switch between light and dark mode - - 20 + + true - - Key bound to the Fishing spell in the game, e.g. 0, f, f1, num0 + + Qt::FocusPolicy::NoFocus - + - Jump to Bobber + Compact - - - - - - verbose + + Switch between the full and the compact view - - - - - - Qt::Vertical + + true - - - 20 - 40 - + + Qt::FocusPolicy::NoFocus - + - - - Qt::Horizontal - - - - 350 - 0 - - - - - - - - - - Start + + + + + 12 - - - - - - Set Area + + 0 - - - - - - Select Color + + 0 - - - - - - Open Config/Logs Folder + + 0 - - - - - - Qt::Vertical + + 0 - - - 20 - 40 - + + + + 4 + + + + + Setup + + + + 320 + 0 + + + + + 320 + 16777215 + + + + + 8 + + + + + Area + + + + + + + + + + + + + + + + → + + + + + + + + + + + + + + Qt::Orientation::Horizontal + + + + 10 + 0 + + + + + + + + + + Set Area + + + Drag a rectangle over the water where the bobber lands + + + + + + + Bobber + + + + + + + + + + + + + 18 + 18 + + + + + 18 + 18 + + + + + + + + + + + + + + + Qt::Orientation::Horizontal + + + + 10 + 0 + + + + + + + + + + Pick Color + + + Click the bobber in a frozen screenshot + + + + + + + Cast Key + + + + + + + Key bound to the Fishing spell in the game, e.g. 0, f, f1, num0 + + + 20 + + + + + + + + + + Tuning + + + + 320 + 0 + + + + + 320 + 16777215 + + + + + 8 + + + + + Threshold Bobber + + + + + + + Per-channel RGB tolerance when searching for the bobber colour + + + + 0 + 0 + + + + + 120 + 0 + + + + + 120 + 16777215 + + + + + + + + Threshold Catch + + + + + + + Colour change of the watched pixel that counts as a bite (dashed line in the meter) + + + + 0 + 0 + + + + + 120 + 0 + + + + + 120 + 16777215 + + + + + + + + Jump to Bobber + + + + + + + Verbose Log + + + + + + + + + + 12 + + + + + Start + + + + + + + + + Qt::Orientation::Vertical + + + + 0 + 10 + + + + + + + + + + 4 + + + + + Statistics + + + + 10 + + + + + 6 + + + + + Casts + + + true + + + + + + + – + + + true + + + + + + + – + + + true + + + + + + + – + + + true + + + + + + + Catches + + + true + + + + + + + – + + + true + + + + + + + – + + + true + + + + + + + – + + + true + + + + + + + Misses + + + true + + + + + + + – + + + true + + + + + + + – + + + true + + + + + + + – + + + true + + + + + + + Catch rate + + + true + + + + + + + – + + + true + + + + + + + – + + + true + + + + + + + – + + + true + + + + + + + Fish / hour + + + true + + + + + + + – + + + true + + + + + + + – + + + true + + + + + + + – + + + true + + + + + + + Fishing time + + + true + + + + + + + – + + + true + + + + + + + – + + + true + + + + + + + – + + + true + + + + + + + Session + + + true + + + + + + + Today + + + true + + + + + + + Total + + + true + + + + + + + + + 8 + + + + + Last rounds + + + true + + + + + + + + 0 + 0 + + + + + + + + + + + + + Bite meter + + + + + + + 0 + 120 + + + + + + + + + + + Log + + + + + + true + + + 500 + + + + + + + + + Qt::Orientation::Horizontal + + + + 10 + 0 + + + + + + + + Open Config/Logs Folder + + + + + + + + + + + + + + + + 8 - - - + + 0 + + + 0 + + + 0 + + + 0 + + + + + Start + + + + + + + + 0 + 0 + + + + + + + + 2 + + + + + Caught + + + true + + + Qt::AlignmentFlag::AlignRight|Qt::AlignmentFlag::AlignVCenter + + + + + + + Rate + + + true + + + Qt::AlignmentFlag::AlignRight|Qt::AlignmentFlag::AlignVCenter + + + + + + + Time + + + true + + + Qt::AlignmentFlag::AlignRight|Qt::AlignmentFlag::AlignVCenter + + + + + + + Session + + + true + + + + + + + – + + + Qt::AlignmentFlag::AlignRight|Qt::AlignmentFlag::AlignVCenter + + + + + + + – + + + Qt::AlignmentFlag::AlignRight|Qt::AlignmentFlag::AlignVCenter + + + + + + + – + + + Qt::AlignmentFlag::AlignRight|Qt::AlignmentFlag::AlignVCenter + + + + + + + Today + + + true + + + + + + + – + + + Qt::AlignmentFlag::AlignRight|Qt::AlignmentFlag::AlignVCenter + + + + + + + – + + + Qt::AlignmentFlag::AlignRight|Qt::AlignmentFlag::AlignVCenter + + + + + + + – + + + Qt::AlignmentFlag::AlignRight|Qt::AlignmentFlag::AlignVCenter + + + + + + + Total + + + true + + + + + + + – + + + Qt::AlignmentFlag::AlignRight|Qt::AlignmentFlag::AlignVCenter + + + + + + + – + + + Qt::AlignmentFlag::AlignRight|Qt::AlignmentFlag::AlignVCenter + + + + + + + – + + + Qt::AlignmentFlag::AlignRight|Qt::AlignmentFlag::AlignVCenter + + + + + + + + + + 0 + 80 + + + + + + + - + - - - + + + StatusLed + QWidget +
getthefish.gui.widgets
+
+ + BiteMeter + QWidget +
getthefish.gui.widgets
+
+ + RoundHistory + QWidget +
getthefish.gui.widgets
+
+
+ + + \ No newline at end of file diff --git a/src/getthefish/gui/main_window.py b/src/getthefish/gui/main_window.py index efcfbef..8c6461c 100644 --- a/src/getthefish/gui/main_window.py +++ b/src/getthefish/gui/main_window.py @@ -1,18 +1,61 @@ -"""Main window: edit settings, pick colour and area, start/stop fishing.""" +"""Main window: edit settings, pick colour and area, start/stop fishing. + +A compact view shows only what matters during a session, so the window fits beside +the game. +""" from __future__ import annotations import logging import sys +import time from collections.abc import Callable from dataclasses import replace from pathlib import Path -from PySide6.QtCore import QObject, QPoint, QRect, QSize, Qt, QThread, QUrl, Signal -from PySide6.QtGui import QCloseEvent, QColor, QDesktopServices, QKeyEvent, QMouseEvent, QPixmap -from PySide6.QtWidgets import QApplication, QLabel, QMainWindow, QMessageBox, QRubberBand, QWidget +from PySide6.QtCore import ( + QByteArray, + QObject, + QPoint, + QRect, + QSettings, + QSize, + Qt, + QThread, + QTimer, + QUrl, + Signal, +) +from PySide6.QtGui import ( + QCloseEvent, + QColor, + QDesktopServices, + QKeyEvent, + QMouseEvent, + QPainter, + QPaintEvent, + QPen, + QPixmap, +) +from PySide6.QtWidgets import ( + QApplication, + QLabel, + QMainWindow, + QMessageBox, + QRubberBand, + QSizePolicy, + QWidget, +) -from getthefish.bot import GetTheFish +from getthefish.bot import ( + BiteSample, + BobberFound, + Event, + GetTheFish, + PhaseChanged, + RoundFinished, + Stats, +) from getthefish.config import ( ConfigError, FishConfig, @@ -22,13 +65,51 @@ normalize_key, ) from getthefish.devices import MssScreen, PyAutoGuiInput, is_known_key +from getthefish.gui import theme +from getthefish.gui.icon import app_icon from getthefish.gui.ui_main import Ui_MainWindow +from getthefish.gui.widgets import QtLogHandler from getthefish.logs import setup_logging +from getthefish.tally import STATS_FILENAME, DailyHistory, Tally logger = logging.getLogger(__name__) BotFactory = Callable[[FishConfig, Callable[[str], None]], GetTheFish] +UI_SETTINGS_FILENAME = "window.ini" +FULL_SIZE = QSize(1000, 600) +COMPACT_SIZE = QSize(320, 230) +NO_VALUE = "\N{EN DASH}" + +STATES = { + "idle": ("Idle", ""), + "stopping": ("Stopping", "warn"), + "casting": ("Casting", "accent"), + "searching": ("Searching bobber", "accent"), + "waiting": ("Waiting for bite", "accent"), + "reeling": ("Bite! Reeling in", "success"), + "caught": ("Caught", "success"), + "missed": ("Missed", "warn"), + "no_bobber": ("No bobber", "danger"), +} +"""Status LED: state -> (text, colour tone). Phases come from the fishing loop's events.""" + + +def _format_tally(tally: Tally, seconds: float) -> tuple[str, str, str, str, str, str]: + """Casts, catches, misses, catch rate, fish per hour and fishing time as display text.""" + rate = tally.catch_rate + per_hour = tally.per_hour(seconds) + minutes, secs = divmod(int(seconds), 60) + hours, minutes = divmod(minutes, 60) + return ( + str(tally.casts), + str(tally.catches), + str(tally.misses), + NO_VALUE if rate is None else f"{rate:.0f}%", + NO_VALUE if per_hour is None else f"{per_hour:.0f}", + f"{hours}:{minutes:02}:{secs:02}", + ) + def default_bot_factory(config: FishConfig, on_status: Callable[[str], None]) -> GetTheFish: return GetTheFish(config, MssScreen(), PyAutoGuiInput(), on_status=on_status) @@ -38,10 +119,12 @@ class FishingWorker(QThread): """Runs one :class:`GetTheFish` instance in a background thread.""" status = Signal(str) + live = Signal(object) def __init__(self, factory: BotFactory, config: FishConfig, parent: QObject | None = None): super().__init__(parent) self.bot = factory(config, self.status.emit) + self.bot.on_event = self.live.emit def run(self) -> None: try: @@ -86,15 +169,60 @@ def keyPressEvent(self, event: QKeyEvent | None) -> None: # noqa: N802 class ColorPicker(ScreenOverlay): - """Click a pixel to choose the bobber colour. Esc cancels.""" + """Click a pixel to choose the bobber colour. Esc cancels. + + A magnifier next to the cursor shows the surrounding pixels and the colour under it. + """ color_picked = Signal(tuple) + LOUPE_RADIUS = 7 + """Pixels shown on each side of the centre pixel.""" + LOUPE_ZOOM = 10 + + def __init__(self, pixmap: QPixmap | None = None) -> None: + super().__init__(pixmap) + self.setMouseTracking(True) + self.cursor_pos: QPoint | None = None + + def mouseMoveEvent(self, event: QMouseEvent | None) -> None: # noqa: N802 + if event is not None: + self.cursor_pos = event.position().toPoint() + self.update() + def mousePressEvent(self, event: QMouseEvent | None) -> None: # noqa: N802 if event is not None and event.button() == Qt.MouseButton.LeftButton: self.color_picked.emit(self.color_at(event.position().toPoint())) self.close() + def paintEvent(self, event: QPaintEvent) -> None: # noqa: N802 + super().paintEvent(event) + if self.cursor_pos is None: + return + cursor, r, zoom = self.cursor_pos, self.LOUPE_RADIUS, self.LOUPE_ZOOM + size = (2 * r + 1) * zoom + center = self.to_physical(cursor) + patch = self._image.copy(QRect(center.x - r, center.y - r, 2 * r + 1, 2 * r + 1)) + # Keep the loupe on screen: flip it to the other side of the cursor near an edge. + x = cursor.x() + 24 if cursor.x() + 24 + size <= self.width() else cursor.x() - 24 - size + y = cursor.y() + 24 if cursor.y() + 54 + size <= self.height() else cursor.y() - 54 - size + p = QPainter(self) + p.drawImage(QRect(x, y, size, size), patch) + p.setPen(QPen(QColor(theme.colors().accent), 2)) + p.drawRect(x, y, size, size) + p.setPen(QPen(QColor("white"), 1)) + p.drawRect(x + r * zoom, y + r * zoom, zoom, zoom) + red, green, blue = self.color_at(cursor) + color = QColor(red, green, blue) + p.fillRect(x, y + size + 2, size + 1, 26, QColor(theme.colors().panel)) + p.fillRect(x + 4, y + size + 6, 18, 18, color) + p.setPen(QColor(theme.colors().text)) + p.drawText( + QRect(x + 28, y + size + 2, size - 28, 26), + Qt.AlignmentFlag.AlignVCenter, + f"{color.name()} {red} {green} {blue}", + ) + class AreaSelector(ScreenOverlay): """Drag with the left button to choose the search area. Esc cancels.""" @@ -149,12 +277,42 @@ def __init__( self.bot_factory = bot_factory self.worker: FishingWorker | None = None self.overlay: ScreenOverlay | None = None + self.total = Tally() + """Statistics since the program started, over all fishing runs.""" + self.history = DailyHistory(config_path.parent / STATS_FILENAME) + self.run_stats = Stats() + """Running counts of the current fishing run, as last reported by it.""" + self.tick: float | None = None + """When fishing time was last booked; None while not fishing.""" + self.compact_before_session = False + self.stopping = False + self.dark = False + self.compact = False + # Window preferences (theme, view, positions) live next to config.json. + self.settings = QSettings( + str(config_path.parent / UI_SETTINGS_FILENAME), QSettings.Format.IniFormat + ) + self.meters = (self.ui.biteMeter, self.ui.compactMeter) + self.round_histories = (self.ui.roundHistory, self.ui.compactRoundHistory) + self.start_buttons = (self.ui.startButton, self.ui.compactStartButton) for spin in (self.ui.thresholdBobberSpinBox, self.ui.thresholdCatchSpinBox): spin.setRange(0, 255) self.refresh() + self.show_stats() + + self.log_handler = QtLogHandler() + self.log_handler.message.connect(self.ui.logView.appendPlainText) + logging.getLogger("getthefish").addHandler(self.log_handler) - self.ui.startButton.clicked.connect(self.toggle_fishing) + self.clock_timer = QTimer(self) + self.clock_timer.setInterval(1000) + self.clock_timer.timeout.connect(self.show_stats) + + for button in self.start_buttons: + button.clicked.connect(self.toggle_fishing) + for meter in self.meters: + meter.threshold_dragged.connect(self.ui.thresholdCatchSpinBox.setValue) self.ui.areaButton.clicked.connect(self.select_area) self.ui.colorButton.clicked.connect(self.pick_color) self.ui.openConfigFolderButton.clicked.connect(self.open_config_folder) @@ -163,6 +321,13 @@ def __init__( self.ui.jumpToBobberCheck.stateChanged.connect(self.settings_changed) self.ui.verboseCheck.stateChanged.connect(self.settings_changed) self.ui.castKeyEdit.editingFinished.connect(self.cast_key_changed) + self.ui.themeButton.clicked.connect(lambda: self.set_dark(not self.dark)) + self.ui.viewButton.clicked.connect(lambda: self.set_compact(not self.compact)) + + self.dark = bool(self.settings.value("dark", theme.system_prefers_dark(), type=bool)) + self.set_dark(self.dark) + self.compact = bool(self.settings.value("compact", False, type=bool)) + self._show_view() @property def is_fishing(self) -> bool: @@ -191,6 +356,8 @@ def refresh(self) -> None: hex_color = QColor(*c.bobber_color).name(QColor.NameFormat.HexRgb) self.ui.hexColorLabel.setText(hex_color) self.ui.bobberColorLabel.setStyleSheet(f"QLabel {{ background-color: {hex_color}; }}") + for meter in self.meters: + meter.set_threshold(c.threshold_catch) def save(self) -> None: try: @@ -204,6 +371,8 @@ def settings_changed(self) -> None: self.config.threshold_catch = self.ui.thresholdCatchSpinBox.value() self.config.jump_to_bobber = self.ui.jumpToBobberCheck.isChecked() self.config.verbose = self.ui.verboseCheck.isChecked() + for meter in self.meters: + meter.set_threshold(self.config.threshold_catch) self.save() def cast_key_changed(self) -> None: @@ -237,6 +406,137 @@ def set_area(self, start: Point, end: Point) -> None: def show_status(self, text: str) -> None: self.ui.statusbar.showMessage(text) + def set_dark(self, dark: bool) -> None: + self.dark = dark + self.settings.setValue("dark", dark) + app = QApplication.instance() + assert isinstance(app, QApplication) + theme.apply(app, dark=dark) + self.ui.themeButton.setText("Light" if dark else "Dark") + self.update() + + def set_compact(self, compact: bool) -> None: + """Switch between the full and the compact view; each keeps its own window geometry.""" + if compact == self.compact: + return + self.settings.setValue(self._geometry_key(), self.saveGeometry()) + self.compact = compact + self.settings.setValue("compact", compact) + self._show_view() + + def _geometry_key(self) -> str: + return "compact_geometry" if self.compact else "full_geometry" + + def _show_view(self) -> None: + current = self.ui.compactPage if self.compact else self.ui.fullPage + # Ignore the hidden page's size, otherwise the compact window could not shrink. + for page in (self.ui.fullPage, self.ui.compactPage): + policy = QSizePolicy.Policy.Preferred if page is current else QSizePolicy.Policy.Ignored + page.setSizePolicy(policy, policy) + self.ui.pages.setCurrentWidget(current) + self.ui.viewButton.setText("Expand" if self.compact else "Compact") + self.ui.titleLabel.setVisible(not self.compact) # room for the status LED + geometry = self.settings.value(self._geometry_key()) + if not (isinstance(geometry, QByteArray) and self.restoreGeometry(geometry)): + self.resize(COMPACT_SIZE if self.compact else FULL_SIZE) + + def show_state(self, state: str) -> None: + """Update the status LED and the start buttons (``state`` is a key of STATES).""" + text, tone = STATES[state] + # The steps of a round breathe; results and idle hold still. + self.ui.statusLed.set_state(text, tone, pulse=tone == "accent") + for button in self.start_buttons: + button.setProperty("fishing", self.is_fishing) + button.style().unpolish(button) + button.style().polish(button) + + def set_start_button(self, text: str, *, enabled: bool = True) -> None: + for button in self.start_buttons: + button.setText(text) + button.setEnabled(enabled) + + def record(self, run_stats: Stats | None = None) -> None: + """Add what happened since the last call to the totals and to today's history. + + ``run_stats`` are the running counts of the current fishing run. + """ + now = time.monotonic() + delta = Tally(seconds=0.0 if self.tick is None else now - self.tick) + self.tick = None if self.tick is None else now + if run_stats is not None: + delta.casts = run_stats.casts - self.run_stats.casts + delta.catches = run_stats.catches - self.run_stats.catches + delta.misses = run_stats.misses - self.run_stats.misses + self.run_stats = run_stats + self.total.add(delta) + self.history.today().add(delta) + self.history.save() + self.show_stats() + + def show_stats(self) -> None: + running = 0.0 if self.tick is None else time.monotonic() - self.tick + u = self.ui + # Per row: the tally, its six full-view labels and its three compact-view labels. + rows = ( + (self.total, + (u.castsValue, u.catchesValue, u.missesValue, u.rateValue, u.perHourValue, + u.elapsedValue), + (u.compactSessionCatches, u.compactSessionRate, u.compactSessionTime)), + (self.history.today(), + (u.todayCastsValue, u.todayCatchesValue, u.todayMissesValue, u.todayRateValue, + u.todayPerHourValue, u.todayElapsedValue), + (u.compactTodayCatches, u.compactTodayRate, u.compactTodayTime)), + (self.history.total(), + (u.totalCastsValue, u.totalCatchesValue, u.totalMissesValue, u.totalRateValue, + u.totalPerHourValue, u.totalElapsedValue), + (u.compactTotalCatches, u.compactTotalRate, u.compactTotalTime)), + ) # fmt: skip + for tally, full, compact in rows: + texts = _format_tally(tally, tally.seconds + running) + for label, text in zip(full, texts, strict=True): + label.setText(text) + for label, text in zip(compact, (texts[1], texts[3], texts[5]), strict=True): + label.setText(text) + + def handle_event(self, event: Event) -> None: + """Live data from the fishing thread.""" + for meter in self.meters: + match event: + case BobberFound(): + meter.reset() + case BiteSample(change=change): + meter.add_sample(change) + match event: + case PhaseChanged(phase=phase) if not self.stopping: + self.show_state(phase.value) + case RoundFinished(result=result, stats=stats): + if stats.catches > self.run_stats.catches: + outcome: str | None = "caught" + elif stats.misses > self.run_stats.misses: + outcome = "missed" + else: # a round interrupted by Stop has no outcome + outcome = "no_bobber" if result is None else None + if outcome is not None: + for history in self.round_histories: + history.add(outcome) + if not self.stopping: + self.show_state(outcome) + self.record(stats) + + def covers_search_area(self) -> bool: + """True if this window hides part of the water or the click that focuses the game.""" + if not self.isVisible(): + return False + ratio = self.devicePixelRatioF() + g = self.frameGeometry() + left, top, right, bottom = self.config.search_area + return ( + g.left() * ratio < right + and (g.right() + 1) * ratio > left + and g.top() * ratio < bottom + and (g.bottom() + 1) * ratio > top + ) + def open_config_folder(self) -> None: """Open the directory containing config.json and the log file.""" folder_url = QUrl.fromLocalFile(str(self.config_path.parent.resolve())) @@ -247,33 +547,52 @@ def toggle_fishing(self) -> None: if self.is_fishing: assert self.worker is not None self.worker.stop() - self.ui.startButton.setEnabled(False) - self.ui.startButton.setText("Stopping...") + self.set_start_button("Stopping...", enabled=False) + self.stopping = True + self.show_state("stopping") + return + self.compact_before_session = self.compact + self.set_compact(True) + if self.covers_search_area(): + # The cast click would focus this window instead of the game and nothing happens. + self.show_status("Move this window beside the game: it covers the fishing area") return try: self.worker = FishingWorker(self.bot_factory, self.config, self) except Exception as e: QMessageBox.critical(self, "Cannot start", str(e)) + self.set_compact(self.compact_before_session) return self.worker.status.connect(self.show_status) + self.worker.live.connect(self.handle_event) self.worker.finished.connect(self.fishing_finished) self.set_editing_enabled(False) - self.ui.startButton.setText("Stop") + self.set_start_button("Stop") + self.run_stats = Stats() + self.tick = time.monotonic() + for meter in self.meters: + meter.reset() + self.clock_timer.start() self.worker.start() + self.show_state("casting") def fishing_finished(self) -> None: self.set_editing_enabled(True) - self.ui.startButton.setEnabled(True) - self.ui.startButton.setText("Start") + self.set_start_button("Start") + self.stopping = False + self.show_state("idle") + self.clock_timer.stop() + self.record() # books the fishing time since the last round + self.tick = None + self.show_stats() + self.set_compact(self.compact_before_session) def set_editing_enabled(self, enabled: bool) -> None: + """Lock what a running session depends on; thresholds stay editable for live tuning.""" for w in ( self.ui.areaButton, self.ui.colorButton, - self.ui.thresholdBobberSpinBox, - self.ui.thresholdCatchSpinBox, self.ui.jumpToBobberCheck, - self.ui.verboseCheck, self.ui.castKeyEdit, ): w.setEnabled(enabled) @@ -293,6 +612,10 @@ def _show_overlay(self, overlay: ScreenOverlay) -> None: overlay.showFullScreen() def closeEvent(self, event: QCloseEvent) -> None: # noqa: N802 + self.clock_timer.stop() + self.settings.setValue(self._geometry_key(), self.saveGeometry()) + self.settings.sync() + logging.getLogger("getthefish").removeHandler(self.log_handler) if self.worker is not None: self.worker.stop() self.worker.wait(5000) @@ -300,7 +623,13 @@ def closeEvent(self, event: QCloseEvent) -> None: # noqa: N802 def main() -> int: + if sys.platform == "win32": + import ctypes + + # Own taskbar entry and icon instead of grouping under python.exe. + ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("Baumfaust.GetTheFish") app = QApplication(sys.argv) + app.setWindowIcon(app_icon()) config_path = default_config_path() if log_file := setup_logging(config_path.parent): logging.info("Logging to %s", log_file) diff --git a/src/getthefish/gui/theme.py b/src/getthefish/gui/theme.py new file mode 100644 index 0000000..9a865d5 --- /dev/null +++ b/src/getthefish/gui/theme.py @@ -0,0 +1,144 @@ +"""Light and dark themes. Kept in Python (not a .qss file) so PyInstaller bundles them.""" + +from __future__ import annotations + +from dataclasses import dataclass + +from PySide6.QtCore import Qt +from PySide6.QtGui import QColor, QPalette +from PySide6.QtWidgets import QApplication + + +@dataclass(frozen=True) +class Colors: + background: str + panel: str + sunken: str + border: str + grid: str + text: str + muted: str + accent: str + on_accent: str + warn: str + danger: str + success: str + + +DARK = Colors( + background="#16171a", + panel="#1e2024", + sunken="#121316", + border="#2d3036", + grid="#26292e", + text="#e4e6e9", + muted="#8a9099", + accent="#4f8cff", + on_accent="#ffffff", + warn="#f2a33a", + danger="#e5484d", + success="#3dd68c", +) + +LIGHT = Colors( + background="#f4f5f7", + panel="#ffffff", + sunken="#eef0f3", + border="#dcdfe4", + grid="#e6e8ec", + text="#1c1f24", + muted="#6b7280", + accent="#2563eb", + on_accent="#ffffff", + warn="#c2780a", + danger="#d93036", + success="#1a9e5c", +) + +_current = DARK + + +def colors() -> Colors: + """The colours of the active theme (for custom-painted widgets).""" + return _current + + +def system_prefers_dark() -> bool: + return QApplication.styleHints().colorScheme() == Qt.ColorScheme.Dark + + +def stylesheet(c: Colors) -> str: + return f""" +QMainWindow {{ background: {c.background}; }} +QWidget {{ color: {c.text}; font-family: "Segoe UI", sans-serif; font-size: 9pt; }} +QToolTip {{ background: {c.panel}; color: {c.text}; border: 1px solid {c.border}; padding: 4px; }} + +QGroupBox {{ + background: {c.panel}; border: 1px solid {c.border}; border-radius: 8px; + margin-top: 20px; padding: 8px; +}} +QGroupBox::title {{ subcontrol-origin: margin; left: 2px; top: 0; color: {c.muted}; }} + +QLabel#titleLabel {{ font-size: 11pt; font-weight: 600; }} +QLabel[caption="true"] {{ color: {c.muted}; font-size: 8pt; }} +QLabel[statValue="true"] {{ font-size: 11pt; font-weight: 600; }} + +QLineEdit, QPlainTextEdit {{ + background: {c.sunken}; border: 1px solid {c.border}; border-radius: 5px; padding: 3px 6px; + selection-background-color: {c.accent}; selection-color: {c.on_accent}; +}} +QLineEdit:focus {{ border-color: {c.accent}; }} +QPlainTextEdit#logView {{ + font-family: "Cascadia Mono", "Consolas", monospace; font-size: 8pt; color: {c.muted}; +}} + +QPushButton {{ + background: {c.panel}; border: 1px solid {c.border}; border-radius: 5px; padding: 5px 12px; +}} +QPushButton:hover {{ border-color: {c.accent}; }} +QPushButton:pressed {{ background: {c.sunken}; }} +QPushButton:disabled {{ color: {c.muted}; }} +QPushButton[flat="true"] {{ border: none; background: transparent; color: {c.muted}; }} +QPushButton[flat="true"]:hover {{ color: {c.text}; background: {c.grid}; }} +QPushButton#startButton, QPushButton#compactStartButton {{ + background: {c.accent}; color: {c.on_accent}; border: none; min-height: 30px; + font-size: 10pt; font-weight: 600; +}} +QPushButton#startButton[fishing="true"], QPushButton#compactStartButton[fishing="true"] {{ + background: {c.danger}; +}} +QPushButton#startButton:disabled, QPushButton#compactStartButton:disabled {{ + background: {c.grid}; color: {c.muted}; +}} + +QLabel#bobberColorLabel {{ border: 1px solid {c.border}; border-radius: 4px; }} +QStatusBar {{ background: {c.background}; color: {c.muted}; }} +QScrollBar:vertical {{ background: transparent; width: 8px; }} +QScrollBar::handle:vertical {{ background: {c.border}; border-radius: 4px; min-height: 24px; }} +QScrollBar::add-line, QScrollBar::sub-line {{ height: 0; }} +""" + + +def apply(app: QApplication, *, dark: bool) -> None: + """Fusion with a matching palette (covers widgets the stylesheet skips) plus the stylesheet.""" + global _current + c = _current = DARK if dark else LIGHT + app.setStyle("Fusion") + palette = QPalette() + for role, color in ( + (QPalette.ColorRole.Window, c.background), + (QPalette.ColorRole.WindowText, c.text), + (QPalette.ColorRole.Base, c.sunken), + (QPalette.ColorRole.AlternateBase, c.panel), + (QPalette.ColorRole.Text, c.text), + (QPalette.ColorRole.Button, c.panel), + (QPalette.ColorRole.ButtonText, c.text), + (QPalette.ColorRole.Highlight, c.accent), + (QPalette.ColorRole.HighlightedText, c.on_accent), + (QPalette.ColorRole.ToolTipBase, c.panel), + (QPalette.ColorRole.ToolTipText, c.text), + (QPalette.ColorRole.PlaceholderText, c.muted), + ): + palette.setColor(role, QColor(color)) + app.setPalette(palette) + app.setStyleSheet(stylesheet(c)) diff --git a/src/getthefish/gui/ui_main.py b/src/getthefish/gui/ui_main.py index 7e931f4..edbc7fe 100644 --- a/src/getthefish/gui/ui_main.py +++ b/src/getthefish/gui/ui_main.py @@ -15,182 +15,606 @@ QFont, QFontDatabase, QGradient, QIcon, QImage, QKeySequence, QLinearGradient, QPainter, QPalette, QPixmap, QRadialGradient, QTransform) -from PySide6.QtWidgets import (QApplication, QCheckBox, QGridLayout, QHBoxLayout, - QLabel, QLineEdit, QMainWindow, QPushButton, - QSizePolicy, QSpacerItem, QSpinBox, QStatusBar, - QVBoxLayout, QWidget) +from PySide6.QtWidgets import (QApplication, QCheckBox, QGridLayout, QGroupBox, + QHBoxLayout, QLabel, QLineEdit, QMainWindow, + QPlainTextEdit, QPushButton, QSizePolicy, QSpacerItem, + QSpinBox, QStackedWidget, QStatusBar, QVBoxLayout, + QWidget) + +from getthefish.gui.widgets import (BiteMeter, RoundHistory, StatusLed) class Ui_MainWindow(object): def setupUi(self, MainWindow): if not MainWindow.objectName(): MainWindow.setObjectName(u"MainWindow") - MainWindow.resize(319, 274) + MainWindow.resize(1000, 600) self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName(u"centralwidget") - self.horizontalLayout = QHBoxLayout(self.centralwidget) - self.horizontalLayout.setObjectName(u"horizontalLayout") - self.verticalLayout_2 = QVBoxLayout() - self.verticalLayout_2.setObjectName(u"verticalLayout_2") - self.gridLayout = QGridLayout() - self.gridLayout.setObjectName(u"gridLayout") - self.label_3 = QLabel(self.centralwidget) - self.label_3.setObjectName(u"label_3") - - self.gridLayout.addWidget(self.label_3, 1, 0, 1, 1) - - self.posStartLabel = QLabel(self.centralwidget) + self.mainLayout = QVBoxLayout(self.centralwidget) + self.mainLayout.setSpacing(8) + self.mainLayout.setObjectName(u"mainLayout") + self.mainLayout.setContentsMargins(12, 12, 12, 12) + self.headerLayout = QHBoxLayout() + self.headerLayout.setSpacing(8) + self.headerLayout.setObjectName(u"headerLayout") + self.titleLabel = QLabel(self.centralwidget) + self.titleLabel.setObjectName(u"titleLabel") + + self.headerLayout.addWidget(self.titleLabel) + + self.statusLed = StatusLed(self.centralwidget) + self.statusLed.setObjectName(u"statusLed") + + self.headerLayout.addWidget(self.statusLed) + + self.headerSpacer = QSpacerItem(10, 0, QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum) + + self.headerLayout.addItem(self.headerSpacer) + + self.themeButton = QPushButton(self.centralwidget) + self.themeButton.setObjectName(u"themeButton") + self.themeButton.setFlat(True) + self.themeButton.setFocusPolicy(Qt.FocusPolicy.NoFocus) + + self.headerLayout.addWidget(self.themeButton) + + self.viewButton = QPushButton(self.centralwidget) + self.viewButton.setObjectName(u"viewButton") + self.viewButton.setFlat(True) + self.viewButton.setFocusPolicy(Qt.FocusPolicy.NoFocus) + + self.headerLayout.addWidget(self.viewButton) + + + self.mainLayout.addLayout(self.headerLayout) + + self.pages = QStackedWidget(self.centralwidget) + self.pages.setObjectName(u"pages") + self.fullPage = QWidget() + self.fullPage.setObjectName(u"fullPage") + self.fullLayout = QHBoxLayout(self.fullPage) + self.fullLayout.setSpacing(12) + self.fullLayout.setObjectName(u"fullLayout") + self.fullLayout.setContentsMargins(0, 0, 0, 0) + self.leftColumn = QVBoxLayout() + self.leftColumn.setSpacing(4) + self.leftColumn.setObjectName(u"leftColumn") + self.setupGroup = QGroupBox(self.fullPage) + self.setupGroup.setObjectName(u"setupGroup") + self.setupGroup.setMinimumSize(QSize(320, 0)) + self.setupGroup.setMaximumSize(QSize(320, 16777215)) + self.setupLayout = QGridLayout(self.setupGroup) + self.setupLayout.setSpacing(8) + self.setupLayout.setObjectName(u"setupLayout") + self.areaLabel = QLabel(self.setupGroup) + self.areaLabel.setObjectName(u"areaLabel") + + self.setupLayout.addWidget(self.areaLabel, 0, 0, 1, 1) + + self.areaLayout = QHBoxLayout() + self.areaLayout.setObjectName(u"areaLayout") + self.posStartLabel = QLabel(self.setupGroup) self.posStartLabel.setObjectName(u"posStartLabel") - self.gridLayout.addWidget(self.posStartLabel, 1, 1, 1, 1) + self.areaLayout.addWidget(self.posStartLabel) - self.label_4 = QLabel(self.centralwidget) - self.label_4.setObjectName(u"label_4") + self.areaArrowLabel = QLabel(self.setupGroup) + self.areaArrowLabel.setObjectName(u"areaArrowLabel") - self.gridLayout.addWidget(self.label_4, 2, 0, 1, 1) + self.areaLayout.addWidget(self.areaArrowLabel) - self.posEndLabel = QLabel(self.centralwidget) + self.posEndLabel = QLabel(self.setupGroup) self.posEndLabel.setObjectName(u"posEndLabel") - self.gridLayout.addWidget(self.posEndLabel, 2, 1, 1, 1) + self.areaLayout.addWidget(self.posEndLabel) - self.label_6 = QLabel(self.centralwidget) - self.label_6.setObjectName(u"label_6") + self.areaSpacer = QSpacerItem(10, 0, QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum) - self.gridLayout.addWidget(self.label_6, 0, 0, 1, 1) + self.areaLayout.addItem(self.areaSpacer) - self.verticalLayout_2.addLayout(self.gridLayout) + self.setupLayout.addLayout(self.areaLayout, 0, 1, 1, 1) - self.horizontalLayout_3 = QHBoxLayout() - self.horizontalLayout_3.setObjectName(u"horizontalLayout_3") - self.label_5 = QLabel(self.centralwidget) - self.label_5.setObjectName(u"label_5") + self.areaButton = QPushButton(self.setupGroup) + self.areaButton.setObjectName(u"areaButton") - self.horizontalLayout_3.addWidget(self.label_5) + self.setupLayout.addWidget(self.areaButton, 0, 2, 1, 1) - self.bobberColorLabel = QLabel(self.centralwidget) - self.bobberColorLabel.setObjectName(u"bobberColorLabel") - sizePolicy = QSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed) - sizePolicy.setHorizontalStretch(0) - sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.bobberColorLabel.sizePolicy().hasHeightForWidth()) - self.bobberColorLabel.setSizePolicy(sizePolicy) - self.bobberColorLabel.setMinimumSize(QSize(20, 20)) - self.bobberColorLabel.setMaximumSize(QSize(20, 20)) + self.bobberLabel = QLabel(self.setupGroup) + self.bobberLabel.setObjectName(u"bobberLabel") - self.horizontalLayout_3.addWidget(self.bobberColorLabel) + self.setupLayout.addWidget(self.bobberLabel, 1, 0, 1, 1) - self.horizontalSpacer_2 = QSpacerItem(40, 20, QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum) + self.colorLayout = QHBoxLayout() + self.colorLayout.setObjectName(u"colorLayout") + self.bobberColorLabel = QLabel(self.setupGroup) + self.bobberColorLabel.setObjectName(u"bobberColorLabel") + self.bobberColorLabel.setMinimumSize(QSize(18, 18)) + self.bobberColorLabel.setMaximumSize(QSize(18, 18)) - self.horizontalLayout_3.addItem(self.horizontalSpacer_2) + self.colorLayout.addWidget(self.bobberColorLabel) - self.hexColorLabel = QLabel(self.centralwidget) + self.hexColorLabel = QLabel(self.setupGroup) self.hexColorLabel.setObjectName(u"hexColorLabel") - self.horizontalLayout_3.addWidget(self.hexColorLabel) + self.colorLayout.addWidget(self.hexColorLabel) + + self.colorSpacer = QSpacerItem(10, 0, QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum) + + self.colorLayout.addItem(self.colorSpacer) + + self.setupLayout.addLayout(self.colorLayout, 1, 1, 1, 1) - self.verticalLayout_2.addLayout(self.horizontalLayout_3) + self.colorButton = QPushButton(self.setupGroup) + self.colorButton.setObjectName(u"colorButton") + + self.setupLayout.addWidget(self.colorButton, 1, 2, 1, 1) + + self.castKeyLabel = QLabel(self.setupGroup) + self.castKeyLabel.setObjectName(u"castKeyLabel") + + self.setupLayout.addWidget(self.castKeyLabel, 2, 0, 1, 1) - self.verticalSpacer_3 = QSpacerItem(20, 5, QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Fixed) + self.castKeyEdit = QLineEdit(self.setupGroup) + self.castKeyEdit.setObjectName(u"castKeyEdit") + self.castKeyEdit.setMaxLength(20) + + self.setupLayout.addWidget(self.castKeyEdit, 2, 1, 1, 2) - self.verticalLayout_2.addItem(self.verticalSpacer_3) - self.label = QLabel(self.centralwidget) - self.label.setObjectName(u"label") + self.leftColumn.addWidget(self.setupGroup) - self.verticalLayout_2.addWidget(self.label) + self.tuningGroup = QGroupBox(self.fullPage) + self.tuningGroup.setObjectName(u"tuningGroup") + self.tuningGroup.setMinimumSize(QSize(320, 0)) + self.tuningGroup.setMaximumSize(QSize(320, 16777215)) + self.tuningLayout = QGridLayout(self.tuningGroup) + self.tuningLayout.setSpacing(8) + self.tuningLayout.setObjectName(u"tuningLayout") + self.thresholdBobberLabel = QLabel(self.tuningGroup) + self.thresholdBobberLabel.setObjectName(u"thresholdBobberLabel") - self.thresholdBobberSpinBox = QSpinBox(self.centralwidget) + self.tuningLayout.addWidget(self.thresholdBobberLabel, 0, 0, 1, 1) + + self.thresholdBobberSpinBox = QSpinBox(self.tuningGroup) self.thresholdBobberSpinBox.setObjectName(u"thresholdBobberSpinBox") + sizePolicy = QSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed) + sizePolicy.setHorizontalStretch(0) + sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.thresholdBobberSpinBox.sizePolicy().hasHeightForWidth()) self.thresholdBobberSpinBox.setSizePolicy(sizePolicy) self.thresholdBobberSpinBox.setMinimumSize(QSize(120, 0)) self.thresholdBobberSpinBox.setMaximumSize(QSize(120, 16777215)) - self.verticalLayout_2.addWidget(self.thresholdBobberSpinBox) + self.tuningLayout.addWidget(self.thresholdBobberSpinBox, 0, 1, 1, 1) - self.label_2 = QLabel(self.centralwidget) - self.label_2.setObjectName(u"label_2") + self.thresholdCatchLabel = QLabel(self.tuningGroup) + self.thresholdCatchLabel.setObjectName(u"thresholdCatchLabel") - self.verticalLayout_2.addWidget(self.label_2) + self.tuningLayout.addWidget(self.thresholdCatchLabel, 1, 0, 1, 1) - self.thresholdCatchSpinBox = QSpinBox(self.centralwidget) + self.thresholdCatchSpinBox = QSpinBox(self.tuningGroup) self.thresholdCatchSpinBox.setObjectName(u"thresholdCatchSpinBox") sizePolicy.setHeightForWidth(self.thresholdCatchSpinBox.sizePolicy().hasHeightForWidth()) self.thresholdCatchSpinBox.setSizePolicy(sizePolicy) self.thresholdCatchSpinBox.setMinimumSize(QSize(120, 0)) self.thresholdCatchSpinBox.setMaximumSize(QSize(120, 16777215)) - self.verticalLayout_2.addWidget(self.thresholdCatchSpinBox) + self.tuningLayout.addWidget(self.thresholdCatchSpinBox, 1, 1, 1, 1) - self.castKeyLabel = QLabel(self.centralwidget) - self.castKeyLabel.setObjectName(u"castKeyLabel") + self.jumpToBobberCheck = QCheckBox(self.tuningGroup) + self.jumpToBobberCheck.setObjectName(u"jumpToBobberCheck") - self.verticalLayout_2.addWidget(self.castKeyLabel) + self.tuningLayout.addWidget(self.jumpToBobberCheck, 2, 0, 1, 2) - self.castKeyEdit = QLineEdit(self.centralwidget) - self.castKeyEdit.setObjectName(u"castKeyEdit") - sizePolicy.setHeightForWidth(self.castKeyEdit.sizePolicy().hasHeightForWidth()) - self.castKeyEdit.setSizePolicy(sizePolicy) - self.castKeyEdit.setMinimumSize(QSize(60, 0)) - self.castKeyEdit.setMaximumSize(QSize(60, 16777215)) - self.castKeyEdit.setMaxLength(20) + self.verboseCheck = QCheckBox(self.tuningGroup) + self.verboseCheck.setObjectName(u"verboseCheck") - self.verticalLayout_2.addWidget(self.castKeyEdit) + self.tuningLayout.addWidget(self.verboseCheck, 3, 0, 1, 2) - self.jumpToBobberCheck = QCheckBox(self.centralwidget) - self.jumpToBobberCheck.setObjectName(u"jumpToBobberCheck") - self.verticalLayout_2.addWidget(self.jumpToBobberCheck) + self.leftColumn.addWidget(self.tuningGroup) - self.verboseCheck = QCheckBox(self.centralwidget) - self.verboseCheck.setObjectName(u"verboseCheck") + self.startLayout = QVBoxLayout() + self.startLayout.setObjectName(u"startLayout") + self.startLayout.setContentsMargins(-1, 12, -1, -1) + self.startButton = QPushButton(self.fullPage) + self.startButton.setObjectName(u"startButton") - self.verticalLayout_2.addWidget(self.verboseCheck) + self.startLayout.addWidget(self.startButton) - self.verticalSpacer_2 = QSpacerItem(20, 40, QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Expanding) - self.verticalLayout_2.addItem(self.verticalSpacer_2) + self.leftColumn.addLayout(self.startLayout) + self.leftSpacer = QSpacerItem(0, 10, QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Expanding) - self.horizontalLayout.addLayout(self.verticalLayout_2) + self.leftColumn.addItem(self.leftSpacer) - self.horizontalSpacer = QSpacerItem(350, 0, QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum) + self.leftColumn.setStretch(3, 1) - self.horizontalLayout.addItem(self.horizontalSpacer) + self.fullLayout.addLayout(self.leftColumn) - self.verticalLayout = QVBoxLayout() - self.verticalLayout.setObjectName(u"verticalLayout") - self.startButton = QPushButton(self.centralwidget) - self.startButton.setObjectName(u"startButton") + self.rightColumn = QVBoxLayout() + self.rightColumn.setSpacing(4) + self.rightColumn.setObjectName(u"rightColumn") + self.sessionGroup = QGroupBox(self.fullPage) + self.sessionGroup.setObjectName(u"sessionGroup") + self.sessionLayout = QVBoxLayout(self.sessionGroup) + self.sessionLayout.setSpacing(10) + self.sessionLayout.setObjectName(u"sessionLayout") + self.statsLayout = QGridLayout() + self.statsLayout.setSpacing(6) + self.statsLayout.setObjectName(u"statsLayout") + self.castsCaption = QLabel(self.sessionGroup) + self.castsCaption.setObjectName(u"castsCaption") + self.castsCaption.setProperty(u"caption", True) - self.verticalLayout.addWidget(self.startButton) + self.statsLayout.addWidget(self.castsCaption, 0, 1, 1, 1) - self.areaButton = QPushButton(self.centralwidget) - self.areaButton.setObjectName(u"areaButton") + self.castsValue = QLabel(self.sessionGroup) + self.castsValue.setObjectName(u"castsValue") + self.castsValue.setProperty(u"statValue", True) - self.verticalLayout.addWidget(self.areaButton) + self.statsLayout.addWidget(self.castsValue, 1, 1, 1, 1) - self.colorButton = QPushButton(self.centralwidget) - self.colorButton.setObjectName(u"colorButton") + self.todayCastsValue = QLabel(self.sessionGroup) + self.todayCastsValue.setObjectName(u"todayCastsValue") + self.todayCastsValue.setProperty(u"statValue", True) + + self.statsLayout.addWidget(self.todayCastsValue, 2, 1, 1, 1) + + self.totalCastsValue = QLabel(self.sessionGroup) + self.totalCastsValue.setObjectName(u"totalCastsValue") + self.totalCastsValue.setProperty(u"statValue", True) + + self.statsLayout.addWidget(self.totalCastsValue, 3, 1, 1, 1) + + self.catchesCaption = QLabel(self.sessionGroup) + self.catchesCaption.setObjectName(u"catchesCaption") + self.catchesCaption.setProperty(u"caption", True) + + self.statsLayout.addWidget(self.catchesCaption, 0, 2, 1, 1) + + self.catchesValue = QLabel(self.sessionGroup) + self.catchesValue.setObjectName(u"catchesValue") + self.catchesValue.setProperty(u"statValue", True) + + self.statsLayout.addWidget(self.catchesValue, 1, 2, 1, 1) + + self.todayCatchesValue = QLabel(self.sessionGroup) + self.todayCatchesValue.setObjectName(u"todayCatchesValue") + self.todayCatchesValue.setProperty(u"statValue", True) + + self.statsLayout.addWidget(self.todayCatchesValue, 2, 2, 1, 1) + + self.totalCatchesValue = QLabel(self.sessionGroup) + self.totalCatchesValue.setObjectName(u"totalCatchesValue") + self.totalCatchesValue.setProperty(u"statValue", True) + + self.statsLayout.addWidget(self.totalCatchesValue, 3, 2, 1, 1) + + self.missesCaption = QLabel(self.sessionGroup) + self.missesCaption.setObjectName(u"missesCaption") + self.missesCaption.setProperty(u"caption", True) + + self.statsLayout.addWidget(self.missesCaption, 0, 3, 1, 1) + + self.missesValue = QLabel(self.sessionGroup) + self.missesValue.setObjectName(u"missesValue") + self.missesValue.setProperty(u"statValue", True) + + self.statsLayout.addWidget(self.missesValue, 1, 3, 1, 1) + + self.todayMissesValue = QLabel(self.sessionGroup) + self.todayMissesValue.setObjectName(u"todayMissesValue") + self.todayMissesValue.setProperty(u"statValue", True) + + self.statsLayout.addWidget(self.todayMissesValue, 2, 3, 1, 1) + + self.totalMissesValue = QLabel(self.sessionGroup) + self.totalMissesValue.setObjectName(u"totalMissesValue") + self.totalMissesValue.setProperty(u"statValue", True) + + self.statsLayout.addWidget(self.totalMissesValue, 3, 3, 1, 1) + + self.rateCaption = QLabel(self.sessionGroup) + self.rateCaption.setObjectName(u"rateCaption") + self.rateCaption.setProperty(u"caption", True) + + self.statsLayout.addWidget(self.rateCaption, 0, 4, 1, 1) + + self.rateValue = QLabel(self.sessionGroup) + self.rateValue.setObjectName(u"rateValue") + self.rateValue.setProperty(u"statValue", True) + + self.statsLayout.addWidget(self.rateValue, 1, 4, 1, 1) + + self.todayRateValue = QLabel(self.sessionGroup) + self.todayRateValue.setObjectName(u"todayRateValue") + self.todayRateValue.setProperty(u"statValue", True) + + self.statsLayout.addWidget(self.todayRateValue, 2, 4, 1, 1) + + self.totalRateValue = QLabel(self.sessionGroup) + self.totalRateValue.setObjectName(u"totalRateValue") + self.totalRateValue.setProperty(u"statValue", True) + + self.statsLayout.addWidget(self.totalRateValue, 3, 4, 1, 1) + + self.perHourCaption = QLabel(self.sessionGroup) + self.perHourCaption.setObjectName(u"perHourCaption") + self.perHourCaption.setProperty(u"caption", True) + + self.statsLayout.addWidget(self.perHourCaption, 0, 5, 1, 1) + + self.perHourValue = QLabel(self.sessionGroup) + self.perHourValue.setObjectName(u"perHourValue") + self.perHourValue.setProperty(u"statValue", True) + + self.statsLayout.addWidget(self.perHourValue, 1, 5, 1, 1) + + self.todayPerHourValue = QLabel(self.sessionGroup) + self.todayPerHourValue.setObjectName(u"todayPerHourValue") + self.todayPerHourValue.setProperty(u"statValue", True) + + self.statsLayout.addWidget(self.todayPerHourValue, 2, 5, 1, 1) + + self.totalPerHourValue = QLabel(self.sessionGroup) + self.totalPerHourValue.setObjectName(u"totalPerHourValue") + self.totalPerHourValue.setProperty(u"statValue", True) + + self.statsLayout.addWidget(self.totalPerHourValue, 3, 5, 1, 1) + + self.elapsedCaption = QLabel(self.sessionGroup) + self.elapsedCaption.setObjectName(u"elapsedCaption") + self.elapsedCaption.setProperty(u"caption", True) + + self.statsLayout.addWidget(self.elapsedCaption, 0, 6, 1, 1) + + self.elapsedValue = QLabel(self.sessionGroup) + self.elapsedValue.setObjectName(u"elapsedValue") + self.elapsedValue.setProperty(u"statValue", True) + + self.statsLayout.addWidget(self.elapsedValue, 1, 6, 1, 1) + + self.todayElapsedValue = QLabel(self.sessionGroup) + self.todayElapsedValue.setObjectName(u"todayElapsedValue") + self.todayElapsedValue.setProperty(u"statValue", True) + + self.statsLayout.addWidget(self.todayElapsedValue, 2, 6, 1, 1) + + self.totalElapsedValue = QLabel(self.sessionGroup) + self.totalElapsedValue.setObjectName(u"totalElapsedValue") + self.totalElapsedValue.setProperty(u"statValue", True) + + self.statsLayout.addWidget(self.totalElapsedValue, 3, 6, 1, 1) + + self.sessionLabel = QLabel(self.sessionGroup) + self.sessionLabel.setObjectName(u"sessionLabel") + self.sessionLabel.setProperty(u"caption", True) + + self.statsLayout.addWidget(self.sessionLabel, 1, 0, 1, 1) - self.verticalLayout.addWidget(self.colorButton) + self.todayLabel = QLabel(self.sessionGroup) + self.todayLabel.setObjectName(u"todayLabel") + self.todayLabel.setProperty(u"caption", True) - self.openConfigFolderButton = QPushButton(self.centralwidget) + self.statsLayout.addWidget(self.todayLabel, 2, 0, 1, 1) + + self.totalLabel = QLabel(self.sessionGroup) + self.totalLabel.setObjectName(u"totalLabel") + self.totalLabel.setProperty(u"caption", True) + + self.statsLayout.addWidget(self.totalLabel, 3, 0, 1, 1) + + + self.sessionLayout.addLayout(self.statsLayout) + + self.roundsLayout = QHBoxLayout() + self.roundsLayout.setSpacing(8) + self.roundsLayout.setObjectName(u"roundsLayout") + self.roundsLabel = QLabel(self.sessionGroup) + self.roundsLabel.setObjectName(u"roundsLabel") + self.roundsLabel.setProperty(u"caption", True) + + self.roundsLayout.addWidget(self.roundsLabel) + + self.roundHistory = RoundHistory(self.sessionGroup) + self.roundHistory.setObjectName(u"roundHistory") + sizePolicy1 = QSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed) + sizePolicy1.setHorizontalStretch(0) + sizePolicy1.setVerticalStretch(0) + sizePolicy1.setHeightForWidth(self.roundHistory.sizePolicy().hasHeightForWidth()) + self.roundHistory.setSizePolicy(sizePolicy1) + + self.roundsLayout.addWidget(self.roundHistory) + + + self.sessionLayout.addLayout(self.roundsLayout) + + + self.rightColumn.addWidget(self.sessionGroup) + + self.meterGroup = QGroupBox(self.fullPage) + self.meterGroup.setObjectName(u"meterGroup") + self.meterLayout = QVBoxLayout(self.meterGroup) + self.meterLayout.setObjectName(u"meterLayout") + self.biteMeter = BiteMeter(self.meterGroup) + self.biteMeter.setObjectName(u"biteMeter") + self.biteMeter.setMinimumSize(QSize(0, 120)) + + self.meterLayout.addWidget(self.biteMeter) + + + self.rightColumn.addWidget(self.meterGroup) + + self.logGroup = QGroupBox(self.fullPage) + self.logGroup.setObjectName(u"logGroup") + self.logLayout = QVBoxLayout(self.logGroup) + self.logLayout.setObjectName(u"logLayout") + self.logView = QPlainTextEdit(self.logGroup) + self.logView.setObjectName(u"logView") + self.logView.setReadOnly(True) + self.logView.setMaximumBlockCount(500) + + self.logLayout.addWidget(self.logView) + + self.logButtonLayout = QHBoxLayout() + self.logButtonLayout.setObjectName(u"logButtonLayout") + self.logButtonSpacer = QSpacerItem(10, 0, QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum) + + self.logButtonLayout.addItem(self.logButtonSpacer) + + self.openConfigFolderButton = QPushButton(self.logGroup) self.openConfigFolderButton.setObjectName(u"openConfigFolderButton") - self.verticalLayout.addWidget(self.openConfigFolderButton) + self.logButtonLayout.addWidget(self.openConfigFolderButton) + + + self.logLayout.addLayout(self.logButtonLayout) + + + self.rightColumn.addWidget(self.logGroup) + + self.rightColumn.setStretch(2, 1) + + self.fullLayout.addLayout(self.rightColumn) + + self.fullLayout.setStretch(1, 1) + self.pages.addWidget(self.fullPage) + self.compactPage = QWidget() + self.compactPage.setObjectName(u"compactPage") + self.compactLayout = QVBoxLayout(self.compactPage) + self.compactLayout.setSpacing(8) + self.compactLayout.setObjectName(u"compactLayout") + self.compactLayout.setContentsMargins(0, 0, 0, 0) + self.compactStartButton = QPushButton(self.compactPage) + self.compactStartButton.setObjectName(u"compactStartButton") + + self.compactLayout.addWidget(self.compactStartButton) + + self.compactRoundHistory = RoundHistory(self.compactPage) + self.compactRoundHistory.setObjectName(u"compactRoundHistory") + sizePolicy1.setHeightForWidth(self.compactRoundHistory.sizePolicy().hasHeightForWidth()) + self.compactRoundHistory.setSizePolicy(sizePolicy1) + + self.compactLayout.addWidget(self.compactRoundHistory) + + self.compactStatsLayout = QGridLayout() + self.compactStatsLayout.setSpacing(2) + self.compactStatsLayout.setObjectName(u"compactStatsLayout") + self.compactCaughtCaption = QLabel(self.compactPage) + self.compactCaughtCaption.setObjectName(u"compactCaughtCaption") + self.compactCaughtCaption.setProperty(u"caption", True) + self.compactCaughtCaption.setAlignment(Qt.AlignmentFlag.AlignRight|Qt.AlignmentFlag.AlignVCenter) + + self.compactStatsLayout.addWidget(self.compactCaughtCaption, 0, 1, 1, 1) + + self.compactRateCaption = QLabel(self.compactPage) + self.compactRateCaption.setObjectName(u"compactRateCaption") + self.compactRateCaption.setProperty(u"caption", True) + self.compactRateCaption.setAlignment(Qt.AlignmentFlag.AlignRight|Qt.AlignmentFlag.AlignVCenter) + + self.compactStatsLayout.addWidget(self.compactRateCaption, 0, 2, 1, 1) + + self.compactTimeCaption = QLabel(self.compactPage) + self.compactTimeCaption.setObjectName(u"compactTimeCaption") + self.compactTimeCaption.setProperty(u"caption", True) + self.compactTimeCaption.setAlignment(Qt.AlignmentFlag.AlignRight|Qt.AlignmentFlag.AlignVCenter) + + self.compactStatsLayout.addWidget(self.compactTimeCaption, 0, 3, 1, 1) + + self.compactSessionLabel = QLabel(self.compactPage) + self.compactSessionLabel.setObjectName(u"compactSessionLabel") + self.compactSessionLabel.setProperty(u"caption", True) + + self.compactStatsLayout.addWidget(self.compactSessionLabel, 1, 0, 1, 1) - self.verticalSpacer = QSpacerItem(20, 40, QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Expanding) + self.compactSessionCatches = QLabel(self.compactPage) + self.compactSessionCatches.setObjectName(u"compactSessionCatches") + self.compactSessionCatches.setAlignment(Qt.AlignmentFlag.AlignRight|Qt.AlignmentFlag.AlignVCenter) - self.verticalLayout.addItem(self.verticalSpacer) + self.compactStatsLayout.addWidget(self.compactSessionCatches, 1, 1, 1, 1) + self.compactSessionRate = QLabel(self.compactPage) + self.compactSessionRate.setObjectName(u"compactSessionRate") + self.compactSessionRate.setAlignment(Qt.AlignmentFlag.AlignRight|Qt.AlignmentFlag.AlignVCenter) - self.horizontalLayout.addLayout(self.verticalLayout) + self.compactStatsLayout.addWidget(self.compactSessionRate, 1, 2, 1, 1) - self.horizontalLayout.setStretch(0, 1) - self.horizontalLayout.setStretch(1, 2) + self.compactSessionTime = QLabel(self.compactPage) + self.compactSessionTime.setObjectName(u"compactSessionTime") + self.compactSessionTime.setAlignment(Qt.AlignmentFlag.AlignRight|Qt.AlignmentFlag.AlignVCenter) + + self.compactStatsLayout.addWidget(self.compactSessionTime, 1, 3, 1, 1) + + self.compactTodayLabel = QLabel(self.compactPage) + self.compactTodayLabel.setObjectName(u"compactTodayLabel") + self.compactTodayLabel.setProperty(u"caption", True) + + self.compactStatsLayout.addWidget(self.compactTodayLabel, 2, 0, 1, 1) + + self.compactTodayCatches = QLabel(self.compactPage) + self.compactTodayCatches.setObjectName(u"compactTodayCatches") + self.compactTodayCatches.setAlignment(Qt.AlignmentFlag.AlignRight|Qt.AlignmentFlag.AlignVCenter) + + self.compactStatsLayout.addWidget(self.compactTodayCatches, 2, 1, 1, 1) + + self.compactTodayRate = QLabel(self.compactPage) + self.compactTodayRate.setObjectName(u"compactTodayRate") + self.compactTodayRate.setAlignment(Qt.AlignmentFlag.AlignRight|Qt.AlignmentFlag.AlignVCenter) + + self.compactStatsLayout.addWidget(self.compactTodayRate, 2, 2, 1, 1) + + self.compactTodayTime = QLabel(self.compactPage) + self.compactTodayTime.setObjectName(u"compactTodayTime") + self.compactTodayTime.setAlignment(Qt.AlignmentFlag.AlignRight|Qt.AlignmentFlag.AlignVCenter) + + self.compactStatsLayout.addWidget(self.compactTodayTime, 2, 3, 1, 1) + + self.compactTotalLabel = QLabel(self.compactPage) + self.compactTotalLabel.setObjectName(u"compactTotalLabel") + self.compactTotalLabel.setProperty(u"caption", True) + + self.compactStatsLayout.addWidget(self.compactTotalLabel, 3, 0, 1, 1) + + self.compactTotalCatches = QLabel(self.compactPage) + self.compactTotalCatches.setObjectName(u"compactTotalCatches") + self.compactTotalCatches.setAlignment(Qt.AlignmentFlag.AlignRight|Qt.AlignmentFlag.AlignVCenter) + + self.compactStatsLayout.addWidget(self.compactTotalCatches, 3, 1, 1, 1) + + self.compactTotalRate = QLabel(self.compactPage) + self.compactTotalRate.setObjectName(u"compactTotalRate") + self.compactTotalRate.setAlignment(Qt.AlignmentFlag.AlignRight|Qt.AlignmentFlag.AlignVCenter) + + self.compactStatsLayout.addWidget(self.compactTotalRate, 3, 2, 1, 1) + + self.compactTotalTime = QLabel(self.compactPage) + self.compactTotalTime.setObjectName(u"compactTotalTime") + self.compactTotalTime.setAlignment(Qt.AlignmentFlag.AlignRight|Qt.AlignmentFlag.AlignVCenter) + + self.compactStatsLayout.addWidget(self.compactTotalTime, 3, 3, 1, 1) + + self.compactStatsLayout.setColumnStretch(0, 1) + self.compactStatsLayout.setColumnStretch(1, 1) + self.compactStatsLayout.setColumnStretch(2, 1) + self.compactStatsLayout.setColumnStretch(3, 1) + + self.compactLayout.addLayout(self.compactStatsLayout) + + self.compactMeter = BiteMeter(self.compactPage) + self.compactMeter.setObjectName(u"compactMeter") + self.compactMeter.setMinimumSize(QSize(0, 80)) + + self.compactLayout.addWidget(self.compactMeter) + + self.pages.addWidget(self.compactPage) + + self.mainLayout.addWidget(self.pages) + + self.mainLayout.setStretch(1, 1) MainWindow.setCentralWidget(self.centralwidget) self.statusbar = QStatusBar(MainWindow) self.statusbar.setObjectName(u"statusbar") @@ -203,24 +627,94 @@ def setupUi(self, MainWindow): def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(QCoreApplication.translate("MainWindow", u"GetTheFish", None)) - self.label_3.setText(QCoreApplication.translate("MainWindow", u"Start:", None)) + self.titleLabel.setText(QCoreApplication.translate("MainWindow", u"GetTheFish", None)) + self.themeButton.setText(QCoreApplication.translate("MainWindow", u"Light", None)) +#if QT_CONFIG(tooltip) + self.themeButton.setToolTip(QCoreApplication.translate("MainWindow", u"Switch between light and dark mode", None)) +#endif // QT_CONFIG(tooltip) + self.viewButton.setText(QCoreApplication.translate("MainWindow", u"Compact", None)) +#if QT_CONFIG(tooltip) + self.viewButton.setToolTip(QCoreApplication.translate("MainWindow", u"Switch between the full and the compact view", None)) +#endif // QT_CONFIG(tooltip) + self.setupGroup.setTitle(QCoreApplication.translate("MainWindow", u"Setup", None)) + self.areaLabel.setText(QCoreApplication.translate("MainWindow", u"Area", None)) self.posStartLabel.setText("") - self.label_4.setText(QCoreApplication.translate("MainWindow", u"End", None)) + self.areaArrowLabel.setText(QCoreApplication.translate("MainWindow", u"\u2192", None)) self.posEndLabel.setText("") - self.label_6.setText(QCoreApplication.translate("MainWindow", u"Fishing Area", None)) - self.label_5.setText(QCoreApplication.translate("MainWindow", u"Bobber Color", None)) + self.areaButton.setText(QCoreApplication.translate("MainWindow", u"Set Area", None)) +#if QT_CONFIG(tooltip) + self.areaButton.setToolTip(QCoreApplication.translate("MainWindow", u"Drag a rectangle over the water where the bobber lands", None)) +#endif // QT_CONFIG(tooltip) + self.bobberLabel.setText(QCoreApplication.translate("MainWindow", u"Bobber", None)) self.bobberColorLabel.setText("") self.hexColorLabel.setText("") - self.label.setText(QCoreApplication.translate("MainWindow", u"Threshold Bobber", None)) - self.label_2.setText(QCoreApplication.translate("MainWindow", u"Threshold Catch", None)) + self.colorButton.setText(QCoreApplication.translate("MainWindow", u"Pick Color", None)) +#if QT_CONFIG(tooltip) + self.colorButton.setToolTip(QCoreApplication.translate("MainWindow", u"Click the bobber in a frozen screenshot", None)) +#endif // QT_CONFIG(tooltip) self.castKeyLabel.setText(QCoreApplication.translate("MainWindow", u"Cast Key", None)) #if QT_CONFIG(tooltip) self.castKeyEdit.setToolTip(QCoreApplication.translate("MainWindow", u"Key bound to the Fishing spell in the game, e.g. 0, f, f1, num0", None)) +#endif // QT_CONFIG(tooltip) + self.tuningGroup.setTitle(QCoreApplication.translate("MainWindow", u"Tuning", None)) + self.thresholdBobberLabel.setText(QCoreApplication.translate("MainWindow", u"Threshold Bobber", None)) +#if QT_CONFIG(tooltip) + self.thresholdBobberSpinBox.setToolTip(QCoreApplication.translate("MainWindow", u"Per-channel RGB tolerance when searching for the bobber colour", None)) +#endif // QT_CONFIG(tooltip) + self.thresholdCatchLabel.setText(QCoreApplication.translate("MainWindow", u"Threshold Catch", None)) +#if QT_CONFIG(tooltip) + self.thresholdCatchSpinBox.setToolTip(QCoreApplication.translate("MainWindow", u"Colour change of the watched pixel that counts as a bite (dashed line in the meter)", None)) #endif // QT_CONFIG(tooltip) self.jumpToBobberCheck.setText(QCoreApplication.translate("MainWindow", u"Jump to Bobber", None)) - self.verboseCheck.setText(QCoreApplication.translate("MainWindow", u"verbose", None)) + self.verboseCheck.setText(QCoreApplication.translate("MainWindow", u"Verbose Log", None)) self.startButton.setText(QCoreApplication.translate("MainWindow", u"Start", None)) - self.areaButton.setText(QCoreApplication.translate("MainWindow", u"Set Area", None)) - self.colorButton.setText(QCoreApplication.translate("MainWindow", u"Select Color", None)) + self.sessionGroup.setTitle(QCoreApplication.translate("MainWindow", u"Statistics", None)) + self.castsCaption.setText(QCoreApplication.translate("MainWindow", u"Casts", None)) + self.castsValue.setText(QCoreApplication.translate("MainWindow", u"\u2013", None)) + self.todayCastsValue.setText(QCoreApplication.translate("MainWindow", u"\u2013", None)) + self.totalCastsValue.setText(QCoreApplication.translate("MainWindow", u"\u2013", None)) + self.catchesCaption.setText(QCoreApplication.translate("MainWindow", u"Catches", None)) + self.catchesValue.setText(QCoreApplication.translate("MainWindow", u"\u2013", None)) + self.todayCatchesValue.setText(QCoreApplication.translate("MainWindow", u"\u2013", None)) + self.totalCatchesValue.setText(QCoreApplication.translate("MainWindow", u"\u2013", None)) + self.missesCaption.setText(QCoreApplication.translate("MainWindow", u"Misses", None)) + self.missesValue.setText(QCoreApplication.translate("MainWindow", u"\u2013", None)) + self.todayMissesValue.setText(QCoreApplication.translate("MainWindow", u"\u2013", None)) + self.totalMissesValue.setText(QCoreApplication.translate("MainWindow", u"\u2013", None)) + self.rateCaption.setText(QCoreApplication.translate("MainWindow", u"Catch rate", None)) + self.rateValue.setText(QCoreApplication.translate("MainWindow", u"\u2013", None)) + self.todayRateValue.setText(QCoreApplication.translate("MainWindow", u"\u2013", None)) + self.totalRateValue.setText(QCoreApplication.translate("MainWindow", u"\u2013", None)) + self.perHourCaption.setText(QCoreApplication.translate("MainWindow", u"Fish / hour", None)) + self.perHourValue.setText(QCoreApplication.translate("MainWindow", u"\u2013", None)) + self.todayPerHourValue.setText(QCoreApplication.translate("MainWindow", u"\u2013", None)) + self.totalPerHourValue.setText(QCoreApplication.translate("MainWindow", u"\u2013", None)) + self.elapsedCaption.setText(QCoreApplication.translate("MainWindow", u"Fishing time", None)) + self.elapsedValue.setText(QCoreApplication.translate("MainWindow", u"\u2013", None)) + self.todayElapsedValue.setText(QCoreApplication.translate("MainWindow", u"\u2013", None)) + self.totalElapsedValue.setText(QCoreApplication.translate("MainWindow", u"\u2013", None)) + self.sessionLabel.setText(QCoreApplication.translate("MainWindow", u"Session", None)) + self.todayLabel.setText(QCoreApplication.translate("MainWindow", u"Today", None)) + self.totalLabel.setText(QCoreApplication.translate("MainWindow", u"Total", None)) + self.roundsLabel.setText(QCoreApplication.translate("MainWindow", u"Last rounds", None)) + self.meterGroup.setTitle(QCoreApplication.translate("MainWindow", u"Bite meter", None)) + self.logGroup.setTitle(QCoreApplication.translate("MainWindow", u"Log", None)) self.openConfigFolderButton.setText(QCoreApplication.translate("MainWindow", u"Open Config/Logs Folder", None)) + self.compactStartButton.setText(QCoreApplication.translate("MainWindow", u"Start", None)) + self.compactCaughtCaption.setText(QCoreApplication.translate("MainWindow", u"Caught", None)) + self.compactRateCaption.setText(QCoreApplication.translate("MainWindow", u"Rate", None)) + self.compactTimeCaption.setText(QCoreApplication.translate("MainWindow", u"Time", None)) + self.compactSessionLabel.setText(QCoreApplication.translate("MainWindow", u"Session", None)) + self.compactSessionCatches.setText(QCoreApplication.translate("MainWindow", u"\u2013", None)) + self.compactSessionRate.setText(QCoreApplication.translate("MainWindow", u"\u2013", None)) + self.compactSessionTime.setText(QCoreApplication.translate("MainWindow", u"\u2013", None)) + self.compactTodayLabel.setText(QCoreApplication.translate("MainWindow", u"Today", None)) + self.compactTodayCatches.setText(QCoreApplication.translate("MainWindow", u"\u2013", None)) + self.compactTodayRate.setText(QCoreApplication.translate("MainWindow", u"\u2013", None)) + self.compactTodayTime.setText(QCoreApplication.translate("MainWindow", u"\u2013", None)) + self.compactTotalLabel.setText(QCoreApplication.translate("MainWindow", u"Total", None)) + self.compactTotalCatches.setText(QCoreApplication.translate("MainWindow", u"\u2013", None)) + self.compactTotalRate.setText(QCoreApplication.translate("MainWindow", u"\u2013", None)) + self.compactTotalTime.setText(QCoreApplication.translate("MainWindow", u"\u2013", None)) # retranslateUi + diff --git a/src/getthefish/gui/widgets.py b/src/getthefish/gui/widgets.py new file mode 100644 index 0000000..e6add2d --- /dev/null +++ b/src/getthefish/gui/widgets.py @@ -0,0 +1,287 @@ +"""Custom-painted widgets: status LED, bite meter, round history and a log bridge.""" + +from __future__ import annotations + +import contextlib +import logging +import math +from collections import deque + +from PySide6.QtCore import QObject, QPointF, QRectF, QSize, Qt, QTimer, Signal +from PySide6.QtGui import ( + QColor, + QFont, + QFontMetrics, + QMouseEvent, + QPainter, + QPainterPath, + QPaintEvent, + QPen, + QRadialGradient, +) +from PySide6.QtWidgets import QSizePolicy, QWidget + +from getthefish.gui import theme + + +class StatusLed(QWidget): + """A tinted pill with a glowing dot and the current state. + + While ``pulse`` is on the glow breathes slowly, to show the loop is busy. + """ + + DOT = 8.0 + PAD = 10.0 + PULSE_MS = 1600 + WIDEST = "Waiting for bite" + """Width reserved for the text, so the header does not jump when the state changes.""" + + def __init__(self, parent: QWidget | None = None) -> None: + super().__init__(parent) + self.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed) + self.text = "Idle" + self.tone = "" + self.pulse = False + self._phase = 0.0 + self._timer = QTimer(self) + self._timer.setInterval(40) + self._timer.timeout.connect(self._tick) + + def set_state(self, text: str, tone: str, *, pulse: bool) -> None: + """``tone`` is a theme colour name (accent, success, warn, danger) or empty for idle.""" + self.text, self.tone, self.pulse = text, tone, pulse + if pulse and not self._timer.isActive(): + self._phase = 0.0 + self._timer.start() + elif not pulse: + self._timer.stop() + self.setToolTip(text) + self.update() + + def _tick(self) -> None: + self._phase = (self._phase + self._timer.interval() / self.PULSE_MS) % 1.0 + self.update() + + def _font(self) -> QFont: + font = QFont(self.font()) + font.setWeight(QFont.Weight.DemiBold) + return font + + def sizeHint(self) -> QSize: # noqa: N802 + fm = QFontMetrics(self._font()) + width = max(fm.horizontalAdvance(self.WIDEST), fm.horizontalAdvance(self.text)) + return QSize(round(self.PAD * 2.5 + self.DOT + width), max(26, fm.height() + 10)) + + def paintEvent(self, event: QPaintEvent) -> None: # noqa: N802 + c = theme.colors() + color = QColor(getattr(c, self.tone) if self.tone else c.muted) + p = QPainter(self) + p.setRenderHint(QPainter.RenderHint.Antialiasing) + pill = QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5) + radius = pill.height() / 2 + fill, edge = QColor(color), QColor(color) + fill.setAlphaF(0.10 if self.tone else 0.06) + edge.setAlphaF(0.35) + p.setPen(QPen(edge, 1)) + p.setBrush(fill) + p.drawRoundedRect(pill, radius, radius) + + center = QPointF(self.PAD + self.DOT / 2, pill.center().y()) + if self.tone: + # 0..1..0 once per pulse period; a steady medium glow when not pulsing. + breath = 0.5 - 0.5 * math.cos(2 * math.pi * self._phase) if self.pulse else 0.5 + glow_radius = self.DOT * (1.0 + 0.6 * breath) + glow = QRadialGradient(center, glow_radius) + inner = QColor(color) + inner.setAlphaF(0.25 + 0.35 * breath) + outer = QColor(color) + outer.setAlphaF(0.0) + glow.setColorAt(0.4, inner) + glow.setColorAt(1.0, outer) + p.setPen(Qt.PenStyle.NoPen) + p.setBrush(glow) + p.drawEllipse(center, glow_radius, glow_radius) + p.setPen(Qt.PenStyle.NoPen) + p.setBrush(color) + p.drawEllipse(center, self.DOT / 2, self.DOT / 2) + + p.setFont(self._font()) + p.setPen(color if self.tone else QColor(c.muted)) + text_left = self.PAD * 1.5 + self.DOT + p.drawText( + QRectF(text_left, 0, self.width() - text_left - self.PAD, self.height()), + Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, + self.text, + ) + + +class RoundHistory(QWidget): + """The outcome of the last rounds as dots, newest on the right.""" + + SIZE = 30 + DOT = 8 + GAP = 4 + + def __init__(self, parent: QWidget | None = None) -> None: + super().__init__(parent) + self.setMinimumHeight(self.DOT + 4) + self.setToolTip("Last rounds: green caught, orange missed, red no bobber") + self.outcomes: deque[str] = deque(maxlen=self.SIZE) + + def add(self, outcome: str) -> None: + """``outcome`` is ``caught``, ``missed`` or ``no_bobber``.""" + self.outcomes.append(outcome) + self.update() + + def paintEvent(self, event: QPaintEvent) -> None: # noqa: N802 + c = theme.colors() + colors = {"caught": c.success, "missed": c.warn, "no_bobber": c.danger} + p = QPainter(self) + p.setRenderHint(QPainter.RenderHint.Antialiasing) + p.setPen(Qt.PenStyle.NoPen) + y = (self.height() - self.DOT) / 2 + fits = max(0, (self.width() + self.GAP) // (self.DOT + self.GAP)) + shown = list(self.outcomes)[-fits:] if fits else [] + # Empty slots first, so the newest dot always sits at the right edge. + slots = [None] * (min(fits, self.SIZE) - len(shown)) + shown + x = self.width() - len(slots) * (self.DOT + self.GAP) + self.GAP + for outcome in slots: + p.setBrush(QColor(c.grid if outcome is None else colors[outcome])) + p.drawEllipse(QRectF(x, y, self.DOT, self.DOT)) + x += self.DOT + self.GAP + + +class BiteMeter(QWidget): + """Scrolling graph of the watched pixel's colour change against ``threshold_catch``. + + Click or drag vertically to move the threshold line. + """ + + threshold_dragged = Signal(int) + + HISTORY = 200 + """Samples kept on screen (20 s at the default poll interval).""" + + def __init__(self, parent: QWidget | None = None) -> None: + super().__init__(parent) + self.setMinimumHeight(110) + self.setCursor(Qt.CursorShape.SizeVerCursor) + self.setToolTip("Click or drag to set Threshold Catch") + self.samples: deque[int] = deque(maxlen=self.HISTORY) + self.threshold = 60 + self._frozen_max: float | None = None + + def add_sample(self, change: int) -> None: + self.samples.append(change) + self.update() + + def reset(self) -> None: + self.samples.clear() + self.update() + + def set_threshold(self, value: int) -> None: + self.threshold = value + self.update() + + @property + def peak(self) -> int: + return max(self.samples, default=0) + + def y_max(self) -> float: + if self._frozen_max is not None: + return self._frozen_max + return float(min(255, max(32, self.threshold * 1.5, self.peak * 1.2))) + + def _plot(self) -> QRectF: + return QRectF(self.rect()).adjusted(8, 24, -8, -6) + + def _value_at(self, y: float) -> int: + plot = self._plot() + frac = (plot.bottom() - y) / plot.height() + return max(0, min(255, round(frac * self.y_max()))) + + def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802 + if event.button() == Qt.MouseButton.LeftButton: + self._frozen_max = self.y_max() + self.threshold_dragged.emit(self._value_at(event.position().y())) + + def mouseMoveEvent(self, event: QMouseEvent) -> None: # noqa: N802 + if self._frozen_max is not None: + self.threshold_dragged.emit(self._value_at(event.position().y())) + + def mouseReleaseEvent(self, event: QMouseEvent) -> None: # noqa: N802 + self._frozen_max = None + self.update() + + def paintEvent(self, event: QPaintEvent) -> None: # noqa: N802 + c = theme.colors() + p = QPainter(self) + p.setRenderHint(QPainter.RenderHint.Antialiasing) + p.fillRect(self.rect(), QColor(c.sunken)) + plot = self._plot() + y_max = self.y_max() + + def y_of(value: float) -> float: + return plot.bottom() - min(value, y_max) / y_max * plot.height() + + p.setPen(QPen(QColor(c.grid), 1)) + for i in range(1, 4): + y = plot.top() + plot.height() * i / 4 + p.drawLine(QPointF(plot.left(), y), QPointF(plot.right(), y)) + + if self.samples: + step = plot.width() / (self.HISTORY - 1) + points = [QPointF(plot.left() + i * step, y_of(v)) for i, v in enumerate(self.samples)] + line = QPainterPath(points[0]) + for pt in points[1:]: + line.lineTo(pt) + area = QPainterPath(line) + area.lineTo(points[-1].x(), plot.bottom()) + area.lineTo(points[0].x(), plot.bottom()) + area.closeSubpath() + fill = QColor(c.accent) + fill.setAlpha(40) + p.fillPath(area, fill) + p.setPen(QPen(QColor(c.accent), 1.5)) + p.drawPath(line) + if self.samples[-1] > self.threshold: + p.setBrush(QColor(c.danger)) + p.setPen(Qt.PenStyle.NoPen) + p.drawEllipse(points[-1], 4.5, 4.5) + + ty = y_of(self.threshold) + p.setPen(QPen(QColor(c.warn), 1.5, Qt.PenStyle.DashLine)) + p.drawLine(QPointF(plot.left(), ty), QPointF(plot.right(), ty)) + + current = self.samples[-1] if self.samples else 0 + p.setPen(QColor(c.muted)) + p.drawText( + QRectF(10, 4, self.width() - 20, 20), + Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, + f"change {current} peak {self.peak}", + ) + p.setPen(QColor(c.warn)) + p.drawText( + QRectF(10, 4, self.width() - 20, 20), + Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter, + f"threshold {self.threshold}", + ) + + +class _LogSignal(QObject): + message = Signal(str) + + +class QtLogHandler(logging.Handler): + """Forwards log records to the GUI thread through :attr:`message`.""" + + def __init__(self) -> None: + super().__init__() + self._signal = _LogSignal() + self.message = self._signal.message + self.setFormatter(logging.Formatter("%(asctime)s %(message)s", "%H:%M:%S")) + + def emit(self, record: logging.LogRecord) -> None: + # RuntimeError: the receiving window was already deleted. + with contextlib.suppress(RuntimeError): + self._signal.message.emit(self.format(record)) diff --git a/src/getthefish/tally.py b/src/getthefish/tally.py new file mode 100644 index 0000000..b64c21a --- /dev/null +++ b/src/getthefish/tally.py @@ -0,0 +1,75 @@ +"""Catch statistics summed over sessions, and a per-day history on disk.""" + +from __future__ import annotations + +import json +import logging +from dataclasses import asdict, dataclass, fields +from datetime import date +from pathlib import Path + +logger = logging.getLogger(__name__) + +STATS_FILENAME = "stats.json" + + +@dataclass +class Tally: + casts: int = 0 + catches: int = 0 + misses: int = 0 + seconds: float = 0.0 + """Time spent fishing (not idle time between sessions).""" + + def add(self, other: Tally) -> None: + self.casts += other.casts + self.catches += other.catches + self.misses += other.misses + self.seconds += other.seconds + + @property + def catch_rate(self) -> float | None: + """Catches per cast in percent, None before the first cast.""" + return 100 * self.catches / self.casts if self.casts else None + + def per_hour(self, seconds: float | None = None) -> float | None: + """Catches per hour of fishing, None in the first minute (too jumpy to be useful).""" + seconds = self.seconds if seconds is None else seconds + return self.catches / seconds * 3600 if seconds >= 60 else None + + +class DailyHistory: + """One :class:`Tally` per calendar day, stored as JSON (``{"YYYY-MM-DD": {...}}``).""" + + def __init__(self, path: Path) -> None: + self.path = path + self.days: dict[str, Tally] = {} + try: + raw = json.loads(path.read_text(encoding="utf-8")) + names = {f.name for f in fields(Tally)} + self.days = { + day: Tally(**{k: v for k, v in values.items() if k in names}) + for day, values in raw.items() + } + except FileNotFoundError: + pass + except (OSError, ValueError, TypeError, AttributeError) as e: + logger.warning("Ignoring unreadable statistics file %s: %s", path, e) + + def today(self, day: date | None = None) -> Tally: + return self.days.setdefault((day or date.today()).isoformat(), Tally()) + + def total(self) -> Tally: + """All days added up.""" + total = Tally() + for tally in self.days.values(): + total.add(tally) + return total + + def save(self) -> None: + try: + self.path.parent.mkdir(parents=True, exist_ok=True) + data = {day: asdict(t) for day, t in sorted(self.days.items())} + self.path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8") + except OSError as e: + logger.warning("Could not save statistics to %s: %s", self.path, e) diff --git a/tests/test_bot.py b/tests/test_bot.py index 1816ddb..fbb9d93 100644 --- a/tests/test_bot.py +++ b/tests/test_bot.py @@ -5,7 +5,17 @@ import pytest -from getthefish.bot import BITE_WATCH_OFFSET, MAX_CONSECUTIVE_FAILURES, GetTheFish +from getthefish.bot import ( + BITE_WATCH_OFFSET, + MAX_CONSECUTIVE_FAILURES, + BiteSample, + BobberFound, + Event, + GetTheFish, + Phase, + PhaseChanged, + RoundFinished, +) from getthefish.config import FishConfig, Point from getthefish.detection import Image from getthefish.devices import AbortedError @@ -79,6 +89,43 @@ def test_fish_once_full_round(config: FishConfig) -> None: assert bot.stats.casts == 1 and bot.stats.catches == 1 +def test_events_are_emitted(config: FishConfig) -> None: + events: list[Event] = [] + screen = FakeScreen(lambda n: scene(bite=n >= 3)) + bot = GetTheFish(config, screen, FakeMouse(), NO_DELAY, on_event=events.append) + bot.fish_once() + found = next(e for e in events if isinstance(e, BobberFound)) + assert found.watch == Point(60 + BITE_WATCH_OFFSET.x, 40 + BITE_WATCH_OFFSET.y) + changes = [e.change for e in events if isinstance(e, BiteSample)] + assert changes[0] == 0 and changes[-1] > config.threshold_catch + + +def test_phases_are_emitted_in_order(config: FishConfig) -> None: + events: list[Event] = [] + screen = FakeScreen(lambda n: scene(bite=n >= 3)) + GetTheFish(config, screen, FakeMouse(), NO_DELAY, on_event=events.append).fish_once() + phases = [e.phase for e in events if isinstance(e, PhaseChanged)] + assert phases == [Phase.CASTING, Phase.SEARCHING, Phase.WAITING, Phase.REELING] + + +def test_stop_while_waiting_is_not_a_miss(config: FishConfig) -> None: + bot = make_bot(config, FakeScreen(scene())) + bot.on_event = lambda e: bot.stop() if isinstance(e, BiteSample) else None + assert bot.fish_once() is False + assert bot.stats.misses == 0 + + +def test_run_reports_each_round(config: FishConfig) -> None: + events: list[Event] = [] + bot = GetTheFish(config, FakeScreen(scene(bobber=False)), FakeMouse(), NO_DELAY) + bot.on_event = events.append + bot.run() + rounds = [e for e in events if isinstance(e, RoundFinished)] + assert len(rounds) == MAX_CONSECUTIVE_FAILURES + assert all(r.result is None for r in rounds) + assert [r.stats.casts for r in rounds] == [1, 2, 3] + + def test_bite_diagnostics_are_reported(config: FishConfig) -> None: config.verbose = True statuses: list[str] = [] diff --git a/tests/test_gui.py b/tests/test_gui.py index 3bb4b2d..f85d5b0 100644 --- a/tests/test_gui.py +++ b/tests/test_gui.py @@ -1,5 +1,6 @@ from __future__ import annotations +import logging from collections.abc import Callable from dataclasses import replace from pathlib import Path @@ -13,8 +14,17 @@ from PySide6.QtGui import QColor, QDesktopServices, QFontMetrics, QPixmap from pytestqt.qtbot import QtBot -from getthefish.bot import GetTheFish +from getthefish.bot import ( + BiteSample, + BobberFound, + GetTheFish, + Phase, + PhaseChanged, + RoundFinished, + Stats, +) from getthefish.config import FishConfig, Point +from getthefish.gui import theme from getthefish.gui.main_window import AreaSelector, ColorPicker, MainWindow from helpers import NO_DELAY, FakeMouse, FakeScreen, make_image @@ -188,3 +198,136 @@ def test_area_selector(qtbot: QtBot) -> None: qtbot.mouseRelease(selector, Qt.MouseButton.LeftButton, pos=QPoint(5, 3)) start, end = blocker.args assert start.x < end.x and start.y < end.y + + +def test_events_update_meter_and_stats(window: MainWindow) -> None: + window.handle_event(BobberFound(Point(300, 100), Point(303, 105))) + window.handle_event(BiteSample(12)) + window.handle_event(BiteSample(80)) + assert list(window.ui.biteMeter.samples) == [12, 80] + assert window.ui.biteMeter.peak == 80 + window.handle_event(RoundFinished(True, Stats(casts=4, catches=3, misses=1))) + assert window.ui.castsValue.text() == "4" + assert window.ui.catchesValue.text() == "3" + assert window.ui.rateValue.text() == "75%" + + +def test_meter_drag_sets_threshold_catch(window: MainWindow, qtbot: QtBot) -> None: + window.resize(1100, 700) + window.show() + qtbot.waitExposed(window) + meter = window.ui.biteMeter + qtbot.mouseClick(meter, Qt.MouseButton.LeftButton, pos=QPoint(50, meter.height() - 1)) + assert window.config.threshold_catch == 0 + assert meter.threshold == 0 + assert FishConfig.load(window.config_path).threshold_catch == 0 + + +def test_thresholds_stay_editable_while_fishing(qtbot: QtBot, tmp_path: Path) -> None: + w = MainWindow(FishConfig(), tmp_path / "config.json", idle_bot_factory) + qtbot.addWidget(w) + w.toggle_fishing() + assert w.worker is not None + assert w.ui.thresholdCatchSpinBox.isEnabled() + assert not w.ui.castKeyEdit.isEnabled() + assert w.ui.statusLed.text == "Casting" + with qtbot.waitSignal(w.worker.finished, timeout=5000): + pass + assert w.ui.statusLed.text == "Idle" + assert not w.ui.statusLed.pulse + + +def test_status_messages_reach_log_panel(window: MainWindow) -> None: + logging.getLogger("getthefish.bot").warning("hello log") + assert "hello log" in window.ui.logView.toPlainText() + + +def test_color_picker_loupe(qtbot: QtBot) -> None: + picker = ColorPicker(_solid_pixmap(QColor(10, 20, 30))) + qtbot.addWidget(picker) + picker.show() + qtbot.mouseMove(picker, QPoint(5, 5)) + assert picker.cursor_pos == QPoint(5, 5) + picker.grab() # paints the loupe + + +def test_compact_view_toggle_is_remembered(window: MainWindow, qtbot: QtBot) -> None: + window.ui.viewButton.click() + assert window.ui.pages.currentWidget() is window.ui.compactPage + window.close() + reopened = MainWindow(FishConfig(), window.config_path, idle_bot_factory) + qtbot.addWidget(reopened) + assert reopened.compact + reopened.ui.viewButton.click() + assert reopened.ui.pages.currentWidget() is reopened.ui.fullPage + + +def test_session_uses_compact_view(window: MainWindow, qtbot: QtBot) -> None: + window.toggle_fishing() + assert window.worker is not None + assert window.compact + assert window.ui.compactStartButton.text() == "Stop" + with qtbot.waitSignal(window.worker.finished, timeout=5000): + pass + assert not window.compact + assert window.ui.compactStartButton.text() == "Start" + + +def test_theme_toggle_is_remembered(window: MainWindow, qtbot: QtBot) -> None: + window.set_dark(True) + window.ui.themeButton.click() + assert not window.dark + assert theme.colors() is theme.LIGHT + window.close() + reopened = MainWindow(FishConfig(), window.config_path, idle_bot_factory) + qtbot.addWidget(reopened) + assert not reopened.dark + + +def test_start_refused_when_window_covers_fishing_area(window: MainWindow, qtbot: QtBot) -> None: + window.show() + qtbot.waitExposed(window) + window.config.start_pos, window.config.end_pos = Point(0, 0), Point(4000, 3000) + window.toggle_fishing() + assert window.worker is None + assert "covers the fishing area" in window.ui.statusbar.currentMessage() + + +def test_statistics_add_up_over_runs_and_restarts(window: MainWindow, qtbot: QtBot) -> None: + for _ in range(2): + window.toggle_fishing() + assert window.worker is not None + with qtbot.waitSignal(window.worker.finished, timeout=5000): + pass + # idle_bot_factory never finds the bobber: 3 casts per run, no catches. + assert window.ui.castsValue.text() == "6" + assert window.ui.todayCastsValue.text() == "6" + assert window.ui.totalCastsValue.text() == "6" + window.close() + + reopened = MainWindow(FishConfig(), window.config_path, idle_bot_factory) + qtbot.addWidget(reopened) + assert reopened.ui.castsValue.text() == "0" + assert reopened.ui.todayCastsValue.text() == "6" + assert reopened.ui.totalCastsValue.text() == "6" + assert reopened.ui.compactTodayCatches.text() == "0" + assert reopened.ui.compactSessionCatches.text() == "0" + + +def test_status_led_and_round_history(window: MainWindow) -> None: + window.handle_event(PhaseChanged(Phase.WAITING)) + assert window.ui.statusLed.text == "Waiting for bite" + assert window.ui.statusLed.tone == "accent" + assert window.ui.statusLed.pulse + window.ui.statusLed.grab() # paints the glow + window.handle_event(RoundFinished(True, Stats(casts=1, catches=1))) + assert window.ui.statusLed.text == "Caught" + assert not window.ui.statusLed.pulse + window.handle_event(RoundFinished(False, Stats(casts=2, catches=1, misses=1))) + window.handle_event(RoundFinished(None, Stats(casts=3, catches=1, misses=1))) + assert window.ui.statusLed.text == "No bobber" + assert window.ui.statusLed.tone == "danger" + window.handle_event(RoundFinished(False, Stats(casts=4, catches=1, misses=1))) # stopped + assert list(window.ui.roundHistory.outcomes) == ["caught", "missed", "no_bobber"] + assert list(window.ui.compactRoundHistory.outcomes) == ["caught", "missed", "no_bobber"] + window.ui.compactRoundHistory.grab() # paints the dots diff --git a/tests/test_icon.py b/tests/test_icon.py new file mode 100644 index 0000000..3904585 --- /dev/null +++ b/tests/test_icon.py @@ -0,0 +1,35 @@ +from __future__ import annotations + +import struct +from pathlib import Path + +import pytest + +pytest.importorskip("PySide6") +pytest.importorskip("pytestqt") + +from PySide6.QtGui import QColor +from pytestqt.qtbot import QtBot + +from getthefish.gui.icon import SIZES, app_icon, main, render + + +def test_render_draws_on_transparent_corners(qtbot: QtBot) -> None: + image = render(64) + assert image.pixelColor(0, 0).alpha() == 0 + assert image.pixelColor(25, 35) == QColor("white") # fish body + assert not app_icon().isNull() + + +def test_writes_multi_size_ico(qtbot: QtBot, tmp_path: Path) -> None: + out = tmp_path / "icons" / "app.ico" + assert main(["icon", str(out)]) == 0 + data = out.read_bytes() + reserved, kind, count = struct.unpack_from(" None: + assert main(["icon"]) == 2 diff --git a/tests/test_tally.py b/tests/test_tally.py new file mode 100644 index 0000000..5af4b71 --- /dev/null +++ b/tests/test_tally.py @@ -0,0 +1,34 @@ +from __future__ import annotations + +from datetime import date +from pathlib import Path + +from getthefish.tally import DailyHistory, Tally + + +def test_rates() -> None: + assert Tally().catch_rate is None + assert Tally().per_hour() is None + t = Tally(casts=4, catches=3, misses=1, seconds=1800) + assert t.catch_rate == 75 + assert t.per_hour() == 6 + assert t.per_hour(59) is None + + +def test_history_round_trip_and_total(tmp_path: Path) -> None: + path = tmp_path / "stats.json" + history = DailyHistory(path) + history.today(date(2026, 10, 24)).add(Tally(casts=5, catches=4, seconds=100)) + history.today(date(2026, 10, 25)).add(Tally(casts=2, catches=1, misses=1, seconds=50)) + history.save() + + reloaded = DailyHistory(path) + assert reloaded.today(date(2026, 10, 25)) == Tally(2, 1, 1, 50) + assert reloaded.total() == Tally(7, 5, 1, 150) + assert reloaded.today(date(2026, 10, 26)) == Tally() + + +def test_unreadable_history_starts_empty(tmp_path: Path) -> None: + path = tmp_path / "stats.json" + path.write_text("not json", encoding="utf-8") + assert DailyHistory(path).total() == Tally()