Skip to content
Edit this page

Weather overview architecture

This page is about how the overview is built: which modules exist, who depends on whom, and what happens from a finished refresh to a sentence on screen. For what the rules say, read docs/overview-rules.md (the source of truth). For a shorter introduction, see Weather overview.

Design in three decisions

  1. Rules are pure. A rule reads an OverviewContext built by hand or from models and returns an Insight or None. No GTK, no settings, no clock: "now", the time zone, the units and the wording seed are all in the context. That is why the whole decision logic is unit-tested without a display.
  2. Deciding is separate from saying. RuleBook finds what is true. decide() chooses what to open and when. The engine only supplies timing. The window and the notifications only deliver.
  3. Publish / subscribe. The engine emits one signal, overview-changed. It does not know who listens.

Modules and dependencies

flowchart TB
    subgraph core["core/overview (no GTK, no settings)"]
        direction TB
        CTX[context.py<br>OverviewContext, Clock, Units,<br>HourlySeries, Window, …]
        HT[hour_tests.py<br>HourTest, HasCode, AtLeast, …]
        RUL[rules.py<br>Rule, FirstHourRule, RuleBook,<br>combine]
        INS[insight.py<br>Insight, LEVELS]
        MSG[messages.py<br>MessageBook, wordings]
        ANN[announce.py<br>AnnounceMemory, decide,<br>should_notify]
    end
    CFG[config.py<br>OVERVIEW_* numbers]
    ENG[state/overview_engine.py<br>OverviewEngine]
    STORE[state/weather_store.py]
    SET[services/settings.py]
    PILL[ui/sections/current.py<br>the pill]
    APP[app.py<br>_announce]
    NOTI[ui/notifications.py]

    RUL --> CTX & HT & INS
    CTX --> MSG
    HT --> CTX
    ANN --> INS
    core --> CFG
    ENG --> core
    ENG --> STORE
    ENG --> SET
    PILL --> ENG
    APP --> ENG
    APP --> ANN
    APP --> NOTI

The usual layer rule applies: core/overview/ imports only config.py and other core/ code, state/overview_engine.py imports core/, services/ and the store, and ui/ and app.py import the engine. app.py also imports should_notify from core/overview/announce.py.

The data model

classDiagram
    class OverviewContext {
        Clock clock
        Units units
        HourlySeries hourly
        SunTimes sun
        DailyOutlook daily
        AirSeries air
        MessageBook messages
        Window window
        from_models()
        first(test)
    }
    class Clock { now, tz, use_24h; time(); approx_time() }
    class Units { imperial; celsius(); kmh() }
    class HourlySeries { times, codes, temperature, precip_probability, windspeed, ...; value(); hour_near() }
    class Window { hours, is_day, heading; first(); is_now() }
    class MessageBook { seed; say(); say_count() }
    class Rule { <<abstract>> kind, level, topic, icon; evaluate(ctx) }
    class FirstHourRule { HourTest test; Phrasing phrasing }
    class HourTest { <<abstract>> }
    class Phrasing { now key; later key; icon; render() }
    class Insight { kind, message, level, topic, key, about, when, valid_until, parts, topics, covers; fingerprint }
    class RuleBook { rules; default(); run(ctx) }

    OverviewContext *-- Clock
    OverviewContext *-- Units
    OverviewContext *-- HourlySeries
    OverviewContext *-- Window
    OverviewContext *-- MessageBook
    Rule <|-- FirstHourRule
    FirstHourRule o-- HourTest
    FirstHourRule o-- Phrasing
    RuleBook o-- Rule
    Rule ..> Insight : returns
    Rule ..> OverviewContext : reads
  • OverviewContext.from_models(hourly, daily, air, now, tz, imperial, use_24h, seed) is the only place the real models are read. It copies the data into small dataclasses in the user's units; thresholds in config.py are metric, so rules convert through Units (ctx.units.celsius(v), ctx.units.kmh(v)). Daily and air data may be missing; a missing series is an empty list.
  • Window is the part of the forecast the rules look at: by day, now until sunset (at least OVERVIEW_DAY_MIN_HOURS ahead); at night, now until the next sunrise; with no sunrise or sunset, the next OVERVIEW_HOURS. Its heading is "Today" or "Tonight".
  • Insight is what the engine and everything after it handles. fingerprint (kind, message key, level, the hour it is about) says whether it is the same as before: it changes when the forecast does, not as time passes. A merged insight carries parts (each thing it says), topics (what its sentence names) and covers (what it makes redundant).
  • Time is injected. Clock.approx_time() rounds predicted times more the further ahead they are (OVERVIEW_ROUNDING), and messages always hedge them ("around 5:00 PM"). Only sunrise and sunset use the exact time().
  • Wordings come from MessageBook. The choice depends only on the seed and the key (random.Random(f"{seed}:{key}")), so the same seed always gives the same text.

