commit 3a68e40ada1c9c71acf39bd65e36ac80f96701ff Author: Mike Eberlein Date: Sun May 10 21:18:21 2026 -0400 Working Golf Score diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e5f35ea --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +build/ +.lock-waf_linux_build diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..06b303d --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Mike Eberlein + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/SPEC.md b/SPEC.md new file mode 100644 index 0000000..8205b6d --- /dev/null +++ b/SPEC.md @@ -0,0 +1,311 @@ +# Golf Score — Application Specification + +**Platform:** Pebble Time 2 (Emery, 200×228 px, color) +**Source:** `src/c/golf_score.c` +**Build output:** `build/golf_score.pbw` + +--- + +## 1. Purpose + +A single-file Pebble watchapp for tracking golf strokes and putts across an 18-hole round. The design prioritises one-handed glanceability and minimal button presses during play, with correction and navigation features accessible via long presses. + +--- + +## 2. Data Model + +### Core types + +```c +typedef struct { + int8_t strokes; // total shots on this hole, range [0, 99] + int8_t putts; // putts on this hole, range [0, strokes] +} HoleScore; + +static HoleScore s_scores[MAX_HOLES]; // MAX_HOLES = 18 +static int s_current_hole = 0; // index into s_scores, range [0, 17] +``` + +`int8_t` is used for both fields because: +- The practical maximum (99) fits in a signed byte. +- `sizeof(HoleScore)` = 2 bytes, so `sizeof(s_scores)` = 36 bytes — small enough that the entire array is written atomically as a single `persist_write_data` blob (no partial-update complexity). + +### Invariant + +`putts <= strokes` at all times. Every mutation point enforces this: + +| Operation | Enforcement | +|-----------|-------------| +| DOWN (−1 stroke) | If `putts > strokes` after decrement, `putts = strokes` | +| UP long (+1 putt) | If `putts` would exceed `strokes`, `strokes` is raised to match | +| DOWN long (−1 putt) | Putts floored at 0; strokes unchanged | + +The invariant was chosen to reflect real golf (putts are a subset of strokes), while keeping the enforcement logic local to each handler rather than centralised — each handler knows exactly which field it owns. + +### Why putts are tracked separately from strokes + +Many apps conflate them. Keeping a separate putt count per hole lets the player review putting performance on the scorecard (total putts is a standard handicap metric) without requiring a separate mode. The trade-off is a slightly more complex button map (long-press for putts), which is acceptable because putts happen far less frequently than stroke taps during a hole. + +--- + +## 3. Persistence + +```c +#define PERSIST_KEY_SCORES 0 +#define PERSIST_KEY_HOLE 1 +``` + +| Key | API | Written | +|-----|-----|---------| +| 0 | `persist_write_data` / `persist_read_data` | Entire `s_scores[18]` blob (36 bytes) | +| 1 | `persist_write_int` / `persist_read_int` | `s_current_hole` | + +**Write points:** after every hole advance (SELECT), after jump-to-hole, after reset, and in `main()` after `app_event_loop()` returns (app exit). Stroke/putt increments during a hole are **not** written immediately to avoid flash wear from rapid taps. + +**Read point:** once, at the top of `main()` before the window is pushed, so the first render already has the restored state. + +**Design decision — no per-keypress save:** Pebble's persistent storage is flash-backed and has a finite write endurance. Saving on every UP/DOWN tap would burn through write cycles quickly during an 18-hole round. Losing a single stroke on a crash is an acceptable trade-off; losing an entire hole's worth of scores after a hole advance (which does save) is not. + +**Design decision — blob vs. individual keys:** Writing the whole array as one blob is simpler than 18×2 individual keys and means the scores are always consistent (either the whole round is there or none of it is). It also fits comfortably within the 256-byte per-value maximum (`sizeof(s_scores)` = 36 bytes). + +--- + +## 4. Window Architecture + +### Window stack hierarchy + +``` +[main_window] ← always at the bottom; never popped by the app + └─ [settings_window] ← pushed by long SELECT on main + ├─ [scorecard_window] ← pushed by "View Scorecard" + ├─ [hole_picker_window] ← pushed by "Jump to Hole" + └─ [help_window] ← pushed by "Controls" +``` + +`main_window` is the only window created at startup and never destroyed during normal operation. All other windows are created on demand and destroy themselves in their `unload` handler (see §4.2). + +### 4.1 Window lifecycle pattern + +Every secondary window follows the same pattern: + +```c +// Push (caller): +s_foo_window = window_create(); +window_set_window_handlers(s_foo_window, (WindowHandlers){ + .load = foo_window_load, + .unload = foo_window_unload, +}); +window_stack_push(s_foo_window, true); + +// Unload (self-cleanup): +static void foo_window_unload(Window *window) { + // destroy child layers first + window_destroy(s_foo_window); + s_foo_window = NULL; +} +``` + +Setting the pointer to `NULL` after `window_destroy` prevents dangling pointer use and makes it safe to check `if (s_foo_window)` elsewhere. + +**Why self-destroy in unload?** The Pebble OS calls `unload` before the window is fully removed from the stack, giving the app a guaranteed cleanup point regardless of whether the window was popped by BACK, by `window_stack_pop`, or by `window_stack_remove`. Centralising cleanup in `unload` means no caller needs to remember to free anything. + +### 4.2 Return-to-main after settings actions + +After "Jump to Hole" or "Reset Round" complete, the app needs to pop multiple windows (hole picker + settings, or just settings) and return to main. This cannot be done synchronously inside a `SimpleMenuLayer` select callback because the callback fires while the layer's own event processing is still on the call stack — destroying the window mid-callback would corrupt the stack frame. + +**Solution: 50 ms deferred timer** + +```c +static void return_to_main_cb(void *data) { + s_return_timer = NULL; + Window *top; + while ((top = window_stack_get_top_window()) != NULL && top != s_main_window) { + window_stack_pop(false); + } + layer_mark_dirty(s_canvas_layer); +} + +static void schedule_return_to_main(void) { + if (s_return_timer) app_timer_cancel(s_return_timer); + s_return_timer = app_timer_register(50, return_to_main_cb, NULL); +} +``` + +The 50 ms delay ensures the select callback has returned and the event loop has fully processed before any window is destroyed. The while loop pops whatever is above main without needing to know the exact stack depth, which makes it robust to future navigation changes. + +Cancelling any existing timer before registering a new one prevents double-pops if an action is somehow triggered twice. + +--- + +## 5. Main Window — Visual Layout + +Screen: 200 × 228 px (no system status bar; app owns full screen). + +``` +y 0–43 GColorJaegerGreen fill (header) + "HOLE N / 18" GOTHIC_18_BOLD white centered (y=12, h=22) +y 44–49 gap +y 50–71 "STROKES" GOTHIC_18_BOLD dark-gray centered +y 70–127 stroke count BITHAM_42_BOLD black centered +y 133 divider line GColorLightGray x=[20, w-20] +y 139–160 "PUTTS" GOTHIC_18_BOLD dark-gray centered +y 158–215 putt count BITHAM_42_BOLD GColorCobaltBlue centered +y 216–227 hint bar GColorLightGray fill + hint text GOTHIC_14 dark-gray trailing-ellipsis centered +``` + +**Design decisions:** + +- **Custom Layer instead of TextLayers:** The main screen is drawn by a single `LayerUpdateProc` (`canvas_update_proc`) rather than a collection of TextLayers. This avoids the overhead of multiple layer objects, keeps all layout constants in one place, and gives full control over drawing order (background → header fill → text, all in one pass). + +- **BITHAM_42_BOLD for counts:** The largest readable number font available as a system font. At 42 pt the count is legible at a glance without raising the watch, which is the primary use case (hand on club, quick look). + +- **Strokes black, putts cobalt blue:** Colour-coding the two counters avoids misreading at a glance. Blue was chosen for putts as it is visually subordinate to black, reflecting that putts are a subset metric. + +- **Hint bar at bottom:** The 12 px hint bar is small enough to not compete with the counts but visible enough to remind new users about the long-press bindings. `GTextOverflowModeTrailingEllipsis` ensures it never wraps. + +- **No status bar:** `StatusBarLayer` would consume 20 px and show a clock the player already has on the watch face. Reclaiming that space for larger number fonts was the right trade-off for a glance-use app. + +--- + +## 6. Button Map + +### Main window + +| Button | Type | Action | Vibration | +|--------|------|--------|-----------| +| UP | Short | `strokes++` (max 99) | Short pulse | +| DOWN | Short | `strokes--` (floor 0); auto-clamp `putts` | None | +| SELECT | Short | Advance to next hole; save | Short pulse (double on hole 18) | +| UP | Long 700 ms | `putts++`; auto-raise `strokes` if needed | None | +| DOWN | Long 700 ms | `putts--` (floor 0) | None | +| SELECT | Long 700 ms | Push settings window | None | + +**Why no vibration on DOWN?** A correction is often a recovery from a mis-tap. Adding a vibe would feel punishing and draw attention on the course. The asymmetry (vibe on increment, silent on decrement) also gives tactile confirmation that a stroke was successfully counted without looking. + +**Why 700 ms long-press threshold?** The Pebble default is 500 ms. 700 ms was chosen to reduce accidental long-press triggers during normal play — a player tapping UP repeatedly at pace will not accidentally trigger the putt increment. + +**Why long SELECT for settings rather than BACK?** The BACK button's system behaviour (pop window / exit app) cannot be reliably overridden for long press. Using SELECT long-press is the standard Pebble pattern for secondary actions. + +### Settings window + +Handled by `SimpleMenuLayer`, which wires UP/DOWN to scroll and SELECT to activate. BACK pops the window via system default. + +### Scorecard and Help windows + +`ScrollLayer` wires UP/DOWN to scroll. BACK pops via system default. + +### Hole picker window + +`SimpleMenuLayer` as above. Selecting a row calls `hole_picker_select_cb`, which sets `s_current_hole`, saves, and schedules the return-to-main timer. + +--- + +## 7. Settings Window + +Implemented as a `SimpleMenuLayer` with one section and four items: + +| Index | Title | Subtitle | Effect | +|-------|-------|----------|--------| +| 0 | View Scorecard | — | Push scorecard window | +| 1 | Jump to Hole | Go back to any hole | Push hole picker window | +| 2 | Reset Round | Clears all scores | Zero all scores, reset to hole 1, save, double vibe, return to main | +| 3 | Controls | Button cheatsheet | Push help window | + +`SimpleMenuSection` and `SimpleMenuItem` arrays are `static` module-level variables. `SimpleMenuLayer` does not deep-copy the arrays — if they were stack-allocated in `settings_window_load` they would be freed before the layer uses them. Static allocation is the correct pattern here. + +Items are initialised in `settings_window_load` rather than at file scope because `SimpleMenuItem.callback` is a function pointer that cannot be a compile-time constant in C89/C90 (though it can in C99). Initialising in load keeps the code compatible across SDK versions. + +--- + +## 8. Hole Picker Window + +`SimpleMenuLayer` with one section of 18 rows, pre-scrolled to `s_current_hole`. + +Row content is built in `hole_picker_window_load`: + +``` +Title: "> Hole N" (current hole) + " Hole N" (all others) +Subtitle: "X str / Y ptt" (if played: strokes > 0 OR putts > 0) + "not played" (otherwise) +``` + +**Why `> ` prefix instead of a colour or bold?** `SimpleMenuLayer` does not expose per-row styling. A text prefix is the only reliable way to mark the current hole within the system widget. Two leading spaces on non-current rows maintain visual alignment. + +**Why rebuild titles/subtitles in `window_load` rather than keeping them live?** The data only needs to be accurate when the window opens. Keeping 18×(16+24) = 720 bytes of string buffers permanently resident but only occasionally accurate is wasteful. Building on load is cheap (one pass over 18 `HoleScore` structs) and guarantees the picker reflects current scores even if the user edits a hole and reopens settings. + +Title/subtitle buffers are `static` for the same reason as settings items — `SimpleMenuLayer` holds pointers into them. + +--- + +## 9. Scorecard Window + +A `ScrollLayer` containing a single `TextLayer`. Content is built by `build_scorecard()` into `s_scorecard_buf[700]`. + +**Buffer sizing:** 18 rows × ~18 chars + header (30 chars) + footer (20 chars) + current-hole marker (2 chars × 1 row) ≈ 370 chars. 700 bytes gives comfortable headroom. + +The current hole is marked with a trailing ` <` on its row so the player can orient themselves without counting. + +The content height for the `ScrollLayer` is measured with `graphics_text_layout_get_content_size` at load time using the same font and bounding width as the `TextLayer`. This keeps the scroll range exactly tight to the rendered text — no arbitrary magic number for content height. + +The scorecard is **read-only**. Reset was moved to the Settings menu to enforce a clear separation: viewing data is non-destructive and accessible, mutating data requires an explicit settings action. + +--- + +## 10. Help Window + +A `ScrollLayer` + `TextLayer` displaying `HELP_TEXT`, a `static const char *const` string literal compiled into flash. No heap allocation is needed for the string itself — `text_layer_set_text` holds a pointer to the literal directly. + +The pattern is identical to the scorecard window but simpler: no `build_*` function, no dynamic buffer, no current-state dependency. + +--- + +## 11. Static Variable Strategy + +All window pointers, layer pointers, and string buffers are file-scope `static`. This is the idiomatic Pebble C pattern for several reasons: + +1. **Pebble heap is small.** Stack frames are limited; large char arrays on the stack risk overflow. +2. **Layer pointers must outlive the function that creates them.** `window_load` builds the UI, but the layers live until `window_unload`. File-scope statics have the right lifetime automatically. +3. **`SimpleMenuLayer` does not copy its data.** Section and item arrays must remain valid for the lifetime of the layer — static storage guarantees this. + +The downside is that only one instance of each secondary window can exist at a time, which is enforced by the navigation structure (settings is modal; its children are modal within it). + +--- + +## 12. Source File Organisation + +Functions are ordered bottom-up by dependency so that no forward declarations are needed: + +``` +1. Persistence (save_scores, load_scores) +2. Main canvas draw (canvas_update_proc) +3. Main window button handlers +4. Scorecard window (build_scorecard, load, unload) +5. Return-to-main timer (return_to_main_cb, schedule_return_to_main) +6. Hole picker window (select_cb, load, unload) +7. Settings callbacks (scorecard_cb, jump_cb, help_cb, reset_cb) + — defined after the windows they push +8. Settings window (load, unload, show_settings) +9. Main window click config and lifecycle +10. main() +``` + +This ordering means that every called function is defined before its caller, eliminating the need for a header file or forward declarations. + +--- + +## 13. Memory Footprint (Emery) + +| Region | Size | +|--------|------| +| `s_scores` | 36 bytes | +| String buffers (hole_buf, stroke_buf, putt_buf) | 40 bytes | +| `s_scorecard_buf` | 700 bytes | +| `s_hole_titles` | 288 bytes (18 × 16) | +| `s_hole_subtitles` | 432 bytes (18 × 24) | +| `HELP_TEXT` | ~380 bytes (flash, not RAM) | +| Total static RAM (approximate) | ~1.5 KB | +| SDK-reported free heap | 127 KB | + +The app is extremely light on memory. The largest single allocation is `s_scorecard_buf` at 700 bytes. All secondary window layers are allocated in their `load` handlers and freed in `unload`, so only one secondary window's layer objects are in heap at any time. diff --git a/package.json b/package.json new file mode 100644 index 0000000..7f797c0 --- /dev/null +++ b/package.json @@ -0,0 +1,42 @@ +{ + "name": "golf_score", + "author": "Mike Eberlein", + "version": "1.0.0", + "description": "Track golf strokes and putts across an 18-hole round.", + "keywords": ["pebble-app", "golf", "sports"], + "dependencies": {}, + "pebble": { + "displayName": "Golf Score", + "uuid": "73037cc5-ba10-41ed-b93f-f55a102774a9", + "sdkVersion": "3", + "enableMultiJS": true, + "targetPlatforms": [ + "basalt", + "chalk", + "diorite", + "emery", + "flint", + "gabbro" + ], + "watchapp": { + "watchface": false + }, + "resources": { + "media": [ + { + "type": "png", + "menuIcon": true, + "name": "APP_ICON_SMALL", + "file": "images/app_icon_small.png", + "targetPlatforms": ["basalt", "chalk", "diorite", "emery", "flint", "gabbro"] + }, + { + "type": "png", + "name": "APP_ICON_LARGE", + "file": "images/app_icon_large.png", + "targetPlatforms": ["basalt", "chalk", "diorite", "emery", "flint", "gabbro"] + } + ] + } + } +} diff --git a/resources/images/app_icon_large.png b/resources/images/app_icon_large.png new file mode 100644 index 0000000..27cae27 Binary files /dev/null and b/resources/images/app_icon_large.png differ diff --git a/resources/images/app_icon_small.png b/resources/images/app_icon_small.png new file mode 100644 index 0000000..269ce0e Binary files /dev/null and b/resources/images/app_icon_small.png differ diff --git a/src/c/golf_score.c b/src/c/golf_score.c new file mode 100644 index 0000000..34cb06a --- /dev/null +++ b/src/c/golf_score.c @@ -0,0 +1,517 @@ +#include + +#define MAX_HOLES 18 +#define PERSIST_KEY_SCORES 0 +#define PERSIST_KEY_HOLE 1 + +typedef struct { + int8_t strokes; + int8_t putts; +} HoleScore; + +// --------------------------------------------------------------------------- +// State +// --------------------------------------------------------------------------- +static HoleScore s_scores[MAX_HOLES]; +static int s_current_hole = 0; + +// --------------------------------------------------------------------------- +// Main window +// --------------------------------------------------------------------------- +static Window *s_main_window; +static Layer *s_canvas_layer; + +static char s_hole_buf[24]; +static char s_stroke_buf[8]; +static char s_putt_buf[8]; + +// --------------------------------------------------------------------------- +// Scorecard window +// --------------------------------------------------------------------------- +static Window *s_scorecard_window; +static ScrollLayer *s_scroll_layer; +static TextLayer *s_scorecard_layer; +static char s_scorecard_buf[700]; + +// --------------------------------------------------------------------------- +// Settings window +// --------------------------------------------------------------------------- +static Window *s_settings_window; +static SimpleMenuLayer *s_settings_menu_layer; +static SimpleMenuSection s_settings_section; +static SimpleMenuItem s_settings_items[4]; + +// --------------------------------------------------------------------------- +// Hole picker window +// --------------------------------------------------------------------------- +static Window *s_hole_picker_window; +static SimpleMenuLayer *s_hole_picker_layer; +static SimpleMenuSection s_hole_section; +static SimpleMenuItem s_hole_items[MAX_HOLES]; +static char s_hole_titles[MAX_HOLES][16]; +static char s_hole_subtitles[MAX_HOLES][24]; + +// --------------------------------------------------------------------------- +// Help / cheatsheet window +// --------------------------------------------------------------------------- +static Window *s_help_window; +static ScrollLayer *s_help_scroll_layer; +static TextLayer *s_help_text_layer; + +static const char *const HELP_TEXT = + "BUTTON GUIDE\n" + "\n" + "UP +1 stroke\n" + "DOWN -1 stroke\n" + "CENTER Next hole\n" + "\n" + "Hold UP +1 putt\n" + "Hold DN -1 putt\n" + "Hold CTR Settings\n" + "\n" + "SETTINGS MENU\n" + "\n" + "View Scorecard\n" + " All 18 holes\n" + "\n" + "Jump to Hole\n" + " Return to any\n" + " previous hole\n" + "\n" + "Reset Round\n" + " Clear all scores\n" + "\n" + "Controls\n" + " This screen"; + +static void help_window_load(Window *window) { + Layer *root = window_get_root_layer(window); + GRect bounds = layer_get_bounds(root); + + GFont font = fonts_get_system_font(FONT_KEY_GOTHIC_18_BOLD); + GSize text_size = graphics_text_layout_get_content_size( + HELP_TEXT, font, + GRect(0, 0, bounds.size.w - 8, 3000), + GTextOverflowModeWordWrap, GTextAlignmentLeft); + int content_h = text_size.h + 20; + + s_help_scroll_layer = scroll_layer_create(bounds); + scroll_layer_set_content_size(s_help_scroll_layer, GSize(bounds.size.w, content_h)); + scroll_layer_set_click_config_onto_window(s_help_scroll_layer, window); + layer_add_child(root, scroll_layer_get_layer(s_help_scroll_layer)); + + s_help_text_layer = text_layer_create(GRect(4, 4, bounds.size.w - 8, content_h)); + text_layer_set_text(s_help_text_layer, HELP_TEXT); + text_layer_set_font(s_help_text_layer, font); + text_layer_set_overflow_mode(s_help_text_layer, GTextOverflowModeWordWrap); + text_layer_set_background_color(s_help_text_layer, GColorClear); + scroll_layer_add_child(s_help_scroll_layer, text_layer_get_layer(s_help_text_layer)); +} + +static void help_window_unload(Window *window) { + text_layer_destroy(s_help_text_layer); + scroll_layer_destroy(s_help_scroll_layer); + window_destroy(s_help_window); + s_help_window = NULL; +} + +// Timer used to pop back to main after a settings action completes +static AppTimer *s_return_timer = NULL; + +// --------------------------------------------------------------------------- +// Persistence +// --------------------------------------------------------------------------- +static void save_scores(void) { + persist_write_data(PERSIST_KEY_SCORES, s_scores, sizeof(s_scores)); + persist_write_int(PERSIST_KEY_HOLE, s_current_hole); +} + +static void load_scores(void) { + if (persist_exists(PERSIST_KEY_SCORES)) { + persist_read_data(PERSIST_KEY_SCORES, s_scores, sizeof(s_scores)); + } + if (persist_exists(PERSIST_KEY_HOLE)) { + int h = persist_read_int(PERSIST_KEY_HOLE); + s_current_hole = (h >= 0 && h < MAX_HOLES) ? h : 0; + } +} + +// --------------------------------------------------------------------------- +// Main canvas draw +// --------------------------------------------------------------------------- +static void canvas_update_proc(Layer *layer, GContext *ctx) { + GRect bounds = layer_get_bounds(layer); + int w = bounds.size.w; + HoleScore *hole = &s_scores[s_current_hole]; + + graphics_context_set_fill_color(ctx, GColorWhite); + graphics_fill_rect(ctx, bounds, 0, GCornerNone); + + // Header + graphics_context_set_fill_color(ctx, GColorJaegerGreen); + graphics_fill_rect(ctx, GRect(0, 0, w, 44), 0, GCornerNone); + + snprintf(s_hole_buf, sizeof(s_hole_buf), "HOLE %d / %d", + s_current_hole + 1, MAX_HOLES); + graphics_context_set_text_color(ctx, GColorWhite); + graphics_draw_text(ctx, s_hole_buf, + fonts_get_system_font(FONT_KEY_GOTHIC_18_BOLD), + GRect(0, 12, w, 22), + GTextOverflowModeWordWrap, GTextAlignmentCenter, NULL); + + // Strokes + graphics_context_set_text_color(ctx, GColorDarkGray); + graphics_draw_text(ctx, "STROKES", + fonts_get_system_font(FONT_KEY_GOTHIC_18_BOLD), + GRect(0, 50, w, 22), + GTextOverflowModeWordWrap, GTextAlignmentCenter, NULL); + + snprintf(s_stroke_buf, sizeof(s_stroke_buf), "%d", hole->strokes); + graphics_context_set_text_color(ctx, GColorBlack); + graphics_draw_text(ctx, s_stroke_buf, + fonts_get_system_font(FONT_KEY_BITHAM_42_BOLD), + GRect(0, 70, w, 58), + GTextOverflowModeWordWrap, GTextAlignmentCenter, NULL); + + // Divider + graphics_context_set_stroke_color(ctx, GColorLightGray); + graphics_draw_line(ctx, GPoint(20, 133), GPoint(w - 20, 133)); + + // Putts + graphics_context_set_text_color(ctx, GColorDarkGray); + graphics_draw_text(ctx, "PUTTS", + fonts_get_system_font(FONT_KEY_GOTHIC_18_BOLD), + GRect(0, 139, w, 22), + GTextOverflowModeWordWrap, GTextAlignmentCenter, NULL); + + snprintf(s_putt_buf, sizeof(s_putt_buf), "%d", hole->putts); + graphics_context_set_text_color(ctx, GColorCobaltBlue); + graphics_draw_text(ctx, s_putt_buf, + fonts_get_system_font(FONT_KEY_BITHAM_42_BOLD), + GRect(0, 158, w, 58), + GTextOverflowModeWordWrap, GTextAlignmentCenter, NULL); + + // Hint bar + graphics_context_set_fill_color(ctx, GColorLightGray); + graphics_fill_rect(ctx, GRect(0, 216, w, 12), 0, GCornerNone); + graphics_context_set_text_color(ctx, GColorDarkGray); + graphics_draw_text(ctx, "Hold +/- = putts Hold O = settings", + fonts_get_system_font(FONT_KEY_GOTHIC_14), + GRect(2, 217, w - 4, 12), + GTextOverflowModeTrailingEllipsis, GTextAlignmentCenter, NULL); +} + +// --------------------------------------------------------------------------- +// Main window — button handlers +// --------------------------------------------------------------------------- +static void up_click_handler(ClickRecognizerRef recognizer, void *context) { + HoleScore *hole = &s_scores[s_current_hole]; + if (hole->strokes < 99) { + hole->strokes++; + vibes_short_pulse(); + } + layer_mark_dirty(s_canvas_layer); +} + +static void down_click_handler(ClickRecognizerRef recognizer, void *context) { + HoleScore *hole = &s_scores[s_current_hole]; + if (hole->strokes > 0) { + hole->strokes--; + if (hole->putts > hole->strokes) { + hole->putts = hole->strokes; + } + } + layer_mark_dirty(s_canvas_layer); +} + +static void select_click_handler(ClickRecognizerRef recognizer, void *context) { + if (s_current_hole < MAX_HOLES - 1) { + s_current_hole++; + vibes_short_pulse(); + } else { + vibes_double_pulse(); + } + save_scores(); + layer_mark_dirty(s_canvas_layer); +} + +static void up_long_handler(ClickRecognizerRef recognizer, void *context) { + HoleScore *hole = &s_scores[s_current_hole]; + if (hole->putts < 99) { + hole->putts++; + if (hole->putts > hole->strokes && hole->strokes < 99) { + hole->strokes = hole->putts; + } + } + layer_mark_dirty(s_canvas_layer); +} + +static void down_long_handler(ClickRecognizerRef recognizer, void *context) { + HoleScore *hole = &s_scores[s_current_hole]; + if (hole->putts > 0) { + hole->putts--; + } + layer_mark_dirty(s_canvas_layer); +} + +// --------------------------------------------------------------------------- +// Scorecard window (read-only — reset lives in settings) +// --------------------------------------------------------------------------- +static void build_scorecard(void) { + int total_str = 0, total_ptt = 0; + int pos = 0; + + pos += snprintf(s_scorecard_buf + pos, sizeof(s_scorecard_buf) - pos, + "SCORECARD\n\nHole Str Ptt\n"); + + for (int i = 0; i < MAX_HOLES; i++) { + total_str += s_scores[i].strokes; + total_ptt += s_scores[i].putts; + pos += snprintf(s_scorecard_buf + pos, sizeof(s_scorecard_buf) - pos, + " %2d %2d %2d%s\n", + i + 1, s_scores[i].strokes, s_scores[i].putts, + (i == s_current_hole) ? " <" : ""); + } + + snprintf(s_scorecard_buf + pos, sizeof(s_scorecard_buf) - pos, + "\nTOT %3d %3d", total_str, total_ptt); +} + +static void scorecard_window_load(Window *window) { + Layer *root = window_get_root_layer(window); + GRect bounds = layer_get_bounds(root); + + build_scorecard(); + + GFont font = fonts_get_system_font(FONT_KEY_GOTHIC_18_BOLD); + GSize text_size = graphics_text_layout_get_content_size( + s_scorecard_buf, font, + GRect(0, 0, bounds.size.w - 8, 3000), + GTextOverflowModeWordWrap, GTextAlignmentLeft); + int content_h = text_size.h + 20; + + s_scroll_layer = scroll_layer_create(bounds); + scroll_layer_set_content_size(s_scroll_layer, GSize(bounds.size.w, content_h)); + scroll_layer_set_click_config_onto_window(s_scroll_layer, window); + layer_add_child(root, scroll_layer_get_layer(s_scroll_layer)); + + s_scorecard_layer = text_layer_create(GRect(4, 4, bounds.size.w - 8, content_h)); + text_layer_set_text(s_scorecard_layer, s_scorecard_buf); + text_layer_set_font(s_scorecard_layer, font); + text_layer_set_overflow_mode(s_scorecard_layer, GTextOverflowModeWordWrap); + text_layer_set_background_color(s_scorecard_layer, GColorClear); + scroll_layer_add_child(s_scroll_layer, text_layer_get_layer(s_scorecard_layer)); +} + +static void scorecard_window_unload(Window *window) { + text_layer_destroy(s_scorecard_layer); + scroll_layer_destroy(s_scroll_layer); + window_destroy(s_scorecard_window); + s_scorecard_window = NULL; +} + +// --------------------------------------------------------------------------- +// Return-to-main helper — pops all windows above s_main_window +// --------------------------------------------------------------------------- +static void return_to_main_cb(void *data) { + s_return_timer = NULL; + Window *top; + while ((top = window_stack_get_top_window()) != NULL && top != s_main_window) { + window_stack_pop(false); + } + layer_mark_dirty(s_canvas_layer); +} + +static void schedule_return_to_main(void) { + if (s_return_timer) app_timer_cancel(s_return_timer); + s_return_timer = app_timer_register(50, return_to_main_cb, NULL); +} + +// --------------------------------------------------------------------------- +// Hole picker window +// --------------------------------------------------------------------------- +static void hole_picker_select_cb(int index, void *ctx) { + s_current_hole = index; + save_scores(); + schedule_return_to_main(); +} + +static void hole_picker_window_load(Window *window) { + Layer *root = window_get_root_layer(window); + GRect bounds = layer_get_bounds(root); + + for (int i = 0; i < MAX_HOLES; i++) { + bool current = (i == s_current_hole); + snprintf(s_hole_titles[i], sizeof(s_hole_titles[i]), + current ? "> Hole %d" : " Hole %d", i + 1); + + HoleScore *h = &s_scores[i]; + if (h->strokes == 0 && h->putts == 0) { + snprintf(s_hole_subtitles[i], sizeof(s_hole_subtitles[i]), "not played"); + } else { + snprintf(s_hole_subtitles[i], sizeof(s_hole_subtitles[i]), + "%d str / %d ptt", h->strokes, h->putts); + } + + s_hole_items[i] = (SimpleMenuItem){ + .title = s_hole_titles[i], + .subtitle = s_hole_subtitles[i], + .callback = hole_picker_select_cb, + }; + } + + s_hole_section = (SimpleMenuSection){ + .title = "Jump to Hole", + .items = s_hole_items, + .num_items = MAX_HOLES, + }; + + s_hole_picker_layer = simple_menu_layer_create(bounds, window, + &s_hole_section, 1, NULL); + simple_menu_layer_set_selected_index(s_hole_picker_layer, s_current_hole, false); + layer_add_child(root, simple_menu_layer_get_layer(s_hole_picker_layer)); +} + +static void hole_picker_window_unload(Window *window) { + simple_menu_layer_destroy(s_hole_picker_layer); + window_destroy(s_hole_picker_window); + s_hole_picker_window = NULL; +} + +// --------------------------------------------------------------------------- +// Settings menu callbacks (defined after the windows they push) +// --------------------------------------------------------------------------- +static void settings_scorecard_cb(int index, void *ctx) { + s_scorecard_window = window_create(); + window_set_background_color(s_scorecard_window, GColorWhite); + window_set_window_handlers(s_scorecard_window, (WindowHandlers){ + .load = scorecard_window_load, + .unload = scorecard_window_unload, + }); + window_stack_push(s_scorecard_window, true); +} + +static void settings_jump_cb(int index, void *ctx) { + s_hole_picker_window = window_create(); + window_set_window_handlers(s_hole_picker_window, (WindowHandlers){ + .load = hole_picker_window_load, + .unload = hole_picker_window_unload, + }); + window_stack_push(s_hole_picker_window, true); +} + +static void settings_help_cb(int index, void *ctx) { + s_help_window = window_create(); + window_set_background_color(s_help_window, GColorWhite); + window_set_window_handlers(s_help_window, (WindowHandlers){ + .load = help_window_load, + .unload = help_window_unload, + }); + window_stack_push(s_help_window, true); +} + +static void settings_reset_cb(int index, void *ctx) { + memset(s_scores, 0, sizeof(s_scores)); + s_current_hole = 0; + save_scores(); + vibes_double_pulse(); + schedule_return_to_main(); +} + +// --------------------------------------------------------------------------- +// Settings window +// --------------------------------------------------------------------------- +static void settings_window_load(Window *window) { + Layer *root = window_get_root_layer(window); + GRect bounds = layer_get_bounds(root); + + s_settings_items[0] = (SimpleMenuItem){ + .title = "View Scorecard", + .callback = settings_scorecard_cb, + }; + s_settings_items[1] = (SimpleMenuItem){ + .title = "Jump to Hole", + .subtitle = "Go back to any hole", + .callback = settings_jump_cb, + }; + s_settings_items[2] = (SimpleMenuItem){ + .title = "Reset Round", + .subtitle = "Clears all scores", + .callback = settings_reset_cb, + }; + s_settings_items[3] = (SimpleMenuItem){ + .title = "Controls", + .subtitle = "Button cheatsheet", + .callback = settings_help_cb, + }; + + s_settings_section = (SimpleMenuSection){ + .title = "Settings", + .items = s_settings_items, + .num_items = 4, + }; + + s_settings_menu_layer = simple_menu_layer_create(bounds, window, + &s_settings_section, 1, NULL); + layer_add_child(root, simple_menu_layer_get_layer(s_settings_menu_layer)); +} + +static void settings_window_unload(Window *window) { + simple_menu_layer_destroy(s_settings_menu_layer); + window_destroy(s_settings_window); + s_settings_window = NULL; +} + +static void show_settings(ClickRecognizerRef recognizer, void *context) { + s_settings_window = window_create(); + window_set_window_handlers(s_settings_window, (WindowHandlers){ + .load = settings_window_load, + .unload = settings_window_unload, + }); + window_stack_push(s_settings_window, true); +} + +// --------------------------------------------------------------------------- +// Main window — click config & lifecycle +// --------------------------------------------------------------------------- +static void click_config_provider(void *context) { + window_single_click_subscribe(BUTTON_ID_UP, up_click_handler); + window_single_click_subscribe(BUTTON_ID_DOWN, down_click_handler); + window_single_click_subscribe(BUTTON_ID_SELECT, select_click_handler); + window_long_click_subscribe(BUTTON_ID_UP, 700, up_long_handler, NULL); + window_long_click_subscribe(BUTTON_ID_DOWN, 700, down_long_handler, NULL); + window_long_click_subscribe(BUTTON_ID_SELECT, 700, show_settings, NULL); +} + +static void main_window_load(Window *window) { + Layer *root = window_get_root_layer(window); + GRect bounds = layer_get_bounds(root); + s_canvas_layer = layer_create(bounds); + layer_set_update_proc(s_canvas_layer, canvas_update_proc); + layer_add_child(root, s_canvas_layer); +} + +static void main_window_unload(Window *window) { + layer_destroy(s_canvas_layer); +} + +// --------------------------------------------------------------------------- +// Entry point +// --------------------------------------------------------------------------- +int main(void) { + load_scores(); + + s_main_window = window_create(); + window_set_click_config_provider(s_main_window, click_config_provider); + window_set_window_handlers(s_main_window, (WindowHandlers){ + .load = main_window_load, + .unload = main_window_unload, + }); + window_stack_push(s_main_window, true); + + app_event_loop(); + + save_scores(); + window_destroy(s_main_window); + return 0; +} diff --git a/wscript b/wscript new file mode 100644 index 0000000..5238bc8 --- /dev/null +++ b/wscript @@ -0,0 +1,54 @@ +# +# This file is the default set of rules to compile a Pebble application. +# +# Feel free to customize this to your needs. +# +import os.path + +top = '.' +out = 'build' + + +def options(ctx): + ctx.load('pebble_sdk') + + +def configure(ctx): + """ + This method is used to configure your build. ctx.load(`pebble_sdk`) automatically configures + a build for each valid platform in `targetPlatforms`. Platform-specific configuration: add your + change after calling ctx.load('pebble_sdk') and make sure to set the correct environment first. + Universal configuration: add your change prior to calling ctx.load('pebble_sdk'). + """ + ctx.load('pebble_sdk') + + +def build(ctx): + ctx.load('pebble_sdk') + + build_worker = os.path.exists('worker_src') + binaries = [] + + cached_env = ctx.env + for platform in ctx.env.TARGET_PLATFORMS: + ctx.env = ctx.all_envs[platform] + ctx.set_group(ctx.env.PLATFORM_NAME) + app_elf = '{}/pebble-app.elf'.format(ctx.env.BUILD_DIR) + ctx.pbl_build(source=ctx.path.ant_glob('src/c/**/*.c'), target=app_elf, bin_type='app') + + if build_worker: + worker_elf = '{}/pebble-worker.elf'.format(ctx.env.BUILD_DIR) + binaries.append({'platform': platform, 'app_elf': app_elf, 'worker_elf': worker_elf}) + ctx.pbl_build(source=ctx.path.ant_glob('worker_src/c/**/*.c'), + target=worker_elf, + bin_type='worker') + else: + binaries.append({'platform': platform, 'app_elf': app_elf}) + ctx.env = cached_env + + ctx.set_group('bundle') + ctx.pbl_bundle(binaries=binaries, + js=ctx.path.ant_glob(['src/pkjs/**/*.js', + 'src/pkjs/**/*.json', + 'src/common/**/*.js']), + js_entry_file='src/pkjs/index.js')