diff --git a/CHANGELOG.md b/CHANGELOG.md index 3007f229c..8efa7307f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,10 @@ ## [2.1.38] - 2026-10-21 +- Track habits you want to avoid with a daily target of 0. +- Set custom coins per occurrence, including negative penalties and 0. - Simplify Apps editing, settings, navigation and app loading; make Photos available to everyone. +- Diary and Photos share saved images and automatically compress new photo uploads. - Fix Profile headers, scrolling, dialogs, font freezes and Android key backups. - Fix large-account sync, false sync failures, sharing controls and activity and achievement views. diff --git a/apps/habits/CHANGELOG.md b/apps/habits/CHANGELOG.md index 8a3ca98fb..57fc1fa48 100644 --- a/apps/habits/CHANGELOG.md +++ b/apps/habits/CHANGELOG.md @@ -2,6 +2,7 @@ ## [1.2.3] - 2026-10-21 +- Track zero-occurrence goals and choose custom coins, including 0 and negative coins per occurrence. - Give each achievement its own meaningful icon. - Maintenance release for Inner Breeze 2.1.38. diff --git a/apps/habits/habits_achievements.zi b/apps/habits/habits_achievements.zi index 82b018b6c..f40c2fca0 100644 --- a/apps/habits/habits_achievements.zi +++ b/apps/habits/habits_achievements.zi @@ -50,7 +50,7 @@ AchievementHabitDaysBackfill :: (habits: *Habits, offset: s32) -> s32 { target = target * 10 + cast(s32)(byte - #char "0") } counter = true - known = known && target > 0 + known = known && target >= 0 } } complete := known && HabitDayComplete(value, counter, target) diff --git a/apps/lumi/CHANGELOG.md b/apps/lumi/CHANGELOG.md index b39c2f30e..7796bd8f0 100644 --- a/apps/lumi/CHANGELOG.md +++ b/apps/lumi/CHANGELOG.md @@ -2,6 +2,7 @@ ## [1.5.4] - 2026-10-21 +- Set a habit's counting target to 0 and show its recorded progress correctly. - Give each achievement its own meaningful icon. - Maintenance release for Inner Breeze 2.1.38. diff --git a/apps/lumi/habit_intent.zi b/apps/lumi/habit_intent.zi index 6ebbc9c32..9550fafbf 100644 --- a/apps/lumi/habit_intent.zi +++ b/apps/lumi/habit_intent.zi @@ -172,10 +172,17 @@ LumiApplyClause :: (plan: *LumiHabitPlan, tag: string, capture: LumiCapture) -> return LumiSetOnce(*plan.reminder, 2) } if tag == "count" { - if capture.number_count != 1 || capture.numbers[0] < 1 || capture.numbers[0] > 9999 { + if capture.number_count != 1 || capture.numbers[0] < 0 || capture.numbers[0] > 9999 { return false } - return LumiSetOnce(*plan.mode, LUMI_MODE_COUNT) && LumiSetOnce(*plan.target, capture.numbers[0]) + if plan.mode == LUMI_MODE_COUNT && plan.target != capture.numbers[0] { + return false + } + if !LumiSetOnce(*plan.mode, LUMI_MODE_COUNT) { + return false + } + plan.target = capture.numbers[0] + return true } if tag == "check" { return LumiSetOnce(*plan.mode, LUMI_MODE_CHECK) diff --git a/assets/fonts/subset/NotoSansJP-App-Regular.otf b/assets/fonts/subset/NotoSansJP-App-Regular.otf index 935df7f71..58850e0d7 100644 Binary files a/assets/fonts/subset/NotoSansJP-App-Regular.otf and b/assets/fonts/subset/NotoSansJP-App-Regular.otf differ diff --git a/assets/fonts/subset/NotoSansKR-App-Regular.otf b/assets/fonts/subset/NotoSansKR-App-Regular.otf index 636c6e359..fa7647b37 100644 Binary files a/assets/fonts/subset/NotoSansKR-App-Regular.otf and b/assets/fonts/subset/NotoSansKR-App-Regular.otf differ diff --git a/assets/fonts/subset/NotoSansSC-App-Regular.otf b/assets/fonts/subset/NotoSansSC-App-Regular.otf index dea4f29d2..c64a1a2a5 100644 Binary files a/assets/fonts/subset/NotoSansSC-App-Regular.otf and b/assets/fonts/subset/NotoSansSC-App-Regular.otf differ diff --git a/assets/fonts/subset/NotoSansTC-App-Regular.otf b/assets/fonts/subset/NotoSansTC-App-Regular.otf index 158c61d0e..9cfc388fa 100644 Binary files a/assets/fonts/subset/NotoSansTC-App-Regular.otf and b/assets/fonts/subset/NotoSansTC-App-Regular.otf differ diff --git a/docs/cells.md b/docs/cells.md index caf5a633f..d5d321ab2 100644 --- a/docs/cells.md +++ b/docs/cells.md @@ -178,6 +178,18 @@ sets a habit's tracking with `set_habit_tracking` (check, count with a target, or span with its good length) and its questions and good answers with `set_habit_questions`; her context lists both for each habit. +A counting habit can have a daily target of 0 to track something the person +wants to avoid. A recorded count of 0 completes that day; occurrences miss the +goal, and unrecorded or cleared days stay incomplete. Closing the count dialog +with 0 records that zero. Stored counts and linked sessions remain visible. + +Custom coins replace difficulty rewards with a signed amount for every +occurrence, regardless of whether the target is reached. For example, -2 coins +with 3 occurrences deducts 6; 0 gives no reward or penalty. A recorded zero +never creates an occurrence. Edits and sync recalculate each day's amount +without charging twice. Rate changes apply from their local day onward, keeping +earlier days' rates, and deleted habits retain their earned coins or penalties. + Each habit has a difficulty, medium, hard or very hard. A done day earns 1, 2 or 3 coins, counted the way the habit list counts a day as done (marked, counted to its target, or covered by linked practice sessions). A changed @@ -513,6 +525,13 @@ the node offers: a newest-first grid of the library's photos under the day each was taken, a viewer with previous, next and Move to Trash, and Trash, where a photo can be restored. Install it from the normal app catalog. +Diary and Photos use the same host import and account storage, even when +Photos is not installed. New opaque still images larger than 256 KiB are +stored as upright JPEG copies at quality 88 and at most 2048 pixels on the +longest edge, only when this saves more than 10%. Source files stay untouched; +capture dates remain in the shared record. Small, transparent and animated +images retain their bytes, as do photos already in the library. + The library belongs to the account, not to Photos, so its photos stay when Photos is removed. The host keeps it (`src/cells/media_store.zi`): each photo is stored once by the SHA-256 of its bytes under diff --git a/fastlane/metadata/android/en-US/changelogs/175.txt b/fastlane/metadata/android/en-US/changelogs/175.txt index a598fe451..8229dba89 100644 --- a/fastlane/metadata/android/en-US/changelogs/175.txt +++ b/fastlane/metadata/android/en-US/changelogs/175.txt @@ -1,3 +1,6 @@ +- Track habits you want to avoid with a daily target of 0. +- Set custom coins per occurrence, including negative penalties and 0. - Simplify Apps editing, settings, navigation and app loading; make Photos available to everyone. +- Diary and Photos share saved images and automatically compress new photo uploads. - Fix Profile headers, scrolling, dialogs, font freezes and Android key backups. - Fix large-account sync, false sync failures, sharing controls and activity and achievement views. diff --git a/locales/cs.txt b/locales/cs.txt index 28a6152ce..9e0907433 100644 --- a/locales/cs.txt +++ b/locales/cs.txt @@ -7466,3 +7466,19 @@ Nepovolit [launcher_edit_apps] Upravit aplikace --- + +[habit_custom_coins] +Vlastní mince +--- + +[habit_coins_per_occurrence] +Mince za výskyt +--- + +[habit_coins_signed_hint] +Záporné hodnoty odečítají mince; 0 nedává žádné. +--- + +[habit_change_coins] +Mince: %s » %s +--- diff --git a/locales/de.txt b/locales/de.txt index 22f0082f1..d7a2bce95 100644 --- a/locales/de.txt +++ b/locales/de.txt @@ -7460,3 +7460,19 @@ Nicht erlauben [launcher_edit_apps] Apps bearbeiten --- + +[habit_custom_coins] +Eigene Münzen +--- + +[habit_coins_per_occurrence] +Münzen pro Vorkommnis +--- + +[habit_coins_signed_hint] +Negative Werte ziehen Münzen ab; 0 vergibt keine. +--- + +[habit_change_coins] +Münzen: %s » %s +--- diff --git a/locales/en.txt b/locales/en.txt index 4c276bbdd..a34dcbbc0 100644 --- a/locales/en.txt +++ b/locales/en.txt @@ -7484,3 +7484,19 @@ Don't allow [launcher_edit_apps] Edit apps --- + +[habit_custom_coins] +Custom coins +--- + +[habit_coins_per_occurrence] +Coins per occurrence +--- + +[habit_coins_signed_hint] +Negative values deduct coins; 0 gives none. +--- + +[habit_change_coins] +Coins: %s » %s +--- diff --git a/locales/es.txt b/locales/es.txt index 6f9bd9cd2..905e23c86 100644 --- a/locales/es.txt +++ b/locales/es.txt @@ -7460,3 +7460,19 @@ No permitir [launcher_edit_apps] Editar apps --- + +[habit_custom_coins] +Monedas personalizadas +--- + +[habit_coins_per_occurrence] +Monedas por ocasión +--- + +[habit_coins_signed_hint] +Los valores negativos restan monedas; 0 no da ninguna. +--- + +[habit_change_coins] +Monedas: %s » %s +--- diff --git a/locales/fr.txt b/locales/fr.txt index ebb6dcdd7..428e665eb 100644 --- a/locales/fr.txt +++ b/locales/fr.txt @@ -7448,3 +7448,19 @@ Ne pas autoriser [launcher_edit_apps] Modifier les apps --- + +[habit_custom_coins] +Pièces personnalisées +--- + +[habit_coins_per_occurrence] +Pièces par occurrence +--- + +[habit_coins_signed_hint] +Les valeurs négatives retirent des pièces ; 0 n’en donne aucune. +--- + +[habit_change_coins] +Pièces : %s » %s +--- diff --git a/locales/id.txt b/locales/id.txt index 5d3d1fd8d..e55d31d12 100644 --- a/locales/id.txt +++ b/locales/id.txt @@ -7449,3 +7449,19 @@ Jangan izinkan [launcher_edit_apps] Edit aplikasi --- + +[habit_custom_coins] +Koin khusus +--- + +[habit_coins_per_occurrence] +Koin per kejadian +--- + +[habit_coins_signed_hint] +Nilai negatif mengurangi koin; 0 tidak memberi koin. +--- + +[habit_change_coins] +Koin: %s » %s +--- diff --git a/locales/it.txt b/locales/it.txt index c2972052b..e942b2bd7 100644 --- a/locales/it.txt +++ b/locales/it.txt @@ -7449,3 +7449,19 @@ Non consentire [launcher_edit_apps] Modifica app --- + +[habit_custom_coins] +Monete personalizzate +--- + +[habit_coins_per_occurrence] +Monete per volta +--- + +[habit_coins_signed_hint] +I valori negativi sottraggono monete; 0 non ne dà. +--- + +[habit_change_coins] +Monete: %s » %s +--- diff --git a/locales/ja.txt b/locales/ja.txt index 3a598d488..7edfb04f0 100644 --- a/locales/ja.txt +++ b/locales/ja.txt @@ -7445,3 +7445,19 @@ Lumi や日記など、Inner Breeze 内のアプリを waozi.xyz から自動で [launcher_edit_apps] アプリを編集 --- + +[habit_custom_coins] +コイン数を指定 +--- + +[habit_coins_per_occurrence] +1回あたりのコイン +--- + +[habit_coins_signed_hint] +負の値はコインを減らし、0では増減しません。 +--- + +[habit_change_coins] +コイン:%s » %s +--- diff --git a/locales/ko.txt b/locales/ko.txt index 555376c5e..2dd3d7de8 100644 --- a/locales/ko.txt +++ b/locales/ko.txt @@ -7455,3 +7455,19 @@ Lumi, 일기 등 Inner Breeze 안의 앱을 waozi.xyz에서 자동으로 업데 [launcher_edit_apps] 앱 편집 --- + +[habit_custom_coins] +코인 직접 설정 +--- + +[habit_coins_per_occurrence] +발생 1회당 코인 +--- + +[habit_coins_signed_hint] +음수는 코인을 차감하며, 0은 코인을 주지 않습니다. +--- + +[habit_change_coins] +코인: %s » %s +--- diff --git a/locales/pt.txt b/locales/pt.txt index 265f7c8b7..4734fae3d 100644 --- a/locales/pt.txt +++ b/locales/pt.txt @@ -7458,3 +7458,19 @@ Não permitir [launcher_edit_apps] Editar apps --- + +[habit_custom_coins] +Moedas personalizadas +--- + +[habit_coins_per_occurrence] +Moedas por ocorrência +--- + +[habit_coins_signed_hint] +Valores negativos descontam moedas; 0 não dá nenhuma. +--- + +[habit_change_coins] +Moedas: %s » %s +--- diff --git a/locales/ru.txt b/locales/ru.txt index bdb4a90f7..68bb85461 100644 --- a/locales/ru.txt +++ b/locales/ru.txt @@ -7454,3 +7454,19 @@ Inner Breeze обновлён до версии %s. [launcher_edit_apps] Изменить приложения --- + +[habit_custom_coins] +Свои монеты +--- + +[habit_coins_per_occurrence] +Монеты за каждый раз +--- + +[habit_coins_signed_hint] +Отрицательные значения вычитают монеты; 0 не даёт монет. +--- + +[habit_change_coins] +Монеты: %s » %s +--- diff --git a/locales/zh.txt b/locales/zh.txt index 2ee8b37e3..7c60a1d41 100644 --- a/locales/zh.txt +++ b/locales/zh.txt @@ -7460,3 +7460,19 @@ Inner Breeze 已更新至 %s 版本。 [launcher_edit_apps] 编辑应用 --- + +[habit_custom_coins] +自定义金币 +--- + +[habit_coins_per_occurrence] +每次发生的金币 +--- + +[habit_coins_signed_hint] +负数扣除金币;0 不增减金币。 +--- + +[habit_change_coins] +金币:%s » %s +--- diff --git a/src/app/app_types.zi b/src/app/app_types.zi index 5a797ce0a..a45e578c8 100644 --- a/src/app/app_types.zi +++ b/src/app/app_types.zi @@ -312,6 +312,13 @@ HabitEditState :: struct { icon: s32 // How hard the habit is, as Habit.difficulty. difficulty: s32 + custom_coins: bool + coin_halves: s32 + coin_text: [12]u8 + coin_cursor: s32 + coin_anchor: s32 + coin_scroll_x: s32 + coin_focused: s32 // The schedule being edited, which the habit takes from today on. schedule: HabitSchedule formula_cursor: s32 diff --git a/src/app/screenshots.zi b/src/app/screenshots.zi index 35e7d6635..5595f5cba 100644 --- a/src/app/screenshots.zi +++ b/src/app/screenshots.zi @@ -860,7 +860,8 @@ setup_screenshot_scene :: (app: *InnerBreeze, request: *ScreenshotRequest) { app.habits.tab = HABIT_TAB_WEEKLY app.habits.view_mode = HABIT_VIEW_WEEKLY app.breathing.screen = ScreenHabits - } else if scene_text == "habit_counts" || scene_text == "habit_count_dialog" { + } else if scene_text == "habit_counts" || scene_text == "habit_count_dialog" || + scene_text == "habit_count_zero" { app.main_tab = APP_MAIN_TAB_HABITS app.habits.screen_mode = HABITS_SCREEN_OVERVIEW app.habits.selected = 2 @@ -868,7 +869,14 @@ setup_screenshot_scene :: (app: *InnerBreeze, request: *ScreenshotRequest) { app.habits.view_mode = HABIT_VIEW_WEEKLY app.breathing.screen = ScreenHabits screenshot_seed_habit_counts(app) - if scene_text == "habit_count_dialog" { + if scene_text == "habit_count_zero" { + app.habits.items[2].counter_target = 0 + app.habits.items[2].custom_coins = true + app.habits.items[2].coin_halves = -4 + habit_set_day(*app.habits, 2, screenshot_day_index_offset(0), 0) + habits_save(*app.habits) + } + if scene_text == "habit_count_dialog" || scene_text == "habit_count_zero" { app.habits.count_dialog_habit = 2 app.habits.count_dialog_day = screenshot_day_index_offset(0) app_open_modal(app, cast(ModalType)ModalHabitCount) diff --git a/src/cells/app_tools.zi b/src/cells/app_tools.zi index 8044c49f3..164681a45 100644 --- a/src/cells/app_tools.zi +++ b/src/cells/app_tools.zi @@ -600,10 +600,10 @@ AppHabitTrackingTool :: (app: *InnerBreeze, arguments: string) -> string { target_at := FieldAt(arguments, 0, "target") if target_at >= 0 { number := ReadNumber(arguments, target_at) - if !number.valid || number.value < 1 || + if !number.valid || number.value < 0 || number.value > cast(float64)HABIT_COUNTER_TARGET_MAX || number.value != cast(float64)cast(s32)number.value { - return ToolFailure("target must be an integer from 1 to 9999") + return ToolFailure("target must be an integer from 0 to 9999") } target = cast(s32)number.value } diff --git a/src/cells/lumi_progress.zi b/src/cells/lumi_progress.zi index 9a2f80ba7..2b8babb0d 100644 --- a/src/cells/lumi_progress.zi +++ b/src/cells/lumi_progress.zi @@ -91,7 +91,11 @@ LumiProgressJson :: (app: *InnerBreeze, metric: s32, days: s32) -> string { } } target := ifx habit_counting_enabled(habit) != 0 then habit_counter_target(habit) else 1 - if count >= target { + complete := count >= target + if target == 0 { + complete = count == 0 && HabitCompletedFor(habit, dates[day]) + } + if complete { values[day] += 1 } } diff --git a/src/cells/media_store.zi b/src/cells/media_store.zi index f5e48d8bc..95b6c7319 100644 --- a/src/cells/media_store.zi +++ b/src/cells/media_store.zi @@ -48,6 +48,11 @@ // upright, as JPEG of this quality. MEDIA_PREVIEW_EDGE :: 512 MEDIA_PREVIEW_QUALITY :: 80 +// New photos use a smaller upright copy when it saves space. Small files, +// transparency and animation keep their existing bytes. +MEDIA_UPLOAD_EDGE :: 2048 +MEDIA_UPLOAD_QUALITY :: 88 +MEDIA_COMPRESS_BYTES :: 262144 MEDIA_NAME_MAX :: 200 // Originals asked for on this device, downloaded by the next media pass. MEDIA_WANTED_MAX :: 32 @@ -422,6 +427,8 @@ MediaAddition :: struct { // A file on this device with the same bytes, linked rather than copied // where the platform allows, or "". source: string + // Original bytes whose camera date survives an optimized library copy. + capture_source: string // Whether a photo the library has in Trash comes back, as when the // person picks it again. restore: bool @@ -431,6 +438,28 @@ MediaAddition :: struct { // its record, and one in Trash comes back. The bytes always land in this // device's file, so a photo known from another device needs no download. MediaImportBytes :: (data: string, name: string) -> MediaImport { + if !DataTemporary() && data.count > MEDIA_COMPRESS_BYTES && data.count <= DIARY_FILE_LIMIT { + // A photo already in this account keeps its existing identity and + // record, including photos added before upload compression. + original_hash: [65]u8 + descriptor := cast(*TextDescriptor)(*data) + storage_sha256_hex(descriptor.data, data.count, *original_hash[0]) + if !MediaRead(TextUntilNul(original_hash[:])).valid { + format := DiaryImageFormat(data) + file_type := PackageText(".", format) + copy := ImageCompress(data, file_type, MEDIA_UPLOAD_EDGE, + MediaOrientationOf(data, format), MEDIA_UPLOAD_QUALITY) + defer { + PackageFree(file_type) + PackageFree(copy) + } + // Keep a copy only when the saving is meaningful. + if copy.count > 0 && copy.count * 10 < data.count * 9 { + return MediaAddBytes(copy, MediaAddition.{.name = name, + .capture_source = data, .restore = true}) + } + } + } return MediaAddBytes(data, MediaAddition.{.name = name, .restore = true}) } @@ -482,14 +511,16 @@ MediaAddBytes :: (data: string, addition: MediaAddition) -> MediaImport { } day: [11]u8 taken: [26]u8 - if !MediaWhen(data, format, addition.day, day[:], taken[:]) { + capture_data := ifx addition.capture_source.count > 0 then addition.capture_source else data + capture_format := ifx addition.capture_source.count > 0 then DiaryImageFormat(capture_data) else format + if !MediaWhen(capture_data, capture_format, addition.day, day[:], taken[:]) { return result } MediaWritePreview(hash, data, format) out: Vec(u8) BuilderPrint(*out, "{\"hash\":\"%\",\"size\":%,\"type\":\"%\",\"name\":", hash, data.count, format) MediaJson(*out, MediaName(addition.name)) - capture := MediaCaptureOf(data, format) + capture := MediaCaptureOf(capture_data, capture_format) BuilderPrint(*out, ",\"day\":\"%\",\"taken\":\"%\",\"added\":%,\"capture\":%,\"trashed\":0}", TextUntilNul(day[:]), TextUntilNul(taken[:]), CellRecordClock() / 1000000, ifx capture.valid && capture.year >= 1000 then 1 else 0) diff --git a/src/cells/shared_state.zi b/src/cells/shared_state.zi index 94571a565..d2904934a 100644 --- a/src/cells/shared_state.zi +++ b/src/cells/shared_state.zi @@ -12,6 +12,7 @@ ModuleHost :: #import, file "module_host.zi"; #import, file "../habits/habit_types.zi"; #import, file "../habits/habit_questions.zi"; #import, file "../habits/habit_schedule.zi"; +#import, file "../habits/habit_coins.zi"; #scope_file shared_app: *InnerBreeze; @@ -79,6 +80,8 @@ SaveHabit :: (message: HabitsMessage) -> bool { (message.is_new || shared_app.habit_edit.index == index) { habit.icon = shared_app.habit_edit.icon habit.difficulty = shared_app.habit_edit.difficulty + habit.custom_coins = shared_app.habit_edit.custom_coins + habit.coin_halves = HabitCoinHalvesClamp(shared_app.habit_edit.coin_halves) habit.questions = shared_app.habit_edit.questions habit.question_count = shared_app.habit_edit.question_count habit.span = shared_app.habit_edit.span diff --git a/src/habits/habit_actions.zi b/src/habits/habit_actions.zi index 7b6292dd0..d5558133d 100644 --- a/src/habits/habit_actions.zi +++ b/src/habits/habit_actions.zi @@ -21,6 +21,9 @@ habit_complete_day :: (app: *InnerBreeze, index: s32, day: s32) -> bool { habit := *app.habits.items[index] count := HabitEffectiveDayCount(habit, day, habit_cached_linked_entries(app, index, day)) target := ifx habit_counting_enabled(habit) != 0 then habit_counter_target(habit) else 1 + if target == 0 && count > 0 { + return false + } if count < target { count = target } @@ -147,7 +150,7 @@ habit_set_questions :: (app: *InnerBreeze, index: s32, habit_set_tracking :: (app: *InnerBreeze, index: s32, counting: bool, target: s32, span: bool, span_goal: HabitGoal) -> bool { if app == null || index < 0 || index >= app.habits.count || - target < 1 || target > HABIT_COUNTER_TARGET_MAX || (counting && span) || + target < 0 || target > HABIT_COUNTER_TARGET_MAX || (counting && span) || span_goal.kind == HABIT_GOAL_YES || span_goal.kind == HABIT_GOAL_NO || span_goal.low < 0 || span_goal.high < 0 || (span_goal.kind == HABIT_GOAL_BETWEEN && span_goal.low > span_goal.high) { diff --git a/src/habits/habit_calendar.zi b/src/habits/habit_calendar.zi index 66a010fc0..19512ebc8 100644 --- a/src/habits/habit_calendar.zi +++ b/src/habits/habit_calendar.zi @@ -7,13 +7,18 @@ habit_counting_enabled :: (habit: *Habit) -> s32 { } habit_counter_target :: (habit: *Habit) -> s32 { - if habit == null || habit.counter_target < 1 { return 1 } + if habit == null || habit.counter_target < 0 { return 1 } return habit.counter_target } HabitDayComplete :: (day: HabitDay, counter_enabled: bool, counter_target: s32) -> bool { if counter_enabled { + // Zero is an avoidance goal. Only a recorded zero succeeds; + // unrecorded or cleared days do not earn completion. + if counter_target == 0 { + return day.completed != 0 && day.count == 0 && day.session_count == 0 + } count := day.count if count <= 0 && day.completed != 0 { count = 1 diff --git a/src/habits/habit_changes.zi b/src/habits/habit_changes.zi index 63a9137d5..9d52388f1 100644 --- a/src/habits/habit_changes.zi +++ b/src/habits/habit_changes.zi @@ -4,6 +4,7 @@ #import, file "habit_types.zi"; #import, file "habit_questions.zi"; #import, file "habit_schedule.zi"; +#import, file "habit_coins.zi"; #import, file "../app/text_buffers.zi"; HABIT_CHANGE_CREATED :: 1 @@ -25,10 +26,26 @@ HABIT_CHANGE_QUESTION_GOAL :: 16 HABIT_CHANGE_DELETED :: 17 HABIT_CHANGE_SPAN_GOAL :: 18 HABIT_CHANGE_DIFFICULTY :: 19 +HABIT_CHANGE_COINS :: 20 HABIT_CHANGE_VALUE_SIZE :: 256 // A save can change every setting and every question. -HABIT_CHANGE_MAX :: 14 + HABIT_QUESTION_MAX * 4 +HABIT_CHANGE_MAX :: 15 + HABIT_QUESTION_MAX * 4 + +// The mode and rate before a change: custom coins per occurrence or +// difficulty coins per completed day, in half coins. +HabitCoinSettingText :: (habit: *Habit, output: []u8) -> string { + cursor: s32 = 0 + output[0] = 0 + unused TextBufferAppendNumber(output, *cursor, ifx habit.custom_coins then 1 else 0) + unused TextBufferAppendByte(output, *cursor, #char ":") + halves := HabitDifficultyHalfCoins(habit.difficulty) + if habit.custom_coins { + halves = HabitCoinHalvesClamp(habit.coin_halves) + } + unused TextBufferAppendNumber(output, *cursor, halves) + return AppTextFromCString(*output[0], cast(s32)output.count) +} // One change of a habit's settings: what changed, the question it concerns // with its words then, and the value before and after as stored text. @@ -237,6 +254,12 @@ HabitChangesBetween :: (before: *Habit, after: *Habit, HabitChangeAddNumber(output, *count, HABIT_CHANGE_DIFFICULTY, before.difficulty, after.difficulty) } + if before.custom_coins != after.custom_coins || + (after.custom_coins && before.coin_halves != after.coin_halves) || + (!after.custom_coins && before.difficulty != after.difficulty) { + unused HabitChangeAdd(output, *count, HABIT_CHANGE_COINS, + HabitCoinSettingText(before, first[:]), HabitCoinSettingText(after, second[:])) + } if HabitTrackingText(before, first[:]) != HabitTrackingText(after, second[:]) { unused HabitChangeAdd(output, *count, HABIT_CHANGE_TRACKING, HabitTrackingText(before, first[:]), HabitTrackingText(after, second[:])) diff --git a/src/habits/habit_coins.zi b/src/habits/habit_coins.zi index 2f4f0f410..6280505f4 100644 --- a/src/habits/habit_coins.zi +++ b/src/habits/habit_coins.zi @@ -1,9 +1,54 @@ -// Coins: each done day of a habit earns coins by how hard the habit is, -// and the shop's rewards cost them. The balance is what the done days -// earned since each habit's coins_from day, plus coins kept from deleted -// habits, less what the rewards bought cost (storage_habit_wallet.zi). +// Coins come from completed days at the difficulty rate, or from each +// occurrence at a custom signed rate. The shop spends their shared balance +// (storage_habit_wallet.zi). #import, file "habit_types.zi"; #import, file "habit_icons.zi"; +#import, file "../app/text_buffers.zi"; + +HABIT_COIN_HALVES_MAX :: 19998 + +HabitCoinHalvesClamp :: (halves: s32) -> s32 { + if halves < -HABIT_COIN_HALVES_MAX { return -HABIT_COIN_HALVES_MAX } + if halves > HABIT_COIN_HALVES_MAX { return HABIT_COIN_HALVES_MAX } + return halves +} + +// Signed coins in half-coin steps, as typed in the editor. +HabitCoinParse :: (text: string, halves: *s32) -> bool { + if text.count == 0 { return false } + index: s64 = 0 + negative := text[0] == #char "-" + if negative { index += 1 } + start := index + whole: s32 = 0 + while index < text.count && text[index] >= #char "0" && text[index] <= #char "9" { + whole = whole * 10 + cast(s32)text[index] - 48 + if whole > 9999 { return false } + index += 1 + } + if index == start { return false } + odd: s32 = 0 + if index < text.count { + if text[index] != #char "." || index + 2 != text.count { return false } + if text[index + 1] == #char "5" { odd = 1 } + else if text[index + 1] != #char "0" { return false } + index += 2 + } + value := whole * 2 + odd + if index != text.count || value > HABIT_COIN_HALVES_MAX { return false } + halves.* = ifx negative then -value else value + return true +} + +HabitCoinText :: (halves: s32, output: []u8) -> string { + absolute := ifx halves < 0 then -halves else halves + unused AppCopyText(ifx halves < 0 then "-" else "", output) + digits: [16]u8 + unused AppFormatS32(absolute / 2, digits[:]) + unused AppAppendText(AppTextFromCString(*digits[0], 16), output) + if absolute % 2 != 0 { unused AppAppendText(".5", output) } + return AppTextFromCString(*output[0], cast(s32)output.count) +} HabitDifficultyClamp :: (difficulty: s32) -> s32 { if difficulty == HABIT_DIFFICULTY_EASY { diff --git a/src/habits/habit_days.zi b/src/habits/habit_days.zi index 67cf428b0..29fea4eda 100644 --- a/src/habits/habit_days.zi +++ b/src/habits/habit_days.zi @@ -47,7 +47,8 @@ HabitDayCount :: (habit: *Habit, day_index: s32) -> s32 { if day.count > 0 { return day.count } - if day.completed != 0 { + if day.completed != 0 && !(habit.counter_enabled != 0 && + habit.counter_target == 0) { return 1 } return 0 diff --git a/src/habits/habit_linked_rules.zi b/src/habits/habit_linked_rules.zi index df2780a32..01f51bb49 100644 --- a/src/habits/habit_linked_rules.zi +++ b/src/habits/habit_linked_rules.zi @@ -1,5 +1,6 @@ #import, file "habit_types.zi"; #import, file "habit_days.zi"; +#import, file "habit_calendar.zi"; #import, file "../app/exercise_types.zi"; #import, file "../core/types.zi"; @@ -118,3 +119,14 @@ HabitEffectiveDayCount :: (habit: *Habit, day_index: s32, } return session_count } + +// Linked occurrences also prevent an avoidance goal from succeeding. +HabitEffectiveDayComplete :: (habit: *Habit, day_index: s32, + linked_ctx: *HabitLinkedContext) -> bool { + count := HabitEffectiveDayCount(habit, day_index, linked_ctx) + if habit_counting_enabled(habit) != 0 && habit_counter_target(habit) == 0 { + return count == 0 && HabitCompletedFor(habit, day_index) + } + target := ifx habit_counting_enabled(habit) != 0 then habit_counter_target(habit) else 1 + return count >= target +} diff --git a/src/habits/habit_model.zi b/src/habits/habit_model.zi index 7477d152b..c42cc6da2 100644 --- a/src/habits/habit_model.zi +++ b/src/habits/habit_model.zi @@ -96,18 +96,11 @@ habits_today_index :: () -> s32 { #program_export habit_completed_day :: (habit: *Habit, day_index: s32) -> s32 { index := habit_find_day(habit, day_index) - if index >= 0 && habit_counting_enabled(habit) != 0 { - count := ifx (habit.days[index].count > 0) then (habit.days[index].count) else (ifx (habit.days[index].completed != 0) then (1) else (0)) - if count >= habit_counter_target(habit) { return 1 } - return 0 - } if index < 0 { return 0 } - if habit.days[index].completed != 0 { - return 1 - } - return ifx (habit.days[index].count > 0) then (1) else (0) + return ifx HabitDayComplete(habit.days[index], + habit_counting_enabled(habit) != 0, habit_counter_target(habit)) then 1 else 0 } habit_completed_today :: (habit: *Habit) -> s32 { @@ -775,21 +768,24 @@ habit_set_day_count :: (habits: *Habits, index: s32, day_index: s32, count: s32) } habit = *habits.items[index] + recorded := count > 0 || (habit_counting_enabled(habit) != 0 && + habit_counter_target(habit) == 0) existing_index = habit_find_day(habit, day_index) if existing_index >= 0 { habit.days[existing_index].count = count - if count > 0 { + if recorded { habit.days[existing_index].completed = 1 } else { habit.days[existing_index].completed = 0 } - } else if count > 0 && habit_reserve_days(habit, habit.day_count + 1) != 0 { + } else if recorded && habit_reserve_days(habit, habit.day_count + 1) != 0 { habit.days[habit.day_count].day_index = day_index habit.days[habit.day_count].count = count habit.days[habit.day_count].completed = 1 habit.day_count += 1 } - habits_queue_day_save_completed(habits, habit, day_index, count, count) + habits_queue_day_save_completed(habits, habit, day_index, + ifx recorded then 1 else 0, count) } habit_toggle_day :: (habits: *Habits, index: s32, day_index: s32) { diff --git a/src/habits/habit_types.zi b/src/habits/habit_types.zi index 26f291567..45ffd609d 100644 --- a/src/habits/habit_types.zi +++ b/src/habits/habit_types.zi @@ -205,6 +205,9 @@ Habit :: struct { // How hard the habit is, a HABIT_DIFFICULTY_ level; each done day // earns its coins. difficulty: s32 + // Custom coins apply to each occurrence, independently of the goal. + custom_coins: bool + coin_halves: s32 // The first day whose completion earns coins, YYYYMMDD. coins_from: s32 // Every schedule the habit has had, oldest first. A changed schedule diff --git a/src/screens/habit_change_text.zi b/src/screens/habit_change_text.zi index 0624f2409..0b70ba0d4 100644 --- a/src/screens/habit_change_text.zi +++ b/src/screens/habit_change_text.zi @@ -5,6 +5,7 @@ #import, file "../habits/habit_questions.zi"; #import, file "../habits/habit_answer_stats.zi"; #import, file "../habits/habit_changes.zi"; +#import, file "../habits/habit_coins.zi"; #import, file "../app/locale.zi"; #import, file "../app/text_buffers.zi"; @@ -207,6 +208,11 @@ HabitChangeDescribe :: (change: *HabitChange, output: []u8) -> string { args[0].text = HabitDifficultyLabel(HabitAnswerNumber(before)) args[1].text = HabitDifficultyLabel(HabitAnswerNumber(after)) used = 2 + } else if change.kind == HABIT_CHANGE_COINS { + key = "habit_change_coins" + args[0].text = HabitCoinText(HabitAnswerNumber(before[2:]), first[:]) + args[1].text = HabitCoinText(HabitAnswerNumber(after[2:]), second[:]) + used = 2 } else if change.kind == HABIT_CHANGE_TRACKING { key = "habit_change_tracking" args[0].text = HabitTrackingDescribe(before, first[:]) diff --git a/src/screens/habits/edit.zi b/src/screens/habits/edit.zi index aaaefe931..b4173ce6a 100644 --- a/src/screens/habits/edit.zi +++ b/src/screens/habits/edit.zi @@ -25,6 +25,7 @@ c :: #system_library "c"; #import, file "../../app/exercise_types.zi"; #import, file "../../habits/habit_icons.zi"; #import, file "../../habits/habit_coins.zi"; +#import, file "../../habits/habit_calendar.zi"; #import, file "../habit_change_text.zi"; #import, file "coins_view.zi"; #import, file "../../habits/habit_schedule.zi"; @@ -139,11 +140,13 @@ habit_edit_begin :: (app: *InnerBreeze, index: s32) { app.habit_edit.sync_mode = app.habits.items[index].sync_mode app.habit_edit.sync_activity = app.habits.items[index].sync_activity app.habit_edit.counter_enabled = app.habits.items[index].counter_enabled - app.habit_edit.counter_target = ifx (app.habits.items[index].counter_target > 0) then (app.habits.items[index].counter_target) else (1) + app.habit_edit.counter_target = habit_counter_target(*app.habits.items[index]) app.habit_edit.schedule = HabitScheduleCurrent(*app.habits.items[index]) app.habit_edit.reminder_hour = app.habits.items[index].reminder_hour app.habit_edit.icon = app.habits.items[index].icon app.habit_edit.difficulty = app.habits.items[index].difficulty + app.habit_edit.custom_coins = app.habits.items[index].custom_coins + app.habit_edit.coin_halves = app.habits.items[index].coin_halves app.habit_edit.questions = app.habits.items[index].questions app.habit_edit.question_count = app.habits.items[index].question_count app.habit_edit.span = app.habits.items[index].span @@ -186,6 +189,7 @@ habit_edit_changed :: (app: *InnerBreeze) -> bool { edit.counter_enabled != original.counter_enabled || edit.counter_target != original.counter_target || edit.reminder_hour != original.reminder_hour || edit.icon != original.icon || edit.difficulty != original.difficulty || + edit.custom_coins != original.custom_coins || edit.coin_halves != original.coin_halves || edit.span != original.span || !habit_edit_goal_same(edit.span_goal, original.span_goal) || !HabitScheduleSame(*edit.schedule, *original.schedule) || edit.question_count != original.question_count { @@ -483,7 +487,7 @@ habit_edit_description_field :: (app: *InnerBreeze, return result.focused } -// Shows the daily target as its number; an empty or zero entry keeps the +// Shows the daily target as its number; an empty entry keeps the // last target until the field is left. habit_edit_counter_text :: (app: *InnerBreeze) { unused AppFormatS32(app.habit_edit.counter_target, @@ -525,7 +529,7 @@ habit_edit_counter_field :: (app: *InnerBreeze, index += 1 } if value > HABIT_COUNTER_TARGET_MAX { value = HABIT_COUNTER_TARGET_MAX } - if value > 0 { app.habit_edit.counter_target = value } + if typed_text.count > 0 { app.habit_edit.counter_target = value } } app.habit_edit.counter_cursor = result.cursor app.habit_edit.counter_anchor = result.anchor @@ -565,7 +569,7 @@ habit_edit_section_body :: (app: *InnerBreeze, section: s32, // The difficulty, counter mode, the span toggle and practice links, // with the target or which spans are good under their toggle, then the // questions. - height := AppScale(HABIT_EDIT_DIFFICULTY_HEIGHT + 52 + 52 + 44) + + height := AppScale(habit_edit_difficulty_height(app) + 52 + 52 + 44) + habit_edit_questions_height(app) if app.habit_edit.counter_enabled != 0 { height += AppScale(52) @@ -1341,6 +1345,7 @@ habit_edit_focus_only :: (app: *InnerBreeze, field: s32) { app.habit_edit.focused = ifx field == 1 then 1 else 0 app.habit_edit.description_focused = ifx field == 2 then 1 else 0 app.habit_edit.counter_focused = ifx field == 3 then 1 else 0 + app.habit_edit.coin_focused = ifx field == 7 then 1 else 0 app.habit_edit.formula_focused = ifx field == 4 then 1 else 0 if field != 5 { app.habit_edit.question_focused = 0 @@ -1877,7 +1882,43 @@ habit_edit_span_goal :: (app: *InnerBreeze, x: s32, y: s32, width: s32) { } // How hard the habit is, and the coins each done day earns for it. -HABIT_EDIT_DIFFICULTY_HEIGHT :: 112 +habit_edit_difficulty_height :: (app: *InnerBreeze) -> s32 { + return 164 + ifx app.habit_edit.custom_coins then 52 else 0 +} + +habit_edit_coin_field :: (app: *InnerBreeze, bounds: Rectangle) { + edit := *app.habit_edit + if edit.coin_focused == 0 { + text := HabitCoinText(edit.coin_halves, edit.coin_text[:]) + edit.coin_cursor = cast(s32)text.count + edit.coin_anchor = edit.coin_cursor + } + typed: [16]u8 + field: TextFieldProps + field.key = KeyHash("habit/edit/coins") + field.bounds = bounds + field.value = FrameTextHold(*app.ui.frame_text, + AppTextFromCString(*edit.coin_text[0], 12)) + field.cursor = edit.coin_cursor + field.anchor = edit.coin_anchor + field.scroll_x = edit.coin_scroll_x + field.focused = edit.coin_focused != 0 + field.focus_id = 7607 + field.max_bytes = 7 + field.max_codepoints = 7 + field.input = SampleTextFieldInput(field.focused, typed[:]) + result := TextField(app.ui.session, field) + if result.edit.changed && AppReplaceText(edit.coin_text[:], + result.edit.start, result.edit.end, result.edit.replacement) { + unused HabitCoinParse(AppTextFromCString(*edit.coin_text[0], 12), *edit.coin_halves) + } + edit.coin_cursor = result.cursor + edit.coin_anchor = result.anchor + edit.coin_scroll_x = result.scroll_x + edit.coin_focused = ifx result.focused then 1 else 0 + if result.focused { habit_edit_focus_only(app, 7) } + if result.clipboard_write { unused TextInputWriteClipboard(result.clipboard_text) } +} habit_edit_difficulty :: (app: *InnerBreeze, x: s32, y: s32, width: s32) { habit_edit_text(app, LocaleText("habit_difficulty_label"), @@ -1893,10 +1934,11 @@ habit_edit_difficulty :: (app: *InnerBreeze, x: s32, y: s32, width: s32) { cast(float32)width, cast(float32)AppScale(42)} props.height = AppScale(42) props.selected_index = HabitDifficultyIndex(app.habit_edit.difficulty) - props.has_selection = true + props.has_selection = !app.habit_edit.custom_coins switch := SegmentedControl(app.ui.session, props, options[:]) if switch.changed { app.habit_edit.difficulty = HabitDifficultyAt(switch.selected_index) + app.habit_edit.custom_coins = false } hint_y := y + AppScale(80) coin := AppScale(18) @@ -1906,19 +1948,45 @@ habit_edit_difficulty :: (app: *InnerBreeze, x: s32, y: s32, width: s32) { hint: TextProps hint.bounds = Rectangle.{cast(float32)(x + coin + AppScale(8)), cast(float32)hint_y, cast(float32)(width - coin - AppScale(8)), - cast(float32)AppScale(22)} - hint.text = HabitDifficultyEarns(app.habit_edit.difficulty) + cast(float32)AppScale(30)} + if app.habit_edit.custom_coins { + hint.text = LocaleText("habit_coins_signed_hint") + } else { + hint.text = HabitDifficultyEarns(app.habit_edit.difficulty) + } hint.font = AppSmallFontSize() hint.class_name = MutedTextClass() hint.vertical_align = cast(TextAlign)TextAlignCenter - hint.wrap = cast(TextWrap)TextWrapEllipsis + hint.wrap = cast(TextWrap)TextWrapAuto Text(app.ui.session, hint) + y += AppScale(112) + habit_edit_text(app, LocaleText("habit_custom_coins"), + x, y + AppScale(10), width - AppScale(110), AppScale(36)) + custom := Toggle(app.ui.session, ToggleProps.{ + .id = 7606, + .bounds = Rectangle.{cast(float32)(x + width - AppScale(100)), + cast(float32)y, cast(float32)AppScale(100), cast(float32)AppScale(36)}, + .value = app.habit_edit.custom_coins, + .off_label = LocaleText("toggle_off"), .on_label = LocaleText("toggle_on")}) + if custom.changed { + app.habit_edit.custom_coins = custom.value + if custom.value { + app.habit_edit.coin_halves = HabitDifficultyHalfCoins(app.habit_edit.difficulty) + } + } + if app.habit_edit.custom_coins { + y += AppScale(52) + habit_edit_text(app, LocaleText("habit_coins_per_occurrence"), + x, y + AppScale(10), width - AppScale(128), AppScale(36)) + habit_edit_coin_field(app, Rectangle.{cast(float32)(x + width - AppScale(120)), + cast(float32)y, cast(float32)AppScale(120), cast(float32)AppScale(44)}) + } } habit_edit_tracking :: (app: *InnerBreeze, x: s32, y: s32, width: s32, viewport_y: s32, viewport_h: s32, content_h: s32) { habit_edit_difficulty(app, x, y, width) - y += AppScale(HABIT_EDIT_DIFFICULTY_HEIGHT) + y += AppScale(habit_edit_difficulty_height(app)) counter_props := ToggleProps.{ .id = 7610, .value = app.habit_edit.counter_enabled != 0, @@ -1954,7 +2022,7 @@ habit_edit_tracking :: (app: *InnerBreeze, x: s32, y: s32, .id = 7620, .bounds = Rectangle.{cast(float32)control_x, cast(float32)y, cast(float32)AppScale(44), cast(float32)AppScale(44)}, - .label = "-", .disabled = app.habit_edit.counter_target <= 1, + .label = "-", .disabled = app.habit_edit.counter_target <= 0, .tone = cast(ButtonTone)ButtonToneNeutral, .emphasis = cast(ButtonEmphasis)ButtonEmphasisSoft}) != 0 { app.habit_edit.counter_target -= 1 diff --git a/src/screens/habits_screen.zi b/src/screens/habits_screen.zi index 108d0b536..cee31ab5a 100644 --- a/src/screens/habits_screen.zi +++ b/src/screens/habits_screen.zi @@ -371,15 +371,8 @@ habits_screen_draw_first_run_guide :: (app: *InnerBreeze) { HabitScreenCompletion :: (app: *InnerBreeze, index: s32, day_index: s32) -> bool { habit := *app.habits.items[index] - if habit_completed_day(habit, day_index) != 0 { return true } - if habit_is_linked(habit) == 0 { return false } linked := habit_cached_linked_entries(app, index, day_index) - if linked == null { return false } - if habit_counting_enabled(habit) != 0 { - return HabitEffectiveDayCount(habit, day_index, linked) >= - habit_counter_target(habit) - } - return HabitLinkedHasDay(linked, day_index) + return HabitEffectiveDayComplete(habit, day_index, linked) } HabitScreenDueToday :: (app: *InnerBreeze) -> s32 { @@ -2025,6 +2018,10 @@ HabitScreenCountDialog :: (app: *InnerBreeze) { } else if action == HABITS_COUNT_OPEN_DAY { habit_open_linked_edit_page(app, index, day_index) } else if action == HABITS_COUNT_CLOSE { + if habit_counter_target(habit) == 0 && + HabitScreenDayCount(app, index, day_index) == 0 { + unused habit_complete_day(app, index, day_index) + } app_close_modal(app) } } diff --git a/src/screens/lumi_screen.zi b/src/screens/lumi_screen.zi index fe4d80a86..91168ebd8 100644 --- a/src/screens/lumi_screen.zi +++ b/src/screens/lumi_screen.zi @@ -395,10 +395,9 @@ LumiHabitAt :: (app: *InnerBreeze, position: s32) -> LumiTask { } habit := *app.habits.items[index] day := habits_today_index() - count := HabitEffectiveDayCount(habit, day, habit_cached_linked_entries(app, index, day)) - target := ifx habit_counting_enabled(habit) != 0 then habit_counter_target(habit) else 1 return LumiTask.{.id = AppTextFromCString(*habit.id[0], HABIT_ID_SIZE), - .title = AppTextFromCString(*habit.name[0], HABIT_NAME_SIZE), .done = count >= target} + .title = AppTextFromCString(*habit.name[0], HABIT_NAME_SIZE), + .done = HabitEffectiveDayComplete(habit, day, habit_cached_linked_entries(app, index, day))} } // The habit's last two weeks, so Lumi can coach from real progress: the @@ -437,14 +436,13 @@ LumiHabitProgressAt :: (app: *InnerBreeze, position: s32) -> LumiHabitProgress { return progress } habit := *app.habits.items[index] - target := ifx habit_counting_enabled(habit) != 0 then habit_counter_target(habit) else 1 // Day 0 lists the habit's linked practice sessions on every day. linked := habit_cached_linked_entries(app, index, 0) today := habits_today_index() day := today streak_open := true for offset: cast(s32)0..LUMI_STREAK_DAYS - 1 { - done := HabitEffectiveDayCount(habit, day, linked) >= target + done := HabitEffectiveDayComplete(habit, day, linked) scheduled := habit_scheduled_day(habit, day) != 0 if offset < LUMI_PROGRESS_DAYS { if scheduled { diff --git a/src/storage/habit_sync_sql.zi b/src/storage/habit_sync_sql.zi index a512c5c43..d32ee53d8 100644 --- a/src/storage/habit_sync_sql.zi +++ b/src/storage/habit_sync_sql.zi @@ -118,43 +118,47 @@ SQL SyncHabitsSQL :: #string SQL INSERT INTO -habits(id,user_id,name,color_r,color_g,color_b,sync_mode,sync_activity,counter_enabled,counter_target,sort_order,deleted_at,updated_at,weekdays,reminder_hour,deactivated,icon,schedule,questions,span,span_goal,span_low,span_high,difficulty) +habits(id,user_id,name,color_r,color_g,color_b,sync_mode,sync_activity,counter_enabled,counter_target,sort_order,deleted_at,updated_at,weekdays,reminder_hour,deactivated,icon,schedule,questions,span,span_goal,span_low,span_high,difficulty,custom_coins,coin_halves) SELECT COALESCE(json_extract(value,'$.id'),''),?2, COALESCE(json_extract(value,'$.name'),''), -CAST(COALESCE(json_extract(value,'$.color_r'),0) AS INTEGER), -CAST(COALESCE(json_extract(value,'$.color_g'),0) AS INTEGER), -CAST(COALESCE(json_extract(value,'$.color_b'),0) AS INTEGER), -CAST(COALESCE(json_extract(value,'$.sync_mode'),0) AS INTEGER), -CAST(COALESCE(json_extract(value,'$.sync_activity'),0) AS INTEGER), +CAST(COALESCE(json_extract(value,'$.color_r'),0) AS INT), +CAST(COALESCE(json_extract(value,'$.color_g'),0) AS INT), +CAST(COALESCE(json_extract(value,'$.color_b'),0) AS INT), +CAST(COALESCE(json_extract(value,'$.sync_mode'),0) AS INT), +CAST(COALESCE(json_extract(value,'$.sync_activity'),0) AS INT), CAST(COALESCE(json_extract(value,'$.counter_enabled'), (SELECT -counter_enabled FROM habits WHERE id=COALESCE(json_extract(value,'$.id'),'')), -0) AS INTEGER), CAST(COALESCE(json_extract(value,'$.counter_target'), -(SELECT counter_target FROM habits WHERE id=COALESCE(json_extract(value,'$.id'),'')), -1) AS INTEGER), CAST(COALESCE(json_extract(value,'$.sort_order'),0) AS INTEGER), -CAST(COALESCE(json_extract(value,'$.deleted_at'),0) AS INTEGER), -CAST(COALESCE(strftime('%s',json_extract(value,'$.updated_at')),'0') AS INTEGER), +counter_enabled FROM habits WHERE id=json_extract(value,'$.id')), +0) AS INT), CAST(COALESCE(json_extract(value,'$.counter_target'), +(SELECT counter_target FROM habits WHERE id=json_extract(value,'$.id')), +1) AS INT), CAST(COALESCE(json_extract(value,'$.sort_order'),0) AS INT), +CAST(COALESCE(json_extract(value,'$.deleted_at'),0) AS INT), +CAST(COALESCE(strftime('%s',json_extract(value,'$.updated_at')),'0') AS INT), CAST(COALESCE(json_extract(value,'$.weekdays'), (SELECT weekdays FROM habits -WHERE id=COALESCE(json_extract(value,'$.id'),'')),0) AS INTEGER), +WHERE id=json_extract(value,'$.id')),0) AS INT), CAST(COALESCE(json_extract(value,'$.reminder_hour'), (SELECT reminder_hour -FROM habits WHERE id=COALESCE(json_extract(value,'$.id'),'')),-1) AS INTEGER), +FROM habits WHERE id=json_extract(value,'$.id')),-1) AS INT), CAST(COALESCE(json_extract(value,'$.deactivated'), (SELECT deactivated -FROM habits WHERE id=COALESCE(json_extract(value,'$.id'),'')),0) AS INTEGER), +FROM habits WHERE id=json_extract(value,'$.id')),0) AS INT), CAST(COALESCE(json_extract(value,'$.icon'), (SELECT icon -FROM habits WHERE id=COALESCE(json_extract(value,'$.id'),'')),0) AS INTEGER), +FROM habits WHERE id=json_extract(value,'$.id')),0) AS INT), CAST(COALESCE(json_extract(value,'$.schedule'), (SELECT schedule -FROM habits WHERE id=COALESCE(json_extract(value,'$.id'),'')),'') AS TEXT), +FROM habits WHERE id=json_extract(value,'$.id')),'') AS TEXT), CAST(COALESCE(json_extract(value,'$.questions'), (SELECT questions -FROM habits WHERE id=COALESCE(json_extract(value,'$.id'),'')),'') AS TEXT), +FROM habits WHERE id=json_extract(value,'$.id')),'') AS TEXT), CAST(COALESCE(json_extract(value,'$.span'), (SELECT span -FROM habits WHERE id=COALESCE(json_extract(value,'$.id'),'')),0) AS INTEGER), +FROM habits WHERE id=json_extract(value,'$.id')),0) AS INT), CAST(COALESCE(json_extract(value,'$.span_goal'), (SELECT span_goal -FROM habits WHERE id=COALESCE(json_extract(value,'$.id'),'')),0) AS INTEGER), +FROM habits WHERE id=json_extract(value,'$.id')),0) AS INT), CAST(COALESCE(json_extract(value,'$.span_low'), (SELECT span_low -FROM habits WHERE id=COALESCE(json_extract(value,'$.id'),'')),0) AS INTEGER), +FROM habits WHERE id=json_extract(value,'$.id')),0) AS INT), CAST(COALESCE(json_extract(value,'$.span_high'), (SELECT span_high -FROM habits WHERE id=COALESCE(json_extract(value,'$.id'),'')),0) AS INTEGER), +FROM habits WHERE id=json_extract(value,'$.id')),0) AS INT), CAST(COALESCE(json_extract(value,'$.difficulty'), (SELECT difficulty -FROM habits WHERE id=COALESCE(json_extract(value,'$.id'),'')),0) AS INTEGER) FROM (SELECT value +FROM habits WHERE id=json_extract(value,'$.id')),0) AS INT), +CAST(COALESCE(json_extract(value,'$.custom_coins'), (SELECT custom_coins +FROM habits WHERE id=json_extract(value,'$.id')),0) AS INT), +CAST(COALESCE(json_extract(value,'$.coin_halves'), (SELECT coin_halves +FROM habits WHERE id=json_extract(value,'$.id')),0) AS INT) FROM (SELECT value FROM json_each(?1,'$.changes.habits') UNION ALL SELECT value FROM json_each(?1,'$.data.habits')) WHERE COALESCE(json_extract(value,'$.id'),'')<>'' ON CONFLICT(id) DO UPDATE SET @@ -164,7 +168,8 @@ counter_enabled=excluded.counter_enabled,counter_target=excluded.counter_target, updated_at=excluded.updated_at, weekdays=excluded.weekdays,reminder_hour=excluded.reminder_hour, deactivated=excluded.deactivated,icon=excluded.icon,schedule=excluded.schedule, questions=excluded.questions,span=excluded.span,span_goal=excluded.span_goal, -span_low=excluded.span_low,span_high=excluded.span_high,difficulty=excluded.difficulty +span_low=excluded.span_low,span_high=excluded.span_high,difficulty=excluded.difficulty, +custom_coins=excluded.custom_coins,coin_halves=excluded.coin_halves WHERE excluded.updated_at > habits.updated_at OR (excluded.updated_at = habits.updated_at AND NOT EXISTS ( SELECT 1 FROM sync_outbox WHERE entity_type='habit' AND entity_id=habits.id AND local_date=0)) @@ -310,7 +315,9 @@ SELECT COALESCE(json_extract(value,'$.id'),''),?2, CAST(COALESCE(json_extract(value,'$.kind'),1) AS INTEGER), CAST(COALESCE(json_extract(value,'$.reward_id'),'') AS TEXT), CAST(COALESCE(json_extract(value,'$.name'),'') AS TEXT), -MAX(CAST(COALESCE(json_extract(value,'$.coins'),0) AS INTEGER),0), +CASE WHEN CAST(COALESCE(json_extract(value,'$.kind'),1) AS INTEGER)=2 THEN +CAST(COALESCE(json_extract(value,'$.coins'),0) AS INTEGER) +ELSE MAX(CAST(COALESCE(json_extract(value,'$.coins'),0) AS INTEGER),0) END, CAST(COALESCE(json_extract(value,'$.at'),0) AS INTEGER), CAST(COALESCE(json_extract(value,'$.deleted_at'),0) AS INTEGER), CAST(COALESCE(strftime('%s',json_extract(value,'$.updated_at')),'0') AS INTEGER) diff --git a/src/storage/import.zi b/src/storage/import.zi index 724b41bf6..6c21ea738 100644 --- a/src/storage/import.zi +++ b/src/storage/import.zi @@ -1,3 +1,4 @@ +#import, file "../habits/habit_coins.zi"; @@ -348,14 +349,14 @@ import_prepare_habit_upsert :: (stmt: **void) -> s32 { return 0 } return ifx (SqlitePrepareText(storage_db_handle(), - "INSERT OR REPLACE INTO habits(id,user_id,name,color_r,color_g,color_b,sync_mode,sync_activity,counter_enabled,counter_target,sort_order,deleted_at,updated_at) VALUES(?1,?2,COALESCE((SELECT name FROM habits WHERE id=?1),?3),?4,?5,?6,?7,?8,CASE WHEN ?9!=0 THEN 1 ELSE COALESCE((SELECT counter_enabled FROM habits WHERE id=?1),0) END,CASE WHEN ?10>0 THEN ?10 ELSE COALESCE((SELECT counter_target FROM habits WHERE id=?1),1) END,?11,0,?12)", + "INSERT OR REPLACE INTO habits(id,user_id,name,color_r,color_g,color_b,sync_mode,sync_activity,counter_enabled,counter_target,sort_order,deleted_at,updated_at,custom_coins,coin_halves) VALUES(?1,?2,COALESCE((SELECT name FROM habits WHERE id=?1),?3),?4,?5,?6,?7,?8,CASE WHEN ?9!=0 THEN 1 ELSE COALESCE((SELECT counter_enabled FROM habits WHERE id=?1),0) END,CASE WHEN ?10>=0 THEN ?10 ELSE COALESCE((SELECT counter_target FROM habits WHERE id=?1),1) END,?11,0,?12,?13,?14)", -1, stmt, null) == SQLITE_OK) then (1) else (0) } import_upsert_habit :: (stmt: *void, id: string, name: string, color: Color, sync_mode: s32, sync_activity: s32, counter_enabled: s32, counter_target: s32, - sort_order: s32, updated_at: s64) -> s32 { + custom_coins: s32, coin_halves: s32, sort_order: s32, updated_at: s64) -> s32 { rc: s32 if stmt == null || id.count == 0 || id[0] == #char "\0" || name.count == 0 || name[0] == #char "\0" { @@ -372,9 +373,11 @@ import_upsert_habit :: (stmt: *void, id: string, name: string, sqlite3_bind_int(stmt, 7, sync_mode) sqlite3_bind_int(stmt, 8, sync_activity) sqlite3_bind_int(stmt, 9, ifx (counter_enabled != 0) then (1) else (0)) - sqlite3_bind_int(stmt, 10, ifx (counter_target > 0) then (counter_target) else (1)) + sqlite3_bind_int(stmt, 10, ifx (counter_target >= 0) then (counter_target) else (1)) sqlite3_bind_int(stmt, 11, sort_order) SqliteBindInt64(stmt, 12, updated_at) + sqlite3_bind_int(stmt, 13, custom_coins) + sqlite3_bind_int(stmt, 14, HabitCoinHalvesClamp(coin_halves)) rc = SqliteStep(stmt) return ifx (rc == SQLITE_DONE) then (1) else (0) } @@ -476,7 +479,7 @@ import_tickmate_db :: (src: *void) -> s32 { } if import_upsert_habit(write_stmt, AppTextFromCString(*local_habit_id[0], 37), name, color, HABIT_SYNC_NONE, 0, counter_enabled, - 1, sort_order, imported_at) != 0 { + 1, 0, 0, sort_order, imported_at) != 0 { ok = 1 } } @@ -735,16 +738,20 @@ import_sqlite_db_file :: (db_path: string, mode: StorageImportMode) -> s32 { } else { day_sql = "SELECT local_date,completed,CASE WHEN completed!=0 THEN 1 ELSE 0 END FROM habit_days WHERE habit_id=?1" } - if has_sync_activity != 0 && has_counter_enabled != 0 && has_counter_target != 0 { - habit_sql = "SELECT id,name,color_r,color_g,color_b,sync_mode,sync_activity,counter_enabled,counter_target,sort_order FROM habits WHERE deleted_at=0 ORDER BY sort_order,id" + if has_sync_activity != 0 && has_counter_enabled != 0 && has_counter_target != 0 && + source_table_has_column(src, "habits", "custom_coins") != 0 && + source_table_has_column(src, "habits", "coin_halves") != 0 { + habit_sql = "SELECT id,name,color_r,color_g,color_b,sync_mode,sync_activity,counter_enabled,counter_target,sort_order,custom_coins,coin_halves FROM habits WHERE deleted_at=0 ORDER BY sort_order,id" + } else if has_sync_activity != 0 && has_counter_enabled != 0 && has_counter_target != 0 { + habit_sql = "SELECT id,name,color_r,color_g,color_b,sync_mode,sync_activity,counter_enabled,counter_target,sort_order,0,0 FROM habits WHERE deleted_at=0 ORDER BY sort_order,id" } else if has_sync_activity != 0 && has_counter_enabled != 0 { - habit_sql = "SELECT id,name,color_r,color_g,color_b,sync_mode,sync_activity,counter_enabled,1,sort_order FROM habits WHERE deleted_at=0 ORDER BY sort_order,id" + habit_sql = "SELECT id,name,color_r,color_g,color_b,sync_mode,sync_activity,counter_enabled,1,sort_order,0,0 FROM habits WHERE deleted_at=0 ORDER BY sort_order,id" } else if has_sync_activity != 0 { - habit_sql = "SELECT id,name,color_r,color_g,color_b,sync_mode,sync_activity,0,1,sort_order FROM habits WHERE deleted_at=0 ORDER BY sort_order,id" + habit_sql = "SELECT id,name,color_r,color_g,color_b,sync_mode,sync_activity,0,1,sort_order,0,0 FROM habits WHERE deleted_at=0 ORDER BY sort_order,id" } else if has_counter_enabled != 0 { - habit_sql = "SELECT id,name,color_r,color_g,color_b,sync_mode,0,counter_enabled,1,sort_order FROM habits WHERE deleted_at=0 ORDER BY sort_order,id" + habit_sql = "SELECT id,name,color_r,color_g,color_b,sync_mode,0,counter_enabled,1,sort_order,0,0 FROM habits WHERE deleted_at=0 ORDER BY sort_order,id" } else { - habit_sql = "SELECT id,name,color_r,color_g,color_b,sync_mode,0,0,1,sort_order FROM habits WHERE deleted_at=0 ORDER BY sort_order,id" + habit_sql = "SELECT id,name,color_r,color_g,color_b,sync_mode,0,0,1,sort_order,0,0 FROM habits WHERE deleted_at=0 ORDER BY sort_order,id" } if SqlitePrepareText(cast(*void)src, habit_sql, -1, *stmt, null) == SQLITE_OK && import_prepare_habit_upsert(*habit_write_stmt) != 0 && @@ -773,6 +780,7 @@ import_sqlite_db_file :: (db_path: string, mode: StorageImportMode) -> s32 { if import_upsert_habit(habit_write_stmt, AppTextFromCString(*local_habit_id[0], 37), name, color, sqlite3_column_int(stmt, 5), sync_activity, counter_enabled, counter_target, + sqlite3_column_int(stmt, 10), sqlite3_column_int(stmt, 11), sort_order, imported_at) != 0 { ok = 1 } diff --git a/src/storage/schema.zi b/src/storage/schema.zi index 2da76d943..244eb8189 100644 --- a/src/storage/schema.zi +++ b/src/storage/schema.zi @@ -238,6 +238,9 @@ migrate_schema :: () -> s32 { if !SchemaExec(SchemaHabitWallet) { return SchemaUpgradeFailed() } + if !SchemaHasColumn("habits", "custom_coins") && !SchemaExec(SchemaHabitCustomCoins) { + return SchemaUpgradeFailed() + } if !SchemaHasColumn("habit_rewards", "icon") && !SchemaExec(SchemaHabitRewardIcons) { return SchemaUpgradeFailed() } diff --git a/src/storage/schema_sql.zi b/src/storage/schema_sql.zi index 5898c54b0..19ff02273 100644 --- a/src/storage/schema_sql.zi +++ b/src/storage/schema_sql.zi @@ -253,6 +253,11 @@ SQL // Habits from before coins earn from the day this version first opens, // and go to the account again so every device takes the same day; work // already queued keeps its place. +SchemaHabitCustomCoins :: #string SQL +ALTER TABLE habits ADD COLUMN custom_coins INTEGER NOT NULL DEFAULT 0; +ALTER TABLE habits ADD COLUMN coin_halves INTEGER NOT NULL DEFAULT 0; +SQL + SchemaHabitCoins :: #string SQL ALTER TABLE habits ADD COLUMN difficulty INTEGER NOT NULL DEFAULT 0; ALTER TABLE habits ADD COLUMN coins_from INTEGER NOT NULL DEFAULT 0; diff --git a/src/storage/storage_core.zi b/src/storage/storage_core.zi index 3de518a2e..4140e2e80 100644 --- a/src/storage/storage_core.zi +++ b/src/storage/storage_core.zi @@ -160,7 +160,7 @@ STORAGE_SYNC_ZERO_HABIT_DAY_REPAIR_KEY :: "sync_zero_habit_day_repair_v1_done" // and its sync position then moves past that record. Raise this whenever // synced records gain fields: a device whose records were received by an // older version downloads them all again once, so it gets every field. -STORAGE_SYNC_RECORD_FIELDS :: 4 +STORAGE_SYNC_RECORD_FIELDS :: 5 STORAGE_SYNC_RECORD_FIELDS_KEY :: "sync_record_fields" // Whether this device's records may still lack fields an older version diff --git a/src/storage/storage_habit_wallet.zi b/src/storage/storage_habit_wallet.zi index 105b6e6dd..1cb9ee3f3 100644 --- a/src/storage/storage_habit_wallet.zi +++ b/src/storage/storage_habit_wallet.zi @@ -22,33 +22,73 @@ sqlite3_column_int :: (statement: *void, column: s32) -> s32 #foreign c "sqlite3 // replaced. A day is done as the habit list shows it: counted to its // target, with linked practice sessions as the floor, or marked. StorageHabitEarnedHalvesSQL :: #string SQL -SELECT COALESCE(SUM(CASE WHEN e.level=3 THEN 1 ELSE 2+2*MIN(MAX(e.level,0),2) END),0) -FROM (SELECT COALESCE((SELECT CAST(c.old_value AS INTEGER) -FROM habit_changes c WHERE c.habit_id=h.id AND c.kind=19 AND c.deleted_at=0 AND +WITH days AS ( +SELECT h.id,h.name,h.icon,d.local_date AS day, +h.custom_coins,h.coin_halves, +COALESCE((SELECT c.old_value FROM habit_changes c +WHERE c.habit_id=h.id AND c.kind=20 AND c.deleted_at=0 AND CAST(strftime('%Y%m%d',c.changed_at,'unixepoch','localtime') AS INTEGER)>d.local_date -ORDER BY c.changed_at,c.rowid LIMIT 1),h.difficulty) AS level -FROM habit_days d JOIN habits h ON h.id=d.habit_id -WHERE h.user_id=?1 AND h.deleted_at=0 AND (?2='' OR h.id=?2) AND h.coins_from>0 AND -d.local_date>=h.coins_from AND CASE WHEN h.counter_enabled<>0 THEN +ORDER BY c.changed_at,c.rowid LIMIT 1),'') AS old_coins, +COALESCE((SELECT CAST(c.old_value AS INTEGER) FROM habit_changes c +WHERE c.habit_id=h.id AND c.kind=19 AND c.deleted_at=0 AND +CAST(strftime('%Y%m%d',c.changed_at,'unixepoch','localtime') AS INTEGER)>d.local_date +ORDER BY c.changed_at,c.rowid LIMIT 1),h.difficulty) AS level, +MAX(d.count,d.session_count,CASE WHEN d.completed<>0 AND +NOT(h.counter_enabled<>0 AND h.counter_target=0) THEN 1 ELSE 0 END) AS occurrences, +CASE WHEN h.counter_enabled<>0 AND h.counter_target=0 THEN +(d.completed<>0 AND MAX(d.count,d.session_count)=0) +WHEN h.counter_enabled<>0 THEN MAX(d.count,d.session_count,CASE WHEN d.completed<>0 THEN 1 ELSE 0 END)>=MAX(h.counter_target,1) -ELSE d.completed<>0 OR d.count>0 OR d.session_count>0 END) e +ELSE d.completed<>0 OR d.count>0 OR d.session_count>0 END AS done +FROM habit_days d JOIN habits h ON h.id=d.habit_id +WHERE h.user_id=?1 AND h.deleted_at=0 AND h.coins_from>0 AND d.local_date>=h.coins_from +), valued AS ( +SELECT *,CASE WHEN substr(old_coins,1,1)='1' THEN old_coins +WHEN old_coins='' AND custom_coins<>0 THEN +'1:'||CAST(MIN(MAX(coin_halves,-19998),19998) AS TEXT) +ELSE '0:'||CAST(CASE WHEN level=3 THEN 1 ELSE 2+2*MIN(MAX(level,0),2) END AS TEXT) +END AS policy FROM days +), earned AS ( +SELECT id,name,icon,day,CAST(substr(policy,3) AS INTEGER)* +CASE WHEN substr(policy,1,1)='1' THEN occurrences ELSE done END AS halves FROM valued +) +SELECT COALESCE(SUM(halves),0) FROM earned WHERE (?2='' OR id=?2) SQL -// The latest coin movements, newest first: each done day as the balance -// counts it (StorageHabitEarnedHalvesSQL) and each reward bought, with the -// habit's or reward's name and symbol and its local date. +// Each day's signed earnings and purchases, newest first. StorageHabitActivitySQL :: #string SQL -SELECT name,icon,halves,day FROM ( -SELECT e.name AS name,e.icon AS icon,CASE WHEN e.level=3 THEN 1 ELSE 2+2*MIN(MAX(e.level,0),2) END AS halves,e.day AS day,0 AS at -FROM (SELECT h.name AS name,h.icon AS icon,d.local_date AS day,COALESCE((SELECT CAST(c.old_value AS INTEGER) -FROM habit_changes c WHERE c.habit_id=h.id AND c.kind=19 AND c.deleted_at=0 AND +WITH days AS ( +SELECT h.id,h.name,h.icon,d.local_date AS day, +h.custom_coins,h.coin_halves, +COALESCE((SELECT c.old_value FROM habit_changes c +WHERE c.habit_id=h.id AND c.kind=20 AND c.deleted_at=0 AND CAST(strftime('%Y%m%d',c.changed_at,'unixepoch','localtime') AS INTEGER)>d.local_date -ORDER BY c.changed_at,c.rowid LIMIT 1),h.difficulty) AS level -FROM habit_days d JOIN habits h ON h.id=d.habit_id -WHERE h.user_id=?1 AND h.deleted_at=0 AND h.coins_from>0 AND -d.local_date>=h.coins_from AND CASE WHEN h.counter_enabled<>0 THEN +ORDER BY c.changed_at,c.rowid LIMIT 1),'') AS old_coins, +COALESCE((SELECT CAST(c.old_value AS INTEGER) FROM habit_changes c +WHERE c.habit_id=h.id AND c.kind=19 AND c.deleted_at=0 AND +CAST(strftime('%Y%m%d',c.changed_at,'unixepoch','localtime') AS INTEGER)>d.local_date +ORDER BY c.changed_at,c.rowid LIMIT 1),h.difficulty) AS level, +MAX(d.count,d.session_count,CASE WHEN d.completed<>0 AND +NOT(h.counter_enabled<>0 AND h.counter_target=0) THEN 1 ELSE 0 END) AS occurrences, +CASE WHEN h.counter_enabled<>0 AND h.counter_target=0 THEN +(d.completed<>0 AND MAX(d.count,d.session_count)=0) +WHEN h.counter_enabled<>0 THEN MAX(d.count,d.session_count,CASE WHEN d.completed<>0 THEN 1 ELSE 0 END)>=MAX(h.counter_target,1) -ELSE d.completed<>0 OR d.count>0 OR d.session_count>0 END) e +ELSE d.completed<>0 OR d.count>0 OR d.session_count>0 END AS done +FROM habit_days d JOIN habits h ON h.id=d.habit_id +WHERE h.user_id=?1 AND h.deleted_at=0 AND h.coins_from>0 AND d.local_date>=h.coins_from +), valued AS ( +SELECT *,CASE WHEN substr(old_coins,1,1)='1' THEN old_coins +WHEN old_coins='' AND custom_coins<>0 THEN +'1:'||CAST(MIN(MAX(coin_halves,-19998),19998) AS TEXT) +ELSE '0:'||CAST(CASE WHEN level=3 THEN 1 ELSE 2+2*MIN(MAX(level,0),2) END AS TEXT) +END AS policy FROM days +), earned AS ( +SELECT id,name,icon,day,CAST(substr(policy,3) AS INTEGER)* +CASE WHEN substr(policy,1,1)='1' THEN occurrences ELSE done END AS halves FROM valued +) +SELECT name,icon,halves,day FROM ( +SELECT name,icon,halves,day,0 AS at FROM earned WHERE halves<>0 UNION ALL SELECT c.name,COALESCE(r.icon,0),-2*c.coins, CAST(strftime('%Y%m%d',c.at,'unixepoch','localtime') AS INTEGER),c.at @@ -124,7 +164,7 @@ storage_habit_wallet_halves :: () -> s64 { storage_habit_coins_keep :: (habit_id: string, at: s64) -> s32 { // A kept record holds whole coins; an odd half coin goes with the habit. earned := storage_habit_earned_halves(habit_id) / 2 - if earned <= 0 || habit_id.count == 0 { + if earned == 0 || habit_id.count == 0 { return 1 } id: [HABIT_REWARD_ID_SIZE]u8 @@ -133,7 +173,7 @@ storage_habit_coins_keep :: (habit_id: string, at: s64) -> s32 { } stored_id := AppTextFromCString(*id[0], HABIT_REWARD_ID_SIZE) stmt: *void = null - sql := "INSERT INTO habit_coins(id,user_id,kind,reward_id,name,coins,at,deleted_at,updated_at) VALUES(?1,?2,2,'',COALESCE((SELECT name FROM habits WHERE id=?3),''),?4,?5,0,?5) ON CONFLICT(id) DO UPDATE SET name=excluded.name,coins=MAX(habit_coins.coins,excluded.coins),deleted_at=0,updated_at=MAX(habit_coins.updated_at+1,excluded.updated_at)" + sql := "INSERT INTO habit_coins(id,user_id,kind,reward_id,name,coins,at,deleted_at,updated_at) VALUES(?1,?2,2,'',COALESCE((SELECT name FROM habits WHERE id=?3),''),?4,?5,0,?5) ON CONFLICT(id) DO UPDATE SET name=excluded.name,coins=excluded.coins,deleted_at=0,updated_at=MAX(habit_coins.updated_at+1,excluded.updated_at)" if SqlitePrepareText(storage_db_handle(), sql, -1, *stmt, null) != SQLITE_OK { return 0 } diff --git a/src/storage/storage_habits.zi b/src/storage/storage_habits.zi index 38593d2c5..32906205e 100644 --- a/src/storage/storage_habits.zi +++ b/src/storage/storage_habits.zi @@ -6,6 +6,7 @@ c :: #system_library "c"; #import, file "../habits/habit_types.zi"; #import, file "../habits/habit_memory.zi"; #import, file "../habits/habit_days.zi"; +#import, file "../habits/habit_calendar.zi"; #import, file "../habits/habit_schedule.zi"; #import, file "../habits/habit_questions.zi"; #import, file "../habits/habit_answer_stats.zi"; @@ -585,7 +586,7 @@ storage_habit_settings_row :: (habit: *Habit, stmt: *void) { habit.counter_enabled = 0 } habit.counter_target = sqlite3_column_int(stmt, 9) - if habit.counter_target < 1 { + if habit.counter_target < 0 { habit.counter_target = 1 } habit.weekdays = sqlite3_column_int(stmt, 10) @@ -612,6 +613,8 @@ storage_habit_settings_row :: (habit: *Habit, stmt: *void) { } habit.difficulty = HabitDifficultyClamp(sqlite3_column_int(stmt, 20)) habit.coins_from = sqlite3_column_int(stmt, 21) + habit.custom_coins = sqlite3_column_int(stmt, 22) != 0 + habit.coin_halves = HabitCoinHalvesClamp(sqlite3_column_int(stmt, 23)) } // The goals a span habit's lengths take: any of a number's. @@ -625,7 +628,7 @@ storage_habit_settings_load :: (habit_id: string, habit: *Habit) -> bool { habit.* = Habit.{} stmt: *void = null if storage_db_handle() == null || SqlitePrepareText(storage_db_handle(), - "SELECT id,name,description,color_r,color_g,color_b,sync_mode,sync_activity,counter_enabled,counter_target,weekdays,reminder_hour,deactivated,icon,schedule,questions,span,span_goal,span_low,span_high,difficulty,coins_from FROM habits WHERE id=?1 AND deleted_at=0", + "SELECT id,name,description,color_r,color_g,color_b,sync_mode,sync_activity,counter_enabled,counter_target,weekdays,reminder_hour,deactivated,icon,schedule,questions,span,span_goal,span_low,span_high,difficulty,coins_from,custom_coins,coin_halves FROM habits WHERE id=?1 AND deleted_at=0", -1, *stmt, null) != SQLITE_OK { return false } @@ -648,7 +651,7 @@ storage_habits_load :: (habits_ptr: *void) -> s32 { } habits_free(habits) habits.* = Habits.{} - if SqlitePrepareText(storage_db_handle(), "SELECT id,name,description,color_r,color_g,color_b,sync_mode,sync_activity,counter_enabled,counter_target,weekdays,reminder_hour,deactivated,icon,schedule,questions,span,span_goal,span_low,span_high,difficulty,coins_from FROM habits WHERE deleted_at=0 ORDER BY sort_order,id LIMIT 32", + if SqlitePrepareText(storage_db_handle(), "SELECT id,name,description,color_r,color_g,color_b,sync_mode,sync_activity,counter_enabled,counter_target,weekdays,reminder_hour,deactivated,icon,schedule,questions,span,span_goal,span_low,span_high,difficulty,coins_from,custom_coins,coin_halves FROM habits WHERE deleted_at=0 ORDER BY sort_order,id LIMIT 32", -1, *stmt, null) != SQLITE_OK { return 0 } @@ -689,7 +692,8 @@ storage_habits_load :: (habits_ptr: *void) -> s32 { habits.items[i].days[d].completed = sqlite3_column_int(stmt, 1) habits.items[i].days[d].count = sqlite3_column_int(stmt, 2) habits.items[i].days[d].session_count = sqlite3_column_int(stmt, 3) - if habits.items[i].days[d].count <= 0 && habits.items[i].days[d].completed != 0 { + if habits.items[i].days[d].count <= 0 && habits.items[i].days[d].completed != 0 && + !(habits.items[i].counter_enabled != 0 && habits.items[i].counter_target == 0) { habits.items[i].days[d].count = 1 } } @@ -887,6 +891,10 @@ storage_habit_merge :: (local: *Habit, base: *Habit, stored: *Habit) { if local.deactivated != base.deactivated { merged.deactivated = local.deactivated } if local.icon != base.icon { merged.icon = local.icon } if local.difficulty != base.difficulty { merged.difficulty = local.difficulty } + if local.custom_coins != base.custom_coins || local.coin_halves != base.coin_halves { + merged.custom_coins = local.custom_coins + merged.coin_halves = local.coin_halves + } local_schedule: [HABIT_SCHEDULE_TEXT_SIZE]u8 base_schedule: [HABIT_SCHEDULE_TEXT_SIZE]u8 if storage_habit_schedule_text(local, local_schedule[:]) != storage_habit_schedule_text(base, base_schedule[:]) { @@ -1037,7 +1045,7 @@ storage_habits_save :: (habits_ptr: *void) { AppCopyText("INSERT OR IGNORE INTO sync_loaded_habits(id) VALUES(?1)", sql_hbp1[:]) SqlitePrepare(storage_db_handle(), *sql_hbp1[0], -1, *loaded_stmt, null) sql_hbq1: [2400] u8 - AppCopyText("INSERT INTO habits(id,user_id,name,description,color_r,color_g,color_b,sync_mode,sync_activity,counter_enabled,counter_target,sort_order,deleted_at,updated_at,weekdays,reminder_hour,deactivated,icon,schedule,questions,span,span_goal,span_low,span_high,difficulty,coins_from) VALUES(?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,0,?13,?14,?15,?16,?17,?18,?19,?20,?21,?22,?23,?24,CASE WHEN ?25>0 THEN ?25 ELSE CAST(strftime('%Y%m%d','now','localtime') AS INTEGER) END) ON CONFLICT(id) DO UPDATE SET user_id=excluded.user_id,name=excluded.name,description=excluded.description,color_r=excluded.color_r,color_g=excluded.color_g,color_b=excluded.color_b,sync_mode=excluded.sync_mode,sync_activity=excluded.sync_activity,counter_enabled=excluded.counter_enabled,counter_target=excluded.counter_target,sort_order=excluded.sort_order,deleted_at=0,updated_at=excluded.updated_at,weekdays=excluded.weekdays,reminder_hour=excluded.reminder_hour,deactivated=excluded.deactivated,icon=excluded.icon,schedule=excluded.schedule,questions=excluded.questions,span=excluded.span,span_goal=excluded.span_goal,span_low=excluded.span_low,span_high=excluded.span_high,difficulty=excluded.difficulty,coins_from=excluded.coins_from WHERE habits.user_id<>excluded.user_id OR habits.name<>excluded.name OR habits.color_r<>excluded.color_r OR habits.color_g<>excluded.color_g OR habits.color_b<>excluded.color_b OR habits.sync_mode<>excluded.sync_mode OR habits.sync_activity<>excluded.sync_activity OR habits.counter_enabled<>excluded.counter_enabled OR habits.counter_target<>excluded.counter_target OR habits.sort_order<>excluded.sort_order OR habits.deleted_at<>0 OR habits.weekdays<>excluded.weekdays OR habits.reminder_hour<>excluded.reminder_hour OR habits.deactivated<>excluded.deactivated OR habits.icon<>excluded.icon OR habits.schedule<>excluded.schedule OR habits.questions<>excluded.questions OR habits.span<>excluded.span OR habits.span_goal<>excluded.span_goal OR habits.span_low<>excluded.span_low OR habits.span_high<>excluded.span_high OR habits.difficulty<>excluded.difficulty OR habits.coins_from<>excluded.coins_from", sql_hbq1[:]) + AppCopyText("INSERT INTO habits(id,user_id,name,description,color_r,color_g,color_b,sync_mode,sync_activity,counter_enabled,counter_target,sort_order,deleted_at,updated_at,weekdays,reminder_hour,deactivated,icon,schedule,questions,span,span_goal,span_low,span_high,difficulty,coins_from,custom_coins,coin_halves) VALUES(?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,0,?13,?14,?15,?16,?17,?18,?19,?20,?21,?22,?23,?24,CASE WHEN ?25>0 THEN ?25 ELSE CAST(strftime('%Y%m%d','now','localtime') AS INTEGER) END,?26,?27) ON CONFLICT(id) DO UPDATE SET user_id=excluded.user_id,name=excluded.name,description=excluded.description,color_r=excluded.color_r,color_g=excluded.color_g,color_b=excluded.color_b,sync_mode=excluded.sync_mode,sync_activity=excluded.sync_activity,counter_enabled=excluded.counter_enabled,counter_target=excluded.counter_target,sort_order=excluded.sort_order,deleted_at=0,updated_at=excluded.updated_at,weekdays=excluded.weekdays,reminder_hour=excluded.reminder_hour,deactivated=excluded.deactivated,icon=excluded.icon,schedule=excluded.schedule,questions=excluded.questions,span=excluded.span,span_goal=excluded.span_goal,span_low=excluded.span_low,span_high=excluded.span_high,difficulty=excluded.difficulty,coins_from=excluded.coins_from,custom_coins=excluded.custom_coins,coin_halves=excluded.coin_halves WHERE habits.user_id<>excluded.user_id OR habits.name<>excluded.name OR habits.color_r<>excluded.color_r OR habits.color_g<>excluded.color_g OR habits.color_b<>excluded.color_b OR habits.sync_mode<>excluded.sync_mode OR habits.sync_activity<>excluded.sync_activity OR habits.counter_enabled<>excluded.counter_enabled OR habits.counter_target<>excluded.counter_target OR habits.sort_order<>excluded.sort_order OR habits.deleted_at<>0 OR habits.weekdays<>excluded.weekdays OR habits.reminder_hour<>excluded.reminder_hour OR habits.deactivated<>excluded.deactivated OR habits.icon<>excluded.icon OR habits.schedule<>excluded.schedule OR habits.questions<>excluded.questions OR habits.span<>excluded.span OR habits.span_goal<>excluded.span_goal OR habits.span_low<>excluded.span_low OR habits.span_high<>excluded.span_high OR habits.difficulty<>excluded.difficulty OR habits.coins_from<>excluded.coins_from OR habits.custom_coins<>excluded.custom_coins OR habits.coin_halves<>excluded.coin_halves", sql_hbq1[:]) SqlitePrepare(storage_db_handle(), *sql_hbq1[0], -1, *habit_stmt, null) sql_hbq2: [72] u8 AppCopyText("UPDATE habits SET description=?2 WHERE id=?1 AND description<>?2", sql_hbq2[:]) @@ -1095,7 +1103,7 @@ storage_habits_save :: (habits_ptr: *void) { sqlite3_bind_int(habit_stmt, 8, habit.sync_mode) sqlite3_bind_int(habit_stmt, 9, habit.sync_activity) sqlite3_bind_int(habit_stmt, 10, ifx (habit.counter_enabled != 0) then (1) else (0)) - sqlite3_bind_int(habit_stmt, 11, ifx (habit.counter_target > 0) then (habit.counter_target) else (1)) + sqlite3_bind_int(habit_stmt, 11, habit_counter_target(habit)) sqlite3_bind_int(habit_stmt, 12, i) SqliteBindInt64(habit_stmt, 13, changed_at) sqlite3_bind_int(habit_stmt, 14, habit.weekdays & 0xff) @@ -1123,6 +1131,8 @@ storage_habits_save :: (habits_ptr: *void) { sqlite3_bind_int(habit_stmt, 23, span_goal.high) sqlite3_bind_int(habit_stmt, 24, HabitDifficultyClamp(habit.difficulty)) sqlite3_bind_int(habit_stmt, 25, habit.coins_from) + sqlite3_bind_int(habit_stmt, 26, ifx habit.custom_coins then 1 else 0) + sqlite3_bind_int(habit_stmt, 27, HabitCoinHalvesClamp(habit.coin_halves)) if SqliteStep(habit_stmt) == SQLITE_DONE && sqlite3_changes(storage_db_handle()) > 0 { storage_enqueue_sync_habit(AppTextFromCString(*habit.id[0], 40)) if !stored { AchievementMarkLive("habit.created") } @@ -1158,7 +1168,7 @@ storage_habits_save :: (habits_ptr: *void) { sqlite3_bind_int(day_stmt, 3, ifx (habit.days[d].count > 0 || habit.days[d].completed != 0) then (1) else (0)) sqlite3_bind_int(day_stmt, 4, - ifx (habit.days[d].count > 0) then (habit.days[d].count) else ((ifx (habit.days[d].completed != 0) then (1) else (0)))) + HabitDayCount(habit, habit.days[d].day_index)) SqliteBindInt64(day_stmt, 5, changed_at) SqliteStep(day_stmt) storage_enqueue_sync_habit_day(AppTextFromCString(*habit.id[0], 40), habit.days[d].day_index) diff --git a/src/storage/sync_record_codec.zi b/src/storage/sync_record_codec.zi index 20835a533..195376ba7 100644 --- a/src/storage/sync_record_codec.zi +++ b/src/storage/sync_record_codec.zi @@ -69,6 +69,8 @@ storage_append_habit_row_json :: (json_handle: s64, stmt_handle: s64) { storage_json_append_int_field(json, "span_high", cast(s64)sqlite3_column_int(stmt, 21)) storage_json_append_int_field(json, "difficulty", cast(s64)sqlite3_column_int(stmt, 22)) storage_json_append_int_field(json, "coins_from", cast(s64)sqlite3_column_int(stmt, 23)) + storage_json_append_int_field(json, "custom_coins", cast(s64)sqlite3_column_int(stmt, 24)) + storage_json_append_int_field(json, "coin_halves", cast(s64)sqlite3_column_int(stmt, 25)) storage_json_builder_append_text(json, "}") } @@ -330,7 +332,7 @@ storage_append_dated_payload_json :: (json: *StorageJsonBuilder, sql: string, id storage_append_habit_payload_json :: (json: *StorageJsonBuilder, habit_id: string) -> s32 { return storage_append_id_payload_json( json, - "SELECT id,name,color_r,color_g,color_b,sync_mode,sync_activity,counter_enabled,counter_target,sort_order,deleted_at,updated_at,weekdays,reminder_hour,deactivated,icon,schedule,questions,span,span_goal,span_low,span_high,difficulty,coins_from FROM habits WHERE user_id=?1 AND id=?2", + "SELECT id,name,color_r,color_g,color_b,sync_mode,sync_activity,counter_enabled,counter_target,sort_order,deleted_at,updated_at,weekdays,reminder_hour,deactivated,icon,schedule,questions,span,span_goal,span_low,span_high,difficulty,coins_from,custom_coins,coin_halves FROM habits WHERE user_id=?1 AND id=?2", habit_id, storage_append_habit_row_json) } diff --git a/tests/habit_calendar_behavior.zi b/tests/habit_calendar_behavior.zi index 0b3aa9cc6..d627d0dfc 100644 --- a/tests/habit_calendar_behavior.zi +++ b/tests/habit_calendar_behavior.zi @@ -25,7 +25,7 @@ ScheduleAnswer :: () -> s32 { rule.every = 2 rule.start = 20261013 if Planned(*rule, 20261013) != 1 || Planned(*rule, 20261014) != 0 || - Planned(*rule, 20261015) != 1 || Planned(*rule, 20261011) != 0 { + Planned(*rule, 20261015) != 1 || Planned(*rule, 20261011) != 0 { return 101 } // Monday, Wednesday and Thursday every week. @@ -34,15 +34,15 @@ ScheduleAnswer :: () -> s32 { rule.every = 1 rule.weekdays = 1 + 4 + 8 if Planned(*rule, 20261012) != 1 || Planned(*rule, 20261013) != 0 || - Planned(*rule, 20261014) != 1 || Planned(*rule, 20261015) != 1 || - Planned(*rule, 20261018) != 0 { + Planned(*rule, 20261014) != 1 || Planned(*rule, 20261015) != 1 || + Planned(*rule, 20261018) != 0 { return 102 } rule.every = 2 rule.weekdays = 1 rule.start = 20261012 if Planned(*rule, 20261012) != 1 || Planned(*rule, 20261019) != 0 || - Planned(*rule, 20261026) != 1 { + Planned(*rule, 20261026) != 1 { return 103 } // The 1st, the 15th and the 31st, which is a shorter month's last day. @@ -51,8 +51,8 @@ ScheduleAnswer :: () -> s32 { rule.every = 1 rule.month_days = 1 + (1 << 14) + (1 << 30) if Planned(*rule, 20261015) != 1 || Planned(*rule, 20261016) != 0 || - Planned(*rule, 20260228) != 1 || Planned(*rule, 20260227) != 0 || - Planned(*rule, 20261101) != 1 { + Planned(*rule, 20260228) != 1 || Planned(*rule, 20260227) != 0 || + Planned(*rule, 20261101) != 1 { return 104 } rule.month_days = 0 @@ -71,32 +71,32 @@ ScheduleAnswer :: () -> s32 { rule.every = 2 rule.start = 20241206 if Planned(*rule, 20261206) != 1 || Planned(*rule, 20261205) != 0 || - Planned(*rule, 20251206) != 0 { + Planned(*rule, 20251206) != 0 { return 107 } rule = HabitSchedule.{} rule.repeat = HABIT_REPEAT_FORMULA rule.start = 20261013 if !HabitScheduleSetFormula(*rule, "days % 3 == 0") || - Planned(*rule, 20261016) != 1 || Planned(*rule, 20261014) != 0 { + Planned(*rule, 20261016) != 1 || Planned(*rule, 20261014) != 0 { return 108 } rule.start = 20260101 if !HabitScheduleSetFormula(*rule, "weekday <= 5 and nth = 1") || - Planned(*rule, 20261001) != 1 || Planned(*rule, 20261003) != 0 || - Planned(*rule, 20261008) != 0 { + Planned(*rule, 20261001) != 1 || Planned(*rule, 20261003) != 0 || + Planned(*rule, 20261008) != 0 { return 109 } if !HabitScheduleSetFormula(*rule, "daysleft == 0 || (month - 1) % 3 == 0 && day == 1") || - Planned(*rule, 20261031) != 1 || Planned(*rule, 20261001) != 1 || - Planned(*rule, 20261101) != 0 { + Planned(*rule, 20261031) != 1 || Planned(*rule, 20261001) != 1 || + Planned(*rule, 20261101) != 0 { return 110 } if !HabitFormulaValid("not (weekday = 6 or weekday = 7)") || - !HabitFormulaValid("-days / 2 >= -3") || - HabitFormulaValid("days %% 3") || HabitFormulaValid("hours == 1") || - HabitFormulaValid("(days") || HabitFormulaValid("") || - HabitFormulaValid("days 3") || HabitFormulaValid("dayswhere") { + !HabitFormulaValid("-days / 2 >= -3") || + HabitFormulaValid("days %% 3") || HabitFormulaValid("hours == 1") || + HabitFormulaValid("(days") || HabitFormulaValid("") || + HabitFormulaValid("days 3") || HabitFormulaValid("dayswhere") { return 111 } rule.repeat = HABIT_REPEAT_NONE @@ -114,8 +114,8 @@ HistoryAnswer :: () -> s32 { weekly.repeat = HABIT_REPEAT_WEEKLY weekly.weekdays = 1 if !HabitScheduleSet(*fresh, weekly, 20261013, false) || - fresh.schedule_count != 1 || - habit_scheduled_day(*fresh, 20261006) != 0 { + fresh.schedule_count != 1 || + habit_scheduled_day(*fresh, 20261006) != 0 { return 200 } habit: Habit @@ -128,31 +128,31 @@ HistoryAnswer :: () -> s32 { if !HabitScheduleSet(*habit, weekly, 20261013, false) { return 201 } if habit.schedule_count != 2 || habit.weekdays != 1 { return 202 } if habit_scheduled_day(*habit, 20261006) != 1 || - habit_scheduled_day(*habit, 20261014) != 0 || - habit_scheduled_day(*habit, 20261019) != 1 { + habit_scheduled_day(*habit, 20261014) != 0 || + habit_scheduled_day(*habit, 20261019) != 1 { return 203 } if HabitScheduleSet(*habit, weekly, 20261013, false) { return 204 } daily := HabitScheduleFromWeekdays(0) if !HabitScheduleSet(*habit, daily, 20261013, false) || - habit.schedule_count != 1 || habit.weekdays != 0 { + habit.schedule_count != 1 || habit.weekdays != 0 { return 205 } if !HabitScheduleSet(*habit, weekly, 20261013, false) || - !HabitScheduleSet(*habit, daily, 20261020, false) || - habit.schedule_count != 3 { + !HabitScheduleSet(*habit, daily, 20261020, false) || + habit.schedule_count != 3 { return 206 } if habit_scheduled_day(*habit, 20261006) != 1 || - habit_scheduled_day(*habit, 20261014) != 0 || - habit_scheduled_day(*habit, 20261021) != 1 { + habit_scheduled_day(*habit, 20261014) != 0 || + habit_scheduled_day(*habit, 20261021) != 1 { return 207 } formula: HabitSchedule formula.repeat = HABIT_REPEAT_FORMULA unused HabitScheduleSetFormula(*formula, "days % 2 == 0") if !HabitScheduleSet(*habit, formula, 20261101, false) || - habit.schedules[3].start != 20261101 { + habit.schedules[3].start != 20261101 { return 208 } text: [HABIT_SCHEDULE_TEXT_SIZE]u8 @@ -166,13 +166,13 @@ HistoryAnswer :: () -> s32 { index: s32 = 0 while index < copy.schedule_count { if copy.schedules[index].from != habit.schedules[index].from || - !HabitScheduleSame(*copy.schedules[index], *habit.schedules[index]) { + !HabitScheduleSame(*copy.schedules[index], *habit.schedules[index]) { return 210 } index += 1 } if habit_scheduled_day(*copy, 20261103) != 1 || - habit_scheduled_day(*copy, 20261102) != 0 { + habit_scheduled_day(*copy, 20261102) != 0 { return 211 } bad: HabitSchedule @@ -201,7 +201,7 @@ Answer :: () -> s32 { habit.counter_enabled = 1 habit.counter_target = 3 if habit_counting_enabled(*habit) != 1 || - habit_counter_target(*habit) != 3 { return 11 } + habit_counter_target(*habit) != 3 { return 11 } days: [2]HabitDay days[0].day_index = 20260925 days[0].count = 2 @@ -212,12 +212,27 @@ Answer :: () -> s32 { habit.day_count = 2 habit.day_capacity = 2 if HabitCompletedFor(*habit, 20260925) || - !HabitCompletedOnDay(days[:], 20260926, true, 3) || - !HabitCompletedOnDay(days[:], 20260925, false, 3) || - HabitCompletedOnDay(days[:], 20260924, false, 1) { + !HabitCompletedOnDay(days[:], 20260926, true, 3) || + !HabitCompletedOnDay(days[:], 20260925, false, 3) || + HabitCompletedOnDay(days[:], 20260924, false, 1) { return 12 } habit.day_count = 3 if HabitCompletedFor(*habit, 20260926) == false { return 13 } + habit.day_count = 2 + habit.counter_target = 0 + days[0].count = 0 + if habit_counter_target(*habit) != 0 || + !HabitCompletedFor(*habit, 20260925) || + HabitDayCount(*habit, 20260925) != 0 || + HabitCompletedFor(*habit, 20260926) || + HabitCompletedFor(*habit, 20260924) { + return 14 + } + days[0].session_count = 1 + if HabitCompletedFor(*habit, 20260925) { return 15 } + days[0].session_count = 0 + days[0].completed = 0 + if HabitCompletedFor(*habit, 20260925) { return 16 } return 42 } diff --git a/tests/habit_form_behavior.zi b/tests/habit_form_behavior.zi index 12416f8f6..5566a6479 100644 --- a/tests/habit_form_behavior.zi +++ b/tests/habit_form_behavior.zi @@ -188,6 +188,19 @@ Check :: () -> s32 { check_true("another navigation attempt asks again", habit_edit_request_leave(app, 4)) habit_edit_resolve_leave(app, 3) check_true("Discard continues to the requested destination", left_route == 4 && app.habit_edit.active == 0) + habit_edit_begin(app, 0) + app.habit_edit.counter_enabled = 1 + app.habit_edit.counter_target = 0 + app.habit_edit.custom_coins = true + app.habit_edit.coin_halves = -4 + habit_edit_commit(app) + check_int("saving a zero target", app.habits.items[0].counter_target, 0) + habit_edit_begin(app, 0) + check_int("reopening a zero target", app.habit_edit.counter_target, 0) + check_true("reopening custom negative coins", app.habit_edit.custom_coins && + app.habit_edit.coin_halves == -4) + check_true("a zero target has no unsaved changes", !habit_edit_changed(app)) + habit_edit_cancel(app) habits_free(*app.habits) CloseTestCells() storage_close() diff --git a/tests/habit_linked_rules_behavior.zi b/tests/habit_linked_rules_behavior.zi index 089fefb9d..55c63427e 100644 --- a/tests/habit_linked_rules_behavior.zi +++ b/tests/habit_linked_rules_behavior.zi @@ -40,12 +40,12 @@ Answer :: () -> s32 { return 3 } if ctx.count != 1 || ctx.entries[0].round_count != 12 || - ctx.entries[0].total_seconds != 78 || - ctx.entries[0].best_seconds != 12 || - ctx.total_seconds != 78 || ctx.best_seconds != 12 || - ctx.entries[0].path[4] != 49 || - !HabitLinkedHasDay(*ctx, 20260925) || - HabitLinkedSessionCountForDay(*ctx, 20260925) != 1 { + ctx.entries[0].total_seconds != 78 || + ctx.entries[0].best_seconds != 12 || + ctx.total_seconds != 78 || ctx.best_seconds != 12 || + ctx.entries[0].path[4] != 49 || + !HabitLinkedHasDay(*ctx, 20260925) || + HabitLinkedSessionCountForDay(*ctx, 20260925) != 1 { return 4 } if !HabitLinkedAppend(*ctx, *path[0], 2026, 9, 25, 4, 5, 6, @@ -53,7 +53,7 @@ Answer :: () -> s32 { return 5 } if ctx.count != 2 || ctx.total_seconds != 85 || - HabitLinkedSessionCountForDay(*ctx, 20260925) != 2 { + HabitLinkedSessionCountForDay(*ctx, 20260925) != 2 { return 6 } @@ -67,15 +67,15 @@ Answer :: () -> s32 { habit.day_count = 2 habit.day_capacity = 2 if HabitDayCount(*habit, 20260925) != 4 || - HabitDayCount(*habit, 20260926) != 1 || - HabitEffectiveDayCount(*habit, 20260925, *ctx) != 4 || - HabitEffectiveDayCount(*habit, 20260926, *ctx) != 1 { + HabitDayCount(*habit, 20260926) != 1 || + HabitEffectiveDayCount(*habit, 20260925, *ctx) != 4 || + HabitEffectiveDayCount(*habit, 20260926, *ctx) != 1 { return 7 } days[0].count = 0 if HabitEffectiveDayCount(*habit, 20260925, *ctx) != 2 || - habit_activity_mask_for(-1) != 0 || - habit_activity_mask_for(EXERCISE_MEDITATION) != 2 { + habit_activity_mask_for(-1) != 0 || + habit_activity_mask_for(EXERCISE_MEDITATION) != 2 { return 8 } ctx.count = HABIT_LINKED_ENTRY_MAX @@ -83,5 +83,14 @@ Answer :: () -> s32 { EXERCISE_MEDITATION, *rounds[0], 1) { return 9 } + habit.counter_enabled = 1 + habit.counter_target = 0 + days[0].completed = 1 + if HabitEffectiveDayComplete(*habit, 20260925, *ctx) || + !HabitEffectiveDayComplete(*habit, 20260926, null) || + HabitEffectiveDayCount(*habit, 20260926, null) != 0 || + HabitEffectiveDayComplete(*habit, 20260927, null) { + return 10 + } return 42 } diff --git a/tests/habit_model_behavior.zi b/tests/habit_model_behavior.zi index b8423d7a8..cf5f0271f 100644 --- a/tests/habit_model_behavior.zi +++ b/tests/habit_model_behavior.zi @@ -307,6 +307,7 @@ Check :: () -> s32 { if guard != 0 { return guard } test_date_helpers() test_count_mutations() + test_zero_target_counts() test_dirty_flush_on_storage_failure() test_move_delete_and_unique_names() test_defaults_and_activity_matching() @@ -314,3 +315,27 @@ Check :: () -> s32 { test_suggested_icons() return failures } + +test_zero_target_counts :: () { + root := make_root("habit-model-zero-target") + check_true("init zero target db", storage_init(root) != 0) + app_state = InnerBreeze.{} + habits := *app_state.habits + unused habits_add_custom(habits, "Avoid", Walk(), 0, 0) + habit := *habits.items[0] + habit.counter_enabled = 1 + habit.counter_target = 0 + check_int("unrecorded day stays incomplete", habit_completed_day(habit, 20261022), 0) + habit_set_day_count(habits, 0, 20261022, 0) + check_int("a confirmed zero completes the day", habit_completed_day(habit, 20261022), 1) + check_int("zero is not converted to one", HabitDayCount(habit, 20261022), 0) + habit_increment_day(habits, 0, 20261022, 3) + check_int("occurrences miss a zero goal", habit_completed_day(habit, 20261022), 0) + habit_increment_day(habits, 0, 20261022, -3) + check_int("correcting the count restores completion", habit_completed_day(habit, 20261022), 1) + habits_flush_save(*app_state) + check_int("the confirmed zero is stored", raw_free_count( + "SELECT COUNT(*) FROM habit_days WHERE local_date=20261022 AND count=0 AND completed=1"), 1) + habits_free(habits) + storage_close() +} diff --git a/tests/habit_tracking_tool_test.py b/tests/habit_tracking_tool_test.py index fda1e1e6e..5bcd25a43 100644 --- a/tests/habit_tracking_tool_test.py +++ b/tests/habit_tracking_tool_test.py @@ -144,6 +144,8 @@ with tempfile.TemporaryDirectory(prefix='inbe-habit-tracking-') as directory: low='14:00', high='36:30') assert result['tracking'] == dict(mode='span', target=1, good='between', low='14:00', high='36:30'), result + result = tracking(window, id=identifier, mode='count', target=0) + assert result['tracking'] == dict(mode='count', target=0), result result = tracking(window, id=identifier, mode='count', target=3) assert result['tracking'] == dict(mode='count', target=3), result result = tracking(window, id=identifier, mode='span') @@ -190,7 +192,7 @@ with tempfile.TemporaryDirectory(prefix='inbe-habit-tracking-') as directory: assert result['ok'] is False and error in result['error'], (items, result) for wrong, error in [ (dict(mode='timer'), 'mode'), - (dict(mode='count', target=0), 'target'), + (dict(mode='count', target=-1), 'target'), (dict(mode='count', good='at_most', high='8:00'), 'spans only'), (dict(mode='span', good='at_most'), 'H:MM'), (dict(mode='span', good='at_most', high='8'), 'H:MM'), diff --git a/tests/habits_count_ui_test.py b/tests/habits_count_ui_test.py index 9bf6e172b..f0f85e5af 100644 --- a/tests/habits_count_ui_test.py +++ b/tests/habits_count_ui_test.py @@ -113,6 +113,17 @@ def wait_count(driver, value, message): time.sleep(0.05) +def scroll_to(driver, **selector): + for _ in range(24): + nodes = driver.find(visible=True, **selector) + if nodes: + return nodes[0] + driver.pointer(200, 450, wheel=-3) + driver.release_pointer() + driver.wait_idle(frames=4) + return driver.wait(**selector) + + with scene("habit_count_dialog") as (driver, database): driver.wait(key=DONE) name = counted_habit(database) @@ -135,6 +146,63 @@ with scene("habit_count_dialog") as (driver, database): expect(driver.find(contains="Daily target", visible=True), [], "dialog after Close") print("PASS the count dialog steps the day's count and closes") +with scene("habit_count_zero") as (driver, database): + driver.wait(key=DONE) + expect(driver.wait(contains="Daily target")["label"], "Daily target 0", "zero target text") + expect(shown_count(driver), 0, "zero count before recording") + driver.press(key=PLUS) + wait_count(driver, 1, "record an occurrence") + driver.press(key=PLUS) + wait_count(driver, 2, "record a second occurrence") + driver.press(key=MINUS) + wait_count(driver, 1, "correct an occurrence") + driver.press(key=MINUS) + wait_count(driver, 0, "correct back to zero") + driver.press(key=DONE) + driver.wait_gone(key=DONE) + expect(sql(database, "SELECT count||':'||completed FROM habit_days d JOIN habits h ON h.id=d.habit_id " + "WHERE h.counter_target=0 AND d.local_date=CAST(strftime('%Y%m%d','now','localtime') AS INTEGER)"), + "0:1", "confirmed zero stays zero and succeeds") +print("PASS zero-target counts record occurrences and confirm a successful zero") + +with scene("habit_edit") as (driver, database): + driver.press(focus_id=7511, role="text_field") + driver.type("Reverse habit") + scroll_to(driver, key=7606) + driver.press(key=7606) + scroll_to(driver, focus_id=7607, role="text_field") + driver.press(focus_id=7607, role="text_field") + driver.key("a", control=True) + driver.type("-2") + driver.wait(focus_id=7607, value="-2") + scroll_to(driver, key=7610) + driver.press(key=7610) + scroll_to(driver, key=7620) + driver.press(key=7620) + driver.wait(focus_id=7622, value="0") + driver.press(key=7621) + driver.wait(focus_id=7622, value="1") + driver.press(focus_id=7622, role="text_field") + driver.key("a", control=True) + driver.type("0") + driver.wait(focus_id=7622, value="0") + driver.pointer(200, 450, wheel=12) + driver.release_pointer() + driver.wait_idle(frames=4) + scroll_to(driver, focus_id=7607, role="text_field") + driver.pointer(200, 450, wheel=-7) + driver.release_pointer() + driver.wait_idle(frames=5) + window = subprocess.check_output([ + "xdotool", "search", "--onlyvisible", "--pid", str(driver.process.pid)], text=True) + subprocess.run(["import", "-window", window.splitlines()[0], + str(TEST_DIR / "zero-target-negative-coins.png")], check=True) + driver.press(label="Create habit", role="button") + expect(sql(database, "SELECT counter_target||':'||custom_coins||':'||coin_halves " + "FROM habits WHERE name='Reverse habit' AND deleted_at=0"), + "0:1:-4", "editor saves a zero target and negative coins per occurrence") +print("PASS the habit editor accepts zero by step and typing, and custom negative coins") + with scene("habit_count_questions") as (driver, database): driver.wait(key=ENTRIES) driver.wait(label="Entries") diff --git a/tests/lumi_habit_intent_test.py b/tests/lumi_habit_intent_test.py index 510a324e9..17397437e 100644 --- a/tests/lumi_habit_intent_test.py +++ b/tests/lumi_habit_intent_test.py @@ -87,6 +87,7 @@ CASES = [ ('en', 'add a habit yoga', '[]', 'exists'), ('en', 'push ups 3 times a day', '[]', [tracking('id-push', mode='count', target=3)]), ('en', 'jumping rope should count to 100', '[]', [tracking('id-rope', mode='count', target=100)]), + ('en', 'jumping rope should count to 0', '[]', [tracking('id-rope', mode='count', target=0)]), ('en', 'jumping rope should ask how many I did, higher is better', '[]', [ questions('id-rope', dict(text='How many I did?', answer='number', good='above_average'))]), ('en', 'jumping rope should ask how many I did, at least 50', ROPE_QUESTIONS, [ diff --git a/tests/media_store_behavior.zi b/tests/media_store_behavior.zi index 42c7d6668..d47cea3a1 100644 --- a/tests/media_store_behavior.zi +++ b/tests/media_store_behavior.zi @@ -18,6 +18,7 @@ #import, file "../src/cells/package_files.zi"; #import, file "../src/cells/diary_records.zi"; #import, file "../src/cells/media_store.zi"; +#import, file "../src/cells/media_metadata.zi"; Byte :: (out: *Vec(u8), value: s64) { unused VecPush(out.*, cast(u8)(value & 255)) @@ -261,6 +262,36 @@ Check :: () -> s32 { check_int("another account's library is empty", MediaQuery("", false), 0) check_true("another account cannot draw them", MediaAsset(morning_hash, false) == "" && !MediaAssetAllowed(preview_asset)) + // Both photo pickers use this same import. Only the library copy is + // optimized; the picked source and camera date remain intact. + large := Photo("2026:10:18 11:22:33", 6, 600000, 4) + large_source := WriteSource("camera.jpg", large) + optimized := MediaImportFile(large_source) + optimized_hash := PackageText(TextUntilNul(optimized.hash[:]), "") + optimized_bytes := PackageRead(MediaPath(optimized_hash, false), DIARY_FILE_LIMIT) + check_true("a large photo is optimized", optimized.succeeded && + optimized_bytes.count > 100 && optimized_bytes.count * 10 < large.count * 9) + check_true("its identity matches the saved copy", Hash(optimized_bytes) == optimized_hash && + optimized_hash != Hash(large)) + check_true("the picked source is untouched", PackageRead(large_source, DIARY_FILE_LIMIT) == large) + check_true("the optimized copy keeps its capture date", + RecordField(optimized_hash, "taken", field[:]) == "2026-10-18T11:22:33") + check_true("rotation is baked into the saved copy", MediaOrientationOf(optimized_bytes, "jpg") == 1) + repeated := MediaImportFile(large_source) + check_true("picking the source again keeps one optimized copy", repeated.succeeded && repeated.existed && + TextUntilNul(repeated.hash[:]) == optimized_hash && MediaQuery("", false) == 1) + + // Existing Diary imports keep their hashes and embeds when picked again. + legacy := Photo("2026:10:19 12:34:56", 1, 600000, 5) + legacy_hash := Hash(legacy) + check_true("keep an older full-sized photo", MediaAddBytes(legacy, + MediaAddition.{.name = "older.jpg"}).succeeded) + legacy_again := MediaImportBytes(legacy, "older copy.jpg") + check_true("existing original identities survive compression", legacy_again.succeeded && legacy_again.existed && + TextUntilNul(legacy_again.hash[:]) == legacy_hash && + PackageRead(MediaPath(legacy_hash, false), DIARY_FILE_LIMIT) == legacy) + PackageFree(optimized_bytes) + PackageFree(optimized_hash) storage_close() return failures } diff --git a/tests/photos_app_behavior.zi b/tests/photos_app_behavior.zi index 606af8846..1ed953edd 100644 --- a/tests/photos_app_behavior.zi +++ b/tests/photos_app_behavior.zi @@ -32,6 +32,7 @@ #import, file "../src/cells/node_apps.zi"; #import, file "../src/cells/hosted_assets.zi"; #import, file "../src/cells/media_store.zi"; +#import, file "../src/cells/diary_photos.zi"; #import, file "../src/cells/package_files.zi"; #import, file "../src/cells/catalog.zi"; #import, file "background_audio_stub.zi"; @@ -352,6 +353,11 @@ Check :: () -> s32 { NodeAppUninstall(slot) check_true("removing Photos keeps its mark off", storage_get_setting_text("app_used_photos") == "0") check_int("the library keeps its photos", MediaQuery("", false), 1) + diary_asset := DiaryPhotoAsset(MediaPlace(MediaRead(TextUntilNul(first.hash[:])))) + check_true("Diary still draws the shared photo without Photos installed", + diary_asset == preview && MediaAssetView(diary_asset).found) + check_true("the shared full photo stays available", + MediaAssetView(MediaAsset(TextUntilNul(first.hash[:]), true)).data == picked) PackageFree(preview) storage_close() return failures diff --git a/tests/schema_zi_test.c b/tests/schema_zi_test.c index 3f3b1d8d5..27730dd97 100644 --- a/tests/schema_zi_test.c +++ b/tests/schema_zi_test.c @@ -165,6 +165,7 @@ static void upgrade_1_8_9(const char *fixture) assert(scalar("SELECT COUNT(*) FROM habit_rewards") == 0); assert(has_column("habit_rewards", "icon")); assert(scalar("SELECT COUNT(*) FROM habit_coins") == 0); + assert(scalar("SELECT COUNT(*) FROM habits WHERE custom_coins=0 AND coin_halves=0") == 1); assert(scalar("SELECT count FROM habit_days") == 7); assert(scalar("SELECT session_count FROM habit_days") == 2); assert(scalar("SELECT COUNT(*) FROM sessions WHERE id='session' AND " diff --git a/tests/storage_habits_behavior.zi b/tests/storage_habits_behavior.zi index f1d742de7..035a92637 100644 --- a/tests/storage_habits_behavior.zi +++ b/tests/storage_habits_behavior.zi @@ -13,6 +13,7 @@ #import, file "../src/storage/storage_profile_stats.zi"; #import, file "../src/storage/storage_sessions.zi"; #import, file "../src/habits/habit_types.zi"; +#import, file "../src/habits/habit_days.zi"; #import, file "../src/habits/habit_coins.zi"; #import, file "../src/habits/habit_icons.zi"; #import, file "../src/habits/habit_memory.zi"; @@ -1083,5 +1084,80 @@ Check :: () -> s32 { test_average_goals_and_changes() test_stale_copy_keeps_synced_values() test_habit_wallet() + test_zero_target_and_custom_coins() return failures } + +test_zero_target_and_custom_coins :: () { + root := make_root("habit-custom-coins") + check_true("init custom coins db", storage_init(root) != 0) + storage_close() + raw_exec(root, "INSERT INTO habits(id,user_id,name,color_r,color_g,color_b,sync_mode,sync_activity,counter_enabled,counter_target,sort_order,deleted_at,custom_coins,coin_halves,coins_from,updated_at) VALUES('avoid',(SELECT id FROM users LIMIT 1),'Avoid',1,2,3,0,0,1,0,0,0,1,-4,20261001,1);INSERT INTO habit_days(habit_id,local_date,completed,count,session_count,updated_at) VALUES('avoid',20261001,1,0,0,1),('avoid',20261002,1,3,0,1),('avoid',20261003,1,1,0,1),('avoid',20261004,0,0,0,1);") + check_true("open custom coins db", storage_init(root) != 0) + habits_a = Habits.{} + check_true("load custom coins", storage_habits_load(cast(*void)*habits_a) != 0) + habit := find_habit(*habits_a, "Avoid") + if habit == null { check_true("avoid exists", false); storage_close(); return } + check_true("zero target and negative coins survive load", habit.counter_target == 0 && + habit.custom_coins && habit.coin_halves == -4) + check_true("a recorded zero succeeds; occurrences and cleared days do not", + HabitCompletedFor(habit, 20261001) && !HabitCompletedFor(habit, 20261002) && + !HabitCompletedFor(habit, 20261004) && !HabitCompletedFor(habit, 20261005)) + check_int("every occurrence deducts coins", cast(s32)storage_habit_wallet_halves(), -16) + activity: [8]HabitCoinActivity + check_int("penalties appear in coin activity", storage_habit_activity_load(activity[:]), 2) + check_true("activity shows signed occurrence totals", activity[0].halves == -4 && activity[1].halves == -12) + habits_save(*habits_a) + check_int("saving preserves the recorded zero", read_db_count( + "SELECT COUNT(*) FROM habit_days WHERE habit_id='avoid' AND local_date=20261001 AND completed=1 AND count=0"), 1) + today := habits_today_index() + check_true("save today's occurrences", storage_habit_day_save("avoid", today, 1, 2) != 0) + habit.coin_halves = 0 + habits_save(*habits_a) + check_int("zero coins give no reward or penalty and preserve earlier rates", + cast(s32)storage_habit_wallet_halves(), -16) + habit.coin_halves = -2 + habits_save(*habits_a) + check_int("negative coins apply per occurrence today", cast(s32)storage_habit_wallet_halves(), -20) + buffer: [8192]u8 + json := synced_changes("habit", "avoid", "habits", buffer[:]) + check_true("sync carries zero targets and custom signed coins", + contains(json, "\"counter_target\":0") && contains(json, "\"custom_coins\":1") && + contains(json, "\"coin_halves\":-2")) + exec_db_sql("UPDATE habits SET custom_coins=0,coin_halves=0,counter_target=1,updated_at=0 WHERE id='avoid';") + check_true("apply synced coin settings", storage_apply_sync_habits_json(json) != 0) + check_int("synced signed coins are retained", read_db_count( + "SELECT COUNT(*) FROM habits WHERE id='avoid' AND custom_coins=1 AND coin_halves=-2 AND counter_target=0"), 1) + check_int("sync replay does not multiply penalties", cast(s32)storage_habit_wallet_halves(), -20) + check_true("keep a deleted habit's negative coins", storage_habit_coins_keep("avoid", 100) != 0) + check_int("deletion preserves penalties", read_db_count( + "SELECT COUNT(*) FROM habit_coins WHERE reward_id='' AND kind=2 AND coins=-10"), 1) + coin_json := synced_changes("habit_coin", "kept:avoid", "habit_coins", buffer[:]) + exec_db_sql("DELETE FROM habit_coins WHERE id='kept:avoid';") + check_true("sync kept negative coins", storage_apply_sync_habit_coins_json(coin_json) != 0) + check_int("kept penalties stay negative after sync", read_db_count( + "SELECT COUNT(*) FROM habit_coins WHERE id='kept:avoid' AND coins=-10"), 1) + halves: s32 = 77 + check_true("signed and zero coin inputs", HabitCoinParse("-2", *halves) && halves == -4 && + HabitCoinParse("0", *halves) && halves == 0 && HabitCoinParse("-0.5", *halves) && halves == -1) + check_true("invalid coin amounts are rejected", !HabitCoinParse("-", *halves) && + !HabitCoinParse("10000", *halves) && !HabitCoinParse("1.3", *halves)) + archive: TextBuffer + append(*archive, root) + append(*archive, "/custom.zip") + check_true("export custom coins", storage_export_zip(TextFromCString(*archive.bytes[0])) != 0) + habits_free(*habits_a) + storage_close() + destination := make_root("habit-custom-coins-import") + check_true("open custom coins import db", storage_init(destination) != 0) + check_true("import custom coins", storage_import_zip(TextFromCString(*archive.bytes[0])) != 0) + habits_a = Habits.{} + check_true("load imported custom coins", storage_habits_load(cast(*void)*habits_a) != 0) + imported := find_habit(*habits_a, "Avoid") + check_true("backup retains zero goals and signed coins", imported != null && + imported.counter_target == 0 && imported.custom_coins && imported.coin_halves == -2) + check_true("backup retains a recorded zero", HabitCompletedFor(imported, 20261001) && + HabitDayCount(imported, 20261001) == 0) + habits_free(*habits_a) + storage_close() +} diff --git a/tests/sync_record_fields.txt b/tests/sync_record_fields.txt index cd6be65ad..2881a833d 100644 --- a/tests/sync_record_fields.txt +++ b/tests/sync_record_fields.txt @@ -1,4 +1,4 @@ -version 4 +version 5 active activity after @@ -9,6 +9,7 @@ before changed_at ciphertext civil +coin_halves coins coins_from collection @@ -22,6 +23,7 @@ content_hash count counter_enabled counter_target +custom_coins day deactivated deleted