Building a rule

flowchart LR
    HT[HourTest<br>which hour?] --> FH[FirstHourRule]
    PH[Phrasing<br>now key + later key] --> FH
    FH --> RULE[Rule in RuleBook.default]

FirstHourRule("freezing", HasCode(FREEZING_CODES), Phrasing("freezing.now", "freezing.later", ICON_RAIN), level="high", topic="freezing") is a whole rule: it finds the first hour of the window that passes the test and renders the "now" or "later" message. Tests combine with AnyOf / AllOf; AtLeast and Below compare a series to a threshold. Shared ones (IS_WET, IS_DRY, IS_FOGGY, IS_WINDY, IS_VERY_WINDY, IS_SNOW) live in hour_tests.py. Rules that need more than "the first hour that…" (StormRule, PrecipitationRule, SunRule, TomorrowRule, …) subclass Rule directly.

One run

OverviewEngine._insights() builds a context and calls RuleBook.default().run(ctx):

flowchart TB
    A[each Rule.evaluate ctx] -->|Insight or None, errors skipped| B[drop valid_until <= now]
    B --> C[sort by priority]
    C --> D[combine]
    D --> E1[1 TURNING_STORMY<br>rain then storm, same wet spell]
    E1 --> E2[2 FOLDS<br>a storm already says rain]
    E2 --> E3[3 TURNING_HEAVY<br>rain then heavy rain, same spell]
    E3 --> E4[4 COMBINATIONS<br>known pair, now or within OVERVIEW_COMBINE_MINUTES]
    E4 --> F[list of Insight, most important first]

Two safety nets: a rule that raises is logged (debug only) and skipped, and if combine() raises, the uncombined insights are returned. If building the context fails, the engine publishes no overview that time.

Deciding: decide()

decide(insights, memory, showing, now) in core/overview/announce.py is a pure function over AnnounceMemory.

flowchart TB
    S[note_seen: refresh 'last true' of every insight,<br>forget ones unseen for OVERVIEW_FORGET_MINUTES] --> P[pending = insights without calm<br>calm only if nothing else]
    P --> R[ready = pending that are due<br>news: always due · reminder: when its time has come]
    R --> G{gap over?<br>OVERVIEW_MIN_GAP_MINUTES since last opening}
    G -- yes --> O[can_open = ready]
    G -- no --> X[can_open = ready that skips the gap<br>new extreme news]
    O & X --> Q{can_open empty?}
    Q -- no --> OPEN[choose: news first, then level, then priority<br>note_said · reason = news or reminder<br>the others wait their turn]
    Q -- yes --> SIL[silent update: keep the insight on screen,<br>else the most important · reason = None]
    OPEN & SIL --> D[Decision: insight, reason, wake_at, topics, waiting]

AnnounceMemory keeps, per fingerprint part, when it was last said, how often, and when it was last true. That is what makes reminders back off (OVERVIEW_REMIND_MINUTES by level, times OVERVIEW_REMIND_BACKOFF each time, capped at OVERVIEW_REMIND_MAX_MINUTES) and why a storm that comes and goes counts once. Low and calm have no reminder time, so they are said once.

wake_at is the next moment something changes: an insight stops being true, a reminder is due, or a waiting insight's gap ends. It is at least one second away.

should_notify(reason, insight) is the second, separate question: news of medium level or above (or on OVERVIEW_NOTIFY_TOPICS, i.e. tomorrow) and reminders of extreme insights may be sent as notifications; a silent update never is.

The engine lifecycle

stateDiagram-v2
    [*] --> Disabled
    Disabled --> Waiting: show-overview or show-notifications on
    Waiting --> Scheduled: store is-ready (new hourly data)
    Scheduled --> Running: one-shot timer fires
    Running --> Scheduled: decision has wake_at
    Running --> Waiting: no wake_at, wait for next refresh
    Scheduled --> Waiting: store reloads (timer cancelled, memory kept)
    Waiting --> Reset: another city
    Scheduled --> Reset: another city
    Reset --> Waiting
    Waiting --> Disabled: both settings off
    Scheduled --> Disabled: both settings off
  • Triggers. weather_store notify::is-ready, and the show-overview / show-notifications settings.
  • Timing. The first run is OVERVIEW_FIRST_DELAY seconds after the first data load (start-up stays fast), later runs OVERVIEW_REFRESH_DELAY after each refresh, and further runs at wake_at. Only one-shot GLib.timeout_add_seconds timers, one at a time. A run is scheduled once per hourly dataset (_scheduled_for), so turning a setting on again doesn't move one that is already scheduled.
  • A refresh doesn't count. While the store reloads, the engine cancels its timer but keeps _memory and the insight on screen (until it stops being true). A refresh, auto-refresh or units change never opens the overview or resets reminders.
  • Reset (_reset) happens on another city or when both settings go off: timer cancelled, memory forgotten, overview-changed emitted with no insight.
  • Opening draws a new wording seed. When decide() returns a reason, the engine draws random.getrandbits(32) and runs the rules a second time (log_steps=False) so the opened insight is phrased with the fresh seed. Silent updates keep the seed, so text never changes under the reader.
  • Publishing. _set() emits overview-changed(announce) only when something changed or it opens. announce is True when it opens (reason is set) and False for a text update.

Public surface for subscribers: current() (the insight, or None once it is no longer true), heading, reason, topics, enabled(), and note_shown() (the user opened the pill, which counts as saying it).

Delivery: window or notification

flowchart TB
    SIG[overview-changed] --> APP[WeatherApplication._on_overview_changed]
    APP --> WG[notifications.withdraw_gone<br>engine.topics]
    APP --> AN{announce and insight?}
    AN -- no --> END[done]
    AN -- yes --> VIS{is_on_screen<br>main window?}
    VIS -- yes --> ON{show-overview on?}
    ON -- yes --> WIN[window: the pill opens]
    ON -- no --> NO1[nowhere]
    VIS -- no --> NT{show-notifications on?}
    NT -- no --> NO2[nowhere]
    NT -- yes --> SN{should_notify?}
    SN -- yes --> SEND[OverviewNotifications.send<br>id overview-topic]
    SN -- no --> NO3[nowhere]

The pill (CurrentCondition) is an independent subscriber: on map it connects to overview-changed and changed::show-overview, and on unmap it disconnects. It reads current() and heading, colours the heading by level and keeps the message open for insight.show_seconds.

OverviewNotifications keeps {notification id: topics}. It sends one notification per topic (overview-<topic>, with the city as the title and the sentence as the body), withdraws the ones an incoming insight covers, and withdraws anything whose topic is no longer true, when the location changes, when notifications are turned off, and when the main window comes into view.

The app logs the choice in debug mode: Overview channel: storm (news, extreme) -> notification overview-storm.

Where to change what

I want to… Change Also
tune a number config.py ("Overview", "Overview rules") docs/overview-rules.md
reword a message core/overview/messages.py same placeholders in every wording; run ./update-pot
add a rule for "the first hour that…" a FirstHourRule in RuleBook.default(), an HourTest if needed message keys, a priority in OVERVIEW_PRIORITIES, the rules doc, a test case
add a rule that needs more a Rule subclass in rules.py same as above
merge two messages into one sentence an entry in COMBINATIONS, FOLDS, TURNING_STORMY or TURNING_HEAVY, plus its own message key never join translated pieces
change when it opens or reminds core/overview/announce.py, OVERVIEW_REMIND_*, OVERVIEW_MIN_GAP_MINUTES rules doc section 6
change what gets notified should_notify, OVERVIEW_NOTIFY_TOPICS rules doc section 7
change the pill ui/sections/current.py

Invariants

  • An insight is never shown after its valid_until.
  • One bad rule never breaks the overview.
  • A refresh never opens the pill or resets reminders.
  • Only one-shot timers; with both settings off nothing is scheduled or computed.
  • The overview is announced in one place at a time (the window or a notification, never both).
  • There is no other notification: don't add one per refresh.
  • Nothing in core/overview/ imports GTK or reads settings.

Tests

tests/test_overview_rules.py builds an OverviewContext by hand with a fixed Clock and calls RuleBook.default().run(ctx). decide() and AnnounceMemory are tested the same way, and tests/test_notifications.py covers OverviewNotifications with a fake app.