From dbdc08b39638230802ce01a93d8cfb6fa845ede8 Mon Sep 17 00:00:00 2001 From: waozixyz Date: Thu, 2 Jul 2026 19:14:16 -0300 Subject: [PATCH] Fix web build and deduplicate code --- .github/workflows/release.yml | 41 +- CHANGELOG.md | 10 + Makefile | 7 +- droid/app/build.gradle | 4 +- .../metadata/android/en-US/changelogs/76.txt | 4 + .../metadata/android/en-US/changelogs/77.txt | 4 + locales/cs.txt | 5 +- locales/de.txt | 5 +- locales/en.txt | 5 +- locales/es.txt | 5 +- locales/fr.txt | 5 +- locales/id.txt | 5 +- locales/it.txt | 5 +- locales/ja.txt | 5 +- locales/ko.txt | 5 +- locales/pt.txt | 5 +- locales/ru.txt | 5 +- locales/zh.txt | 5 +- scripts/upload-amazon-appstore.mjs | 106 +- src/app/app.c | 78 +- src/app/app.h | 20 + src/app/app_nav.c | 17 +- src/app/app_settings.c | 10 +- src/core/version.h | 6 +- src/practices/meditation/meditation_config.c | 43 +- src/practices/meditation/meditation_manual.c | 29 +- src/practices/meditation/meditation_session.c | 38 +- .../sun_salutation/sun_salutation_practice.c | 9 + .../sun_salutation/sun_salutation_session.c | 26 +- src/practices/whm/whm_config.c | 36 +- src/practices/whm/whm_manual.c | 24 +- src/practices/whm/whm_session.c | 46 +- src/screens/habits_screen.c | 124 ++- src/screens/habits_screen.h | 2 +- src/screens/practice_screen.c | 296 +++++- src/screens/practice_screen.h | 24 + src/screens/profile_screen.c | 92 +- src/screens/settings/settings_data.c | 7 +- src/screens/settings/settings_device.c | 17 +- src/screens/settings/settings_screen.c | 2 + src/screens/settings/settings_session.c | 33 +- src/screens/settings/settings_sync_account.c | 197 +++- src/screens/settings/settings_sync_account.h | 1 + src/screens/settings/settings_theme.c | 14 + src/screens/settings/settings_ui.c | 35 + src/screens/settings/settings_ui.h | 7 + src/storage/db.c | 10 +- src/storage/db.h | 1 + src/storage/import.c | 229 +++-- src/storage/storage.c | 950 ++++++++++-------- src/storage/storage.h | 6 +- src/storage/storage_sessions.c | 141 +-- src/storage/sync_review.c | 196 ++-- src/web_shell.html | 9 +- tests/app_bottom_nav_test.c | 44 + tests/sync_review_test.c | 157 ++- vendor/flint | 2 +- windows/inbe.rc | 8 +- 58 files changed, 2183 insertions(+), 1039 deletions(-) create mode 100644 fastlane/metadata/android/en-US/changelogs/76.txt create mode 100644 fastlane/metadata/android/en-US/changelogs/77.txt diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index fbf6a5c8e..611173031 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -565,10 +565,35 @@ jobs: mkdir -p build/itch/inbe-web unzip -q "$web_zip" -d build/itch/inbe-web - butler push build/itch/inbe-web waozi/inbe:html5 --userversion "$VERSION" - butler push "$android_apk" waozi/inbe:android --userversion "$VERSION" - butler push "$windows_zip" waozi/inbe:windows --userversion "$VERSION" - butler push "$linux_appimage" waozi/inbe:linux --userversion "$VERSION" + butler_push() { + local target="$1" + local channel="$2" + local attempt + local log_file + log_file="$(mktemp)" + + for attempt in 1 2 3 4 5 6; do + if butler push "$target" "waozi/inbe:$channel" --userversion "$VERSION" 2>&1 | tee "$log_file"; then + rm -f "$log_file" + return 0 + fi + if ! grep -q "latest build is still processing" "$log_file"; then + rm -f "$log_file" + return 1 + fi + echo "itch.io channel $channel is still processing; retrying in 60s ($attempt/6)" + sleep 60 + done + + rm -f "$log_file" + echo "itch.io channel $channel was still processing after retries" + return 1 + } + + butler_push build/itch/inbe-web html5 + butler_push "$android_apk" android + butler_push "$windows_zip" windows + butler_push "$linux_appimage" linux publish-google-play: name: Publish Google Play Production @@ -595,13 +620,13 @@ jobs: name: release-android path: build/release/android - - name: Publish AAB to Play Games on PC Production + - name: Publish AAB to Google Play Production uses: r0adkll/upload-google-play@v1 with: serviceAccountJsonPlainText: ${{ secrets.PLAY_STORE_JSON_KEY }} packageName: xyz.waozi.inbe releaseFiles: build/release/android/*.aab - tracks: google_play_games_pc:production + track: production status: completed publish-amazon: @@ -641,9 +666,9 @@ jobs: with: node-version: '24' - - name: Upload APK to Amazon Appstore + - name: Upload AAB to Amazon Appstore env: - AMAZON_RELEASE_FILE: build/release/android/inbe-${{ needs.release.outputs.version }}.apk + AMAZON_RELEASE_FILE: build/release/android/inbe-${{ needs.release.outputs.version }}.aab run: node scripts/upload-amazon-appstore.mjs publish-chrome-web-store: diff --git a/CHANGELOG.md b/CHANGELOG.md index 2bb90432c..61897e16d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,14 @@ # Changelog +## [1.8.0] - 2026-07-02 +### Changed +- upgrade to sync protocol v3 +- ui fixes + +## [1.7.12] - 2026-07-01 +### Changed +- fix web +- deduplicate code + ## [1.7.11] - 2026-07-01 ### Addded - add more banners diff --git a/Makefile b/Makefile index f7fb101d1..3d397daab 100644 --- a/Makefile +++ b/Makefile @@ -409,11 +409,11 @@ $(SYNC_ACCOUNT_TEST): tests/sync_account_test.c src/storage/sync_account.c src/s tests/sync_account_test.c src/storage/sync_account.c $(FLINT_DIR)/src/flint_lyra_account.c src/storage/storage.c src/storage/storage_sessions.c src/storage/sync_review.c src/storage/db.c src/storage/import.c src/third_party/miniz.c $(SQLITE_SRC) \ $(LIBOQS_A) -Wl,--gc-sections -lm -lpthread -ldl -$(SYNC_REVIEW_TEST): tests/sync_review_test.c src/storage/storage.c src/storage/storage_sessions.c src/storage/sync_review.c src/storage/db.c src/storage/import.c src/storage/storage.h src/storage/db.h src/storage/import.h src/third_party/miniz.c src/third_party/miniz.h $(SQLITE_SRC) $(SQLITE_AMALGAMATION_H) | $(TEST_BIN_DIR) +$(SYNC_REVIEW_TEST): tests/sync_review_test.c src/storage/storage.c src/storage/storage_sessions.c src/storage/sync_review.c src/storage/db.c src/storage/import.c src/storage/storage.h src/storage/db.h src/storage/import.h src/screens/habits_screen.c src/screens/habits_screen.h src/third_party/miniz.c src/third_party/miniz.h $(SQLITE_SRC) $(SQLITE_AMALGAMATION_H) | $(TEST_BIN_DIR) $(CC) -Wall -Wextra -std=c99 -D_DEFAULT_SOURCE -D_GNU_SOURCE -DMINIZ_NO_ZLIB_COMPATIBLE_NAMES -ffunction-sections -fdata-sections \ -Isrc -Isrc/app -Isrc/core -Isrc/screens -Isrc/screens/settings -Isrc/practices -Isrc/practices/whm -Isrc/practices/meditation -Isrc/storage -Isrc/platform/android -Isrc/third_party $(FLINT_INCLUDE) -I$(RAYLIB_DIR) $(SQLITE_INCLUDE) \ -o $@ \ - tests/sync_review_test.c src/storage/storage.c src/storage/storage_sessions.c src/storage/sync_review.c src/storage/db.c src/storage/import.c src/third_party/miniz.c $(SQLITE_SRC) \ + tests/sync_review_test.c src/storage/storage.c src/storage/storage_sessions.c src/storage/sync_review.c src/storage/db.c src/storage/import.c src/screens/habits_screen.c src/third_party/miniz.c $(SQLITE_SRC) \ -Wl,--gc-sections -lm -lpthread -ldl $(FONT_LOCALE_TEST): tests/font_locale_test.c $(FONT_OUTPUTS) | $(TEST_BIN_DIR) @@ -881,7 +881,8 @@ $(WEB_TARGET): Makefile $(SRC) $(FLINT_WEB_SRCS) $(FLINT_ICON_STAMP) $(SQLITE_SR -sASYNCIFY \ -sFORCE_FILESYSTEM=1 \ -sFETCH=1 \ - -sALLOW_MEMORY_GROWTH=1 \ + -sALLOW_MEMORY_GROWTH=0 \ + -sINITIAL_MEMORY=268435456 \ -sSTACK_SIZE=8388608 \ -sEXPORTED_FUNCTIONS=_main,_malloc,_free,_app_web_get_play_in_background,_app_web_set_backgrounded,_app_web_background_tick \ --shell-file src/web_shell.html \ diff --git a/droid/app/build.gradle b/droid/app/build.gradle index be1d6be60..9d78c3f52 100644 --- a/droid/app/build.gradle +++ b/droid/app/build.gradle @@ -35,8 +35,8 @@ android { defaultConfig { minSdk 21 targetSdk 35 - versionCode 73 - versionName "1.7.11" + versionCode 75 + versionName "1.8.0" } diff --git a/fastlane/metadata/android/en-US/changelogs/76.txt b/fastlane/metadata/android/en-US/changelogs/76.txt new file mode 100644 index 000000000..5d641e496 --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/76.txt @@ -0,0 +1,4 @@ +Changed +--- +- fix web +- deduplicate code diff --git a/fastlane/metadata/android/en-US/changelogs/77.txt b/fastlane/metadata/android/en-US/changelogs/77.txt new file mode 100644 index 000000000..4e0f0a844 --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/77.txt @@ -0,0 +1,4 @@ +Changed +--- +- upgrade to sync protocol v3 +- ui fixes diff --git a/locales/cs.txt b/locales/cs.txt index 7f886a852..039f610e1 100644 --- a/locales/cs.txt +++ b/locales/cs.txt @@ -376,6 +376,9 @@ Hlasitost [show_session_volume_control_label] Zobrazit ovládání hlasitosti --- +[show_session_return_button_label] +Zobrazit tlačítko návratu +--- [reset_to_defaults_label] Obnovit výchozí --- @@ -827,7 +830,7 @@ Spustit cvičení Manuál --- [practice_configure_button] -Nastavit cvičení +Nastavit --- [practice_music_practice_list_title] Používat hudbu pro cvičení diff --git a/locales/de.txt b/locales/de.txt index c94079a8a..17e7d7de8 100644 --- a/locales/de.txt +++ b/locales/de.txt @@ -376,6 +376,9 @@ Lautstärke [show_session_volume_control_label] Lautstärkeregler anzeigen --- +[show_session_return_button_label] +Zurück-Taste anzeigen +--- [reset_to_defaults_label] Auf Standard zurücksetzen --- @@ -827,7 +830,7 @@ Praxis starten Anleitung --- [practice_configure_button] -Praxis konfigurieren +Konfigurieren --- [practice_music_practice_list_title] Musik für Praktiken verwenden diff --git a/locales/en.txt b/locales/en.txt index a1e3e8b8b..e905c9144 100644 --- a/locales/en.txt +++ b/locales/en.txt @@ -400,6 +400,9 @@ Volume [show_session_volume_control_label] Show volume control --- +[show_session_return_button_label] +Show return button +--- [reset_to_defaults_label] Reset to defaults --- @@ -826,7 +829,7 @@ Start Practice Manual --- [practice_configure_button] -Configure Practice +Configure --- [practice_music_practice_list_title] Use music for practices diff --git a/locales/es.txt b/locales/es.txt index 07345eab8..d09a97563 100644 --- a/locales/es.txt +++ b/locales/es.txt @@ -376,6 +376,9 @@ Volumen [show_session_volume_control_label] Mostrar control de volumen --- +[show_session_return_button_label] +Mostrar botón de volver +--- [reset_to_defaults_label] Restablecer valores predeterminados --- @@ -827,7 +830,7 @@ Iniciar práctica Manual --- [practice_configure_button] -Configurar práctica +Configurar --- [practice_music_practice_list_title] Usar música en prácticas diff --git a/locales/fr.txt b/locales/fr.txt index 26329ea11..d36518095 100644 --- a/locales/fr.txt +++ b/locales/fr.txt @@ -379,6 +379,9 @@ Volume [show_session_volume_control_label] Afficher le contrôle du volume --- +[show_session_return_button_label] +Afficher le bouton retour +--- [reset_to_defaults_label] Réinitialiser --- @@ -827,7 +830,7 @@ Démarrer la pratique Manuel --- [practice_configure_button] -Configurer la pratique +Configurer --- [practice_music_practice_list_title] Utiliser la musique pour les pratiques diff --git a/locales/id.txt b/locales/id.txt index 535832cfe..9557cbb7e 100644 --- a/locales/id.txt +++ b/locales/id.txt @@ -376,6 +376,9 @@ Volume [show_session_volume_control_label] Tampilkan kontrol volume --- +[show_session_return_button_label] +Tampilkan tombol kembali +--- [reset_to_defaults_label] Reset ke default --- @@ -827,7 +830,7 @@ Mulai latihan Manual --- [practice_configure_button] -Konfigurasi latihan +Atur --- [practice_music_practice_list_title] Gunakan musik untuk latihan diff --git a/locales/it.txt b/locales/it.txt index 603af8310..7753f8729 100644 --- a/locales/it.txt +++ b/locales/it.txt @@ -394,6 +394,9 @@ Volume [show_session_volume_control_label] Mostra controllo volume --- +[show_session_return_button_label] +Mostra pulsante indietro +--- [reset_to_defaults_label] Ripristina predefiniti --- @@ -827,7 +830,7 @@ Avvia pratica Manuale --- [practice_configure_button] -Configura pratica +Configura --- [practice_music_practice_list_title] Usa musica per le pratiche diff --git a/locales/ja.txt b/locales/ja.txt index 88d0c55bc..3d8547f91 100644 --- a/locales/ja.txt +++ b/locales/ja.txt @@ -376,6 +376,9 @@ OK [show_session_volume_control_label] 音量コントロールを表示 --- +[show_session_return_button_label] +戻るボタンを表示 +--- [reset_to_defaults_label] デフォルトに戻す --- @@ -829,7 +832,7 @@ Alias saved マニュアル --- [practice_configure_button] -プラクティスを設定 +設定 --- [practice_music_practice_list_title] 音楽を使うプラクティス diff --git a/locales/ko.txt b/locales/ko.txt index db9de7c2a..9014f3500 100644 --- a/locales/ko.txt +++ b/locales/ko.txt @@ -394,6 +394,9 @@ Finish [show_session_volume_control_label] 볼륨 조절 표시 --- +[show_session_return_button_label] +돌아가기 버튼 표시 +--- [reset_to_defaults_label] 기본값으로 재설정 --- @@ -826,7 +829,7 @@ Alias saved 설명서 --- [practice_configure_button] -연습 설정 +설정 --- [practice_music_practice_list_title] 연습에 음악 사용 diff --git a/locales/pt.txt b/locales/pt.txt index b79921db9..d2a5130b6 100644 --- a/locales/pt.txt +++ b/locales/pt.txt @@ -376,6 +376,9 @@ Volume [show_session_volume_control_label] Mostrar controle de volume --- +[show_session_return_button_label] +Mostrar botão de voltar +--- [reset_to_defaults_label] Restaurar padrões --- @@ -827,7 +830,7 @@ Iniciar prática Manual --- [practice_configure_button] -Configurar prática +Configurar --- [practice_music_practice_list_title] Usar música nas práticas diff --git a/locales/ru.txt b/locales/ru.txt index 76bf4335e..c0498e770 100644 --- a/locales/ru.txt +++ b/locales/ru.txt @@ -397,6 +397,9 @@ OK [show_session_volume_control_label] Показывать регулятор громкости --- +[show_session_return_button_label] +Показывать кнопку возврата +--- [reset_to_defaults_label] Сбросить настройки --- @@ -827,7 +830,7 @@ Alias saved Инструкция --- [practice_configure_button] -Настроить практику +Настроить --- [practice_music_practice_list_title] Использовать музыку для практик diff --git a/locales/zh.txt b/locales/zh.txt index 6d50eeff2..bc8c54125 100644 --- a/locales/zh.txt +++ b/locales/zh.txt @@ -376,6 +376,9 @@ Finish [show_session_volume_control_label] 显示音量控制 --- +[show_session_return_button_label] +显示返回按钮 +--- [reset_to_defaults_label] 恢复默认 --- @@ -827,7 +830,7 @@ Alias saved 手册 --- [practice_configure_button] -配置练习 +配置 --- [practice_music_practice_list_title] 为练习使用音乐 diff --git a/scripts/upload-amazon-appstore.mjs b/scripts/upload-amazon-appstore.mjs index ff0107c9d..2d50f0ce4 100644 --- a/scripts/upload-amazon-appstore.mjs +++ b/scripts/upload-amazon-appstore.mjs @@ -1,4 +1,5 @@ import { readFile } from "node:fs/promises"; +import { extname } from "node:path"; const baseUrl = "https://developer.amazon.com/api/appstore"; @@ -15,28 +16,92 @@ async function readResponseText(response) { return text.length > 0 ? text : "(empty response)"; } +function isAllowedFailure(response, allowedStatuses) { + return Array.isArray(allowedStatuses) && allowedStatuses.includes(response.status); +} + async function requestJson(url, options = {}) { const response = await fetch(url, options); const text = await readResponseText(response); + if (isAllowedFailure(response, options.allowedStatuses)) { + return null; + } if (!response.ok) { throw new Error(`${options.method || "GET"} ${url} failed: ${response.status} ${response.statusText}: ${text}`); } return text === "(empty response)" ? {} : JSON.parse(text); } +async function requestJsonWithResponse(url, options = {}) { + const response = await fetch(url, options); + const text = await readResponseText(response); + if (!response.ok) { + throw new Error(`${options.method || "GET"} ${url} failed: ${response.status} ${response.statusText}: ${text}`); + } + return { + data: text === "(empty response)" ? {} : JSON.parse(text), + response, + }; +} + async function requestOk(url, options = {}) { const response = await fetch(url, options); const text = await readResponseText(response); + if (isAllowedFailure(response, options.allowedStatuses)) { + return null; + } if (!response.ok) { throw new Error(`${options.method || "GET"} ${url} failed: ${response.status} ${response.statusText}: ${text}`); } return response; } +function releaseKindForFile(file) { + const ext = extname(file).toLowerCase(); + if (ext === ".apk") { + return { + label: "APK", + resourceCandidates: ["apks"], + contentType: "application/vnd.android.package-archive", + }; + } + if (ext === ".aab") { + return { + label: "AAB", + resourceCandidates: ["appbundles", "appBundles", "aabs", "bundles", "apks"], + contentType: "application/octet-stream", + }; + } + throw new Error(`Unsupported Amazon release file extension "${ext}". Expected .apk or .aab`); +} + +function describeAsset(asset) { + return `id=${asset.id ?? "(missing)"} versionCode=${asset.versionCode ?? "(unknown)"} name=${asset.name ?? "(unknown)"}`; +} + +async function findBinaryCollection(editId, releaseKind) { + for (const resource of releaseKind.resourceCandidates) { + const assets = await requestJson(`${baseUrl}/v1/applications/${appId}/edits/${editId}/${resource}`, { + headers: jsonHeaders, + allowedStatuses: [404], + }); + if (assets === null) { + continue; + } + if (!Array.isArray(assets) || assets.length === 0) { + throw new Error(`Amazon edit has no ${releaseKind.label} asset to replace in ${resource}`); + } + return { resource, assets }; + } + + throw new Error(`Amazon edit does not expose a ${releaseKind.label} collection. Tried: ${releaseKind.resourceCandidates.join(", ")}`); +} + const clientId = requireEnv("AMAZON_CLIENT_ID"); const clientSecret = requireEnv("AMAZON_CLIENT_SECRET"); const appId = requireEnv("AMAZON_APP_ID"); const releaseFile = requireEnv("AMAZON_RELEASE_FILE"); +const releaseKind = releaseKindForFile(releaseFile); console.log("Getting Amazon authentication token"); const tokenParams = new URLSearchParams({ @@ -59,14 +124,21 @@ const jsonHeaders = { }; console.log("Checking for an open Amazon edit"); -const activeEdit = await requestJson(`${baseUrl}/v1/applications/${appId}/edits`, { +const { data: activeEdit, response: activeEditResponse } = await requestJsonWithResponse(`${baseUrl}/v1/applications/${appId}/edits`, { headers: jsonHeaders, }); if (activeEdit.id) { + const activeEditEtag = activeEditResponse.headers.get("etag"); + if (!activeEditEtag) { + throw new Error(`Amazon did not return an ETag for open edit ${activeEdit.id}`); + } console.log(`Deleting stale open edit ${activeEdit.id}`); await requestOk(`${baseUrl}/v1/applications/${appId}/edits/${activeEdit.id}`, { method: "DELETE", - headers: jsonHeaders, + headers: { + ...jsonHeaders, + "If-Match": activeEditEtag, + }, }); } @@ -79,33 +151,31 @@ if (!edit.id) { throw new Error("Amazon did not return an edit id"); } -console.log("Finding APK slot to replace"); -const apks = await requestJson(`${baseUrl}/v1/applications/${appId}/edits/${edit.id}/apks`, { - headers: jsonHeaders, -}); -if (!Array.isArray(apks) || apks.length === 0) { - throw new Error("Amazon edit has no APK slot to replace"); +console.log(`Finding ${releaseKind.label} slot to replace`); +const { resource, assets } = await findBinaryCollection(edit.id, releaseKind); +const asset = assets[0]; +if (!asset.id) { + throw new Error(`Amazon ${releaseKind.label} asset did not include an id: ${JSON.stringify(asset)}`); } -const apk = apks[0]; -console.log(`Replacing APK ${apk.id} versionCode=${apk.versionCode} name=${apk.name}`); +console.log(`Replacing ${releaseKind.label} ${describeAsset(asset)} via ${resource}`); -const apkResponse = await requestOk(`${baseUrl}/v1/applications/${appId}/edits/${edit.id}/apks/${apk.id}`, { +const assetResponse = await requestOk(`${baseUrl}/v1/applications/${appId}/edits/${edit.id}/${resource}/${asset.id}`, { headers: jsonHeaders, }); -const etag = apkResponse.headers.get("etag"); +const etag = assetResponse.headers.get("etag"); if (!etag) { - throw new Error(`Amazon did not return an ETag for APK ${apk.id}`); + throw new Error(`Amazon did not return an ETag for ${releaseKind.label} ${asset.id}`); } -const apkBytes = await readFile(releaseFile); -await requestOk(`${baseUrl}/v1/applications/${appId}/edits/${edit.id}/apks/${apk.id}/replace`, { +const releaseBytes = await readFile(releaseFile); +await requestOk(`${baseUrl}/v1/applications/${appId}/edits/${edit.id}/${resource}/${asset.id}/replace`, { method: "PUT", headers: { ...authHeaders, - "Content-Type": "application/vnd.android.package-archive", + "Content-Type": releaseKind.contentType, "If-Match": etag, }, - body: apkBytes, + body: releaseBytes, }); -console.log("Amazon APK upload completed"); +console.log(`Amazon ${releaseKind.label} upload completed`); diff --git a/src/app/app.c b/src/app/app.c index 805755d3a..875ed504a 100644 --- a/src/app/app.c +++ b/src/app/app.c @@ -100,12 +100,19 @@ app_switch_screen(InbeApp *app, int screen) if(screen == InbeScreenHabits && app->inbe.screen != InbeScreenHabits) app->habits.focus_selected_tab = 1; +#if defined(PLATFORM_WEB) + flint_transition_reset(&app->screen_transition); + app->inbe.screen = screen; + app->screen_transition_target = screen; + return; +#else if(app->transition_mode == APP_TRANSITION_NONE) { flint_transition_reset(&app->screen_transition); app->inbe.screen = screen; app->screen_transition_target = screen; return; } +#endif app->screen_transition_target = screen; if(app->screen_transition.active) { @@ -223,6 +230,33 @@ app_close_modal(InbeApp *app) app->modal_input_block_frame = app->inbe.frame; } +SessionExitModalResult +app_draw_session_exit_modal(int can_save, const char *save_message, + const char *discard_message) +{ + int modal_result; + + if(can_save) { + modal_result = ui_draw_modal_3btn(locale_get("exit_session_title"), + save_message, + locale_get("cancel_button"), + locale_get("save_button"), + locale_get("discard_button")); + if(modal_result == 2) + return SessionExitModalSave; + if(modal_result == 3) + return SessionExitModalDiscard; + } else { + modal_result = ui_draw_modal(locale_get("exit_session_title"), + discard_message, + locale_get("cancel_button"), + locale_get("exit_button")); + if(modal_result == 2) + return SessionExitModalDiscard; + } + return modal_result == 1 ? SessionExitModalCancel : SessionExitModalNone; +} + static int exercise_manual_seen_bit(int exercise_type) { @@ -434,7 +468,11 @@ load_config(void) config.title_custom = 0; } - refresh_theme_colors(FLINT_THEME_SKY, 0); /* Default: Sky light mode */ +#if defined(PLATFORM_WEB) + refresh_theme_colors(FLINT_THEME_SKY, 1); +#else + refresh_theme_colors(FLINT_THEME_SKY, 0); +#endif config.loaded = 1; } @@ -1036,6 +1074,8 @@ updateapp(InbeApp *app) int profile_guide_active = 0; int practice_fullscreen_modal = 0; int global_modal_drawn = 0; + int content_input_clip_active = 0; + int bottom_input_reserved = 0; #if !ANDROID_BUILD && !defined(PLATFORM_WEB) app->backgrounded = (!IsWindowFocused() || IsWindowMinimized()) ? 1 : 0; @@ -1055,9 +1095,7 @@ updateapp(InbeApp *app) profile_guide_active = profile_screen_first_run_guide_active(app); practice_fullscreen_modal = app->modal.active && - (app->modal.type == UIModalPracticeManual || - app->modal.type == UIModalPracticeConfig || - app->modal.type == UIModalPracticeMusic || + (app->modal.type == UIModalPracticeMusic || app->modal.type == UIModalEditProgressiveStartSpeed); if(app->modal.active || first_run_guide_active || habits_guide_active || profile_guide_active) { @@ -1066,8 +1104,24 @@ updateapp(InbeApp *app) view_height = app_page_height(app, view_height); center_y = view_height / 2; + bottom_input_reserved = app_content_bottom_reserved(app); + if(bottom_input_reserved > 0 && bottom_input_reserved < view_height) { + ui_push_input_clip((Rectangle){0, 0, (float)view_width, + (float)(view_height - bottom_input_reserved)}); + content_input_clip_active = 1; + } - if(IsKeyPressed(KEY_BACK)) { + if(IsKeyPressed(KEY_BACK) +#if !ANDROID_BUILD && !defined(PLATFORM_WEB) + || (IsKeyPressed(KEY_BACKSPACE) && + ((app->inbe.screen == InbeScreenStart && + app->practice_tab != PRACTICE_TAB_PLAY) || + (app->show_session_return_button && + (app->inbe.screen == InbeScreenSession || + app->inbe.screen == InbeScreenMeditation || + app->inbe.screen == InbeScreenSunSalutation)))) +#endif + ) { if(first_run_guide_active || habits_guide_active || profile_guide_active) { app->tutorial_step = 0; practice_screen_prepare_first_run_guide(app); @@ -1134,7 +1188,15 @@ updateapp(InbeApp *app) case InbeScreenStart: { if(!practice_fullscreen_modal) { - practice_screen_draw_home(app); + if(app->practice_tab == PRACTICE_TAB_MANUAL) { + manual_screen_draw(app); + } else if(app->practice_tab == PRACTICE_TAB_CONFIG) { + const PracticeDefinition *practice = practice_get(app->exercise_type); + if(practice->draw_config != NULL) + practice->draw_config(app); + } else { + practice_screen_draw_home(app); + } } } // Skip drawing on the same frame modal opens to prevent click propagation @@ -1173,6 +1235,8 @@ updateapp(InbeApp *app) } finish_frame: + if(content_input_clip_active) + ui_pop_input_clip(); if(practice_fullscreen_modal) { draw_global_modal(app); global_modal_drawn = 1; @@ -1186,11 +1250,13 @@ finish_frame: draw_global_modal(app); app_flush_deferred_settings(app); app_observe_direct_screen_change(app, frame_screen); +#if !defined(PLATFORM_WEB) if(app->transition_mode == APP_TRANSITION_FADE) { flint_transition_draw_fade(&app->screen_transition, view_width, app_page_height(app, view_height), flint_theme_get_bg()); } +#endif app_advance_screen_transition(app); app->inbe.frame++; } diff --git a/src/app/app.h b/src/app/app.h index cf156a6dc..927aea102 100644 --- a/src/app/app.h +++ b/src/app/app.h @@ -102,6 +102,13 @@ typedef enum { UIModalConfirmRemoveFriend, } UIModalType; +typedef enum SessionExitModalResult { + SessionExitModalNone = 0, + SessionExitModalCancel, + SessionExitModalSave, + SessionExitModalDiscard, +} SessionExitModalResult; + typedef struct { int active; UIModalType type; @@ -245,6 +252,13 @@ typedef struct HabitEditState { int counter_enabled; } HabitEditState; +typedef struct ProfileGuideAnchors { + Rectangle account; + Rectangle data; + Rectangle social; + int valid; +} ProfileGuideAnchors; + struct InbeApp { Inbe inbe; Inbe settings_preview; @@ -280,6 +294,7 @@ struct InbeApp { int settings_dirty; int settings_save_delay_ticks; int settings_tab; + int show_session_return_button; int profile_view; int profile_tab; int profile_tab_scroll; @@ -321,8 +336,10 @@ struct InbeApp { int habits_guide_seen; int profile_guide_step; int profile_guide_seen; + ProfileGuideAnchors profile_guide_anchors; int exercise_manual_seen_mask; int practice_visible_mask; + int practice_home_scroll; int theme_id; int dark_mode; @@ -390,6 +407,9 @@ void app_unload_texture(Texture2D texture); void app_open_modal(InbeApp *app, UIModalType type); void app_close_modal(InbeApp *app); +SessionExitModalResult app_draw_session_exit_modal(int can_save, + const char *save_message, + const char *discard_message); int clampi(int x, int min, int max); int int_from_count(const char src[4]); diff --git a/src/app/app_nav.c b/src/app/app_nav.c index 4f1407695..ad68f3b52 100644 --- a/src/app/app_nav.c +++ b/src/app/app_nav.c @@ -92,6 +92,15 @@ app_apply_nav_route(InbeApp *app, int route) } } +static int +app_is_practice_fullscreen_subview(const InbeApp *app) +{ + return app != NULL && + app->inbe.screen == InbeScreenStart && + (app->practice_tab == PRACTICE_TAB_MANUAL || + app->practice_tab == PRACTICE_TAB_CONFIG); +} + int app_content_bottom_reserved(const InbeApp *app) { @@ -100,6 +109,8 @@ app_content_bottom_reserved(const InbeApp *app) if(app->inbe.screen == InbeScreenHabits && app->habits.screen_mode == HABITS_SCREEN_REORDER) return 0; + if(app_is_practice_fullscreen_subview(app)) + return 0; if(app_current_nav_route(app) == APP_NAV_ROUTE_NONE) return 0; return ui_bottom_nav_height(); @@ -123,9 +134,7 @@ app_has_fullscreen_overlay(const InbeApp *app) { if(app == NULL || !app->modal.active) return 0; - return app->modal.type == UIModalPracticeManual || - app->modal.type == UIModalPracticeConfig || - app->modal.type == UIModalPracticeMusic || + return app->modal.type == UIModalPracticeMusic || app->modal.type == UIModalEditProgressiveStartSpeed; } @@ -168,6 +177,8 @@ app_current_nav_route(const InbeApp *app) case InbeScreenProfile: return APP_NAV_ROUTE_PROFILE; case InbeScreenStart: + if(app_is_practice_fullscreen_subview(app)) + return APP_NAV_ROUTE_NONE; return APP_NAV_ROUTE_PRACTICE; case InbeScreenHabits: return APP_NAV_ROUTE_HABITS; diff --git a/src/app/app_settings.c b/src/app/app_settings.c index 9db8e2e6d..15dad9784 100644 --- a/src/app/app_settings.c +++ b/src/app/app_settings.c @@ -182,6 +182,7 @@ save_settings(InbeApp *app) {"breath_animation", app->inbe.breath_animation}, {"advanced_session_controls", app->advanced_session_controls ? 1 : 0}, {"double_tap_to_breathe", app->double_tap_to_breathe ? 1 : 0}, + {"show_session_return_button", app->show_session_return_button ? 1 : 0}, {"show_session_volume_control", app->show_session_volume_control ? 1 : 0}, {"hold_display_mode", app->hold_display_mode}, {"exercise_type", app->exercise_type}, @@ -276,7 +277,7 @@ app_load_settings(InbeApp *app) {&app->profile_guide_seen, "profile_guide_seen", 0}, {&app->dark_mode, "dark_mode", 0}, {&app->fullscreen_enabled, "fullscreen", 0}, -#if ANDROID_BUILD +#if ANDROID_BUILD || defined(PLATFORM_WEB) {&app->on_screen_keyboard_enabled, "on_screen_keyboard", 1}, #else {&app->on_screen_keyboard_enabled, "on_screen_keyboard", 0}, @@ -284,12 +285,16 @@ app_load_settings(InbeApp *app) {&app->inbe.progressive_speed, "progressive_speed", 1}, {&app->advanced_session_controls, "advanced_session_controls", 0}, {&app->double_tap_to_breathe, "double_tap_to_breathe", 0}, + {&app->show_session_return_button, "show_session_return_button", 1}, {&app->show_session_volume_control, "show_session_volume_control", 0}, {&app->meditation.show_extend_controls, "meditation_show_extend_controls", 1}, {&app->meditation.music_enabled, "meditation_music_enabled", 1}, }; load_bool_settings(settings, sizeof(settings) / sizeof(settings[0])); } +#if ANDROID_BUILD || defined(PLATFORM_WEB) + app->on_screen_keyboard_enabled = 1; +#endif { LoadedClampedSetting settings[] = { @@ -362,6 +367,9 @@ app_load_settings(InbeApp *app) if(getenv("INBE_FORCE_DARK_MODE") != NULL) { app->theme_mode = APP_THEME_DARK; } +#if defined(PLATFORM_WEB) + app->transition_mode = APP_TRANSITION_NONE; +#endif app->inbe.play_in_background = storage_get_setting_int("play_in_background", 1) != 0; diff --git a/src/core/version.h b/src/core/version.h index 643442087..e82a27659 100644 --- a/src/core/version.h +++ b/src/core/version.h @@ -2,8 +2,8 @@ #define INBE_VERSION_H #define INBE_VERSION_MAJOR 1 -#define INBE_VERSION_MINOR 7 -#define INBE_VERSION_PATCH 11 -#define INBE_VERSION_STRING "1.7.11" +#define INBE_VERSION_MINOR 8 +#define INBE_VERSION_PATCH 0 +#define INBE_VERSION_STRING "1.8.0" #endif diff --git a/src/practices/meditation/meditation_config.c b/src/practices/meditation/meditation_config.c index 63e132ff4..d1cc4e4c0 100644 --- a/src/practices/meditation/meditation_config.c +++ b/src/practices/meditation/meditation_config.c @@ -5,6 +5,7 @@ #include "flint_theme.h" #include "flint_ui.h" #include "raylib.h" +#include "screens/practice_screen.h" #include @@ -27,10 +28,11 @@ meditation_config_duration_height(int content_w) static int meditation_config_content_height(InbeApp *app, int content_w) { - int integrated = app->inbe.screen == InbeScreenStart && - app->modal.type != UIModalPracticeConfig; return meditation_config_duration_height(content_w) + - (integrated ? app_content_bottom_reserved(app) : 0) + flint_px(24); + (practice_screen_subscreen_integrated(app, UIModalPracticeConfig) + ? app_content_bottom_reserved(app) + : 0) + + flint_px(24); } static void @@ -148,39 +150,18 @@ meditation_config_scroll_page_content_height(int content_w, void *user_data) void meditation_config_screen_draw(InbeApp *app) { - int integrated = app->inbe.screen == InbeScreenStart && - app->modal.type != UIModalPracticeConfig; - int title_h = integrated ? app_content_top_reserved(app) : flint_ui_title_bar_height(); - int scroll_y; - int scroll_h; - int bottom_reserved = integrated ? app_content_bottom_reserved(app) : 0; + PracticeSubscreenLayout layout; - if(!integrated) { - if(flint_ui_return_title_bar(app->icons[UI_ICON_TYPE_RETURN], locale_get("practice_config_title"), title_h)) { - if(app->modal.active && app->modal.type == UIModalPracticeConfig) { - app_close_modal(app); - } else { - if(app->settings_dirty) - save_settings(app); - meditation_practice_leave_config(app); - app->settings_scroll = 0; - app->practice_tab = PRACTICE_TAB_PLAY; - app_switch_screen(app, InbeScreenStart); - } - } - } - - scroll_y = title_h + flint_px(16); - scroll_h = view_height - scroll_y - bottom_reserved - - (integrated ? flint_px(8) : 0); - if(scroll_h < 0) - scroll_h = 0; + practice_screen_config_layout(app, UIModalPracticeConfig, flint_px(16), &layout); + practice_screen_handle_config_title(app, locale_get("practice_config_title"), + UIModalPracticeConfig, + meditation_practice_leave_config); { MeditationConfigScrollPageContext page_ctx = {app}; FlintUIScrollPage page = ui_scroll_page_begin((FlintUIScrollPageSpec){ - .y = scroll_y, - .height = scroll_h, + .y = layout.scroll_y, + .height = layout.scroll_h, .max_content_width = flint_px(CONTENT_MAX_W), .min_content_width = flint_px(320), .scroll_offset = &app->settings_scroll, diff --git a/src/practices/meditation/meditation_manual.c b/src/practices/meditation/meditation_manual.c index a99388e19..7b16cc4ac 100644 --- a/src/practices/meditation/meditation_manual.c +++ b/src/practices/meditation/meditation_manual.c @@ -3,6 +3,7 @@ #include "app.h" #include "flint_locale.h" #include "screens/manual_screen.h" +#include "screens/practice_screen.h" #include "flint_theme.h" #include "flint_ui.h" #include "raylib.h" @@ -81,14 +82,7 @@ meditation_manual_scroll_page_content_height(int content_w, void *user_data) void meditation_manual_draw(InbeApp *app) { - int integrated = app->inbe.screen == InbeScreenStart && - app->modal.type != UIModalPracticeManual; - int title_h = integrated ? app_content_top_reserved(app) : flint_ui_title_bar_height(); - int nav_h = MEDITATION_MANUAL_PAGES > 1 ? manual_screen_guide_nav_height() : 0; - int bottom_reserved = integrated ? app_content_bottom_reserved(app) : 0; - int nav_y = view_height - bottom_reserved - nav_h; - int content_y = title_h + flint_px(16); - int content_h = nav_y - content_y - flint_px(16); + PracticeManualLayout layout; int responsive_max_w = (int)(view_width * 0.90f); int max_content_w = flint_px(520); int page = clampi(app->tutorial_step, 0, MEDITATION_MANUAL_PAGES - 1); @@ -101,17 +95,18 @@ meditation_manual_draw(InbeApp *app) page = manual_screen_guide_update_page(app, MEDITATION_MANUAL_PAGES, meditation_manual_start, meditation_manual_close); - if(!integrated && - flint_ui_return_title_bar(app->icons[UI_ICON_TYPE_RETURN], locale_get("meditation_manual_title"), title_h)) + practice_screen_manual_layout(app, UIModalPracticeManual, MEDITATION_MANUAL_PAGES, + flint_px(16), flint_px(16), flint_px(120), + &layout); + if(flint_ui_return_title_bar(app->icons[UI_ICON_TYPE_RETURN], + locale_get("meditation_manual_title"), + layout.title_h)) meditation_manual_close(app, 0); - if(content_h < flint_px(120)) - content_h = flint_px(120); - { FlintUIScrollPage scroll_page = ui_scroll_page_begin((FlintUIScrollPageSpec){ - .y = content_y, - .height = content_h, + .y = layout.content_y, + .height = layout.content_h, .max_content_width = responsive_max_w, .min_content_width = flint_px(280), .scroll_offset = &app->manual_scroll, @@ -127,8 +122,8 @@ meditation_manual_draw(InbeApp *app) manual_screen_guide_draw_nav(app, (ManualGuideNav){ .page = page, .page_count = MEDITATION_MANUAL_PAGES, - .y = nav_y, - .h = nav_h, + .y = layout.nav_y, + .h = layout.nav_h, .show_left_on_first = exercise_manual_seen(app, EXERCISE_MEDITATION), .start = meditation_manual_start, .close = meditation_manual_close diff --git a/src/practices/meditation/meditation_session.c b/src/practices/meditation/meditation_session.c index 3fa2468dd..cfd5ff0f3 100644 --- a/src/practices/meditation/meditation_session.c +++ b/src/practices/meditation/meditation_session.c @@ -418,41 +418,29 @@ meditation_draw_screen(InbeApp *app, int center_x, int center_y) int text_w; int title_h = flint_ui_title_bar_height(); - if(flint_ui_return_title_bar(app->icons[UI_ICON_TYPE_RETURN], locale_get("meditation_title"), title_h)) { + if(app->show_session_return_button && + flint_ui_return_title_bar(app->icons[UI_ICON_TYPE_RETURN], locale_get("meditation_title"), title_h)) { meditation_request_exit(app); return; + } else if(!app->show_session_return_button) { + flint_ui_title_bar(locale_get("meditation_title"), title_h); } draw_meditation_sound_controls(app); if(app->modal.active && app->modal.type == UIModalConfirmExitSession) { int elapsed = meditation_elapsed_seconds(app); - int modal_result; + SessionExitModalResult result; - if(elapsed >= 60) { - modal_result = ui_draw_modal_3btn(locale_get("exit_session_title"), - locale_get("meditation_save_elapsed_message"), - locale_get("cancel_button"), - locale_get("save_button"), - locale_get("discard_button")); - if(modal_result == 1) { - app_close_modal(app); - } else if(modal_result == 2) { + result = app_draw_session_exit_modal(elapsed >= 60, + locale_get("meditation_save_elapsed_message"), + locale_get("meditation_under_minute_exit_message")); + if(result == SessionExitModalCancel) { + app_close_modal(app); + } else if(result == SessionExitModalSave || result == SessionExitModalDiscard) { + if(result == SessionExitModalSave) meditation_save_elapsed(app); - meditation_exit_to_start(app); - } else if(modal_result == 3) { - meditation_exit_to_start(app); - } - } else { - modal_result = ui_draw_modal(locale_get("exit_session_title"), - locale_get("meditation_under_minute_exit_message"), - locale_get("cancel_button"), - locale_get("exit_button")); - if(modal_result == 1) { - app_close_modal(app); - } else if(modal_result == 2) { - meditation_exit_to_start(app); - } + meditation_exit_to_start(app); } return; } diff --git a/src/practices/sun_salutation/sun_salutation_practice.c b/src/practices/sun_salutation/sun_salutation_practice.c index 49b05bfe5..a1ea50482 100644 --- a/src/practices/sun_salutation/sun_salutation_practice.c +++ b/src/practices/sun_salutation/sun_salutation_practice.c @@ -227,6 +227,15 @@ sun_salutation_config_screen_draw(InbeApp *app) app_close_modal(app); return; } + } else if(flint_ui_return_title_bar(app->icons[UI_ICON_TYPE_RETURN], + locale_get("practice_config_title"), + title_h)) { + if(app->settings_dirty) + save_settings(app); + app->settings_scroll = 0; + app->practice_tab = PRACTICE_TAB_PLAY; + app_switch_screen(app, InbeScreenStart); + return; } flint_centered_column(CONTENT_MAX_W, CONTENT_SIDE_PAD, &content_x, &content_w); diff --git a/src/practices/sun_salutation/sun_salutation_session.c b/src/practices/sun_salutation/sun_salutation_session.c index 164768f7d..6aacdd9c2 100644 --- a/src/practices/sun_salutation/sun_salutation_session.c +++ b/src/practices/sun_salutation/sun_salutation_session.c @@ -192,16 +192,17 @@ sun_salutation_draw_screen(InbeApp *app, int center_x, int center_y) FlintUIIconRowResult row; Texture2D pose; const char *step_label; + char step_title[32]; int step; int repetition; int repetitions; int pose_index; int text_w; int title_h = flint_ui_title_bar_height(); - int content_top = title_h + flint_px(42); - const char *warning_text = locale_get("sun_salutation_work_in_progress"); - int warning_font = flint_ui_font_small(); - int warning_y; + int subtitle_h = flint_px(34); + int content_top = title_h + subtitle_h + flint_px(8); + int subtitle_font = flint_ui_font_small(); + int subtitle_y; int image_bottom; int min_view_dim = view_width < view_height ? view_width : view_height; @@ -248,15 +249,20 @@ sun_salutation_draw_screen(InbeApp *app, int center_x, int center_y) pose = app->sun_salutation.poses[pose_index]; step_label = sun_salutation_step_label(step); - if(flint_ui_return_title_bar(app->icons[UI_ICON_TYPE_RETURN], step_label, title_h)) { + snprintf(step_title, sizeof(step_title), "Step %d / %d", step + 1, + SUN_SALUTATION_STEP_COUNT); + if(app->show_session_return_button && + flint_ui_return_title_bar(app->icons[UI_ICON_TYPE_RETURN], step_title, title_h)) { sun_salutation_request_exit(app); return; + } else if(!app->show_session_return_button) { + flint_ui_title_bar(step_title, title_h); } - text_w = flint_text_measure(warning_text, warning_font); - warning_y = title_h + flint_px(6); - flint_text_draw(warning_text, center_x - text_w / 2, - flint_ui_text_y(warning_text, warning_y, flint_px(28), warning_font), - warning_font, flint_theme_get_text()); + text_w = flint_text_measure(step_label, subtitle_font); + subtitle_y = title_h; + flint_text_draw(step_label, center_x - text_w / 2, + flint_ui_text_y(step_label, subtitle_y, subtitle_h, subtitle_font), + subtitle_font, flint_theme_get_text()); controls[0] = (FlintUIIconRowItem){app->icons[UI_ICON_TYPE_BACKWARD], step <= 0 && repetition <= 0}; diff --git a/src/practices/whm/whm_config.c b/src/practices/whm/whm_config.c index 3534f87a7..9c662ce4b 100644 --- a/src/practices/whm/whm_config.c +++ b/src/practices/whm/whm_config.c @@ -6,6 +6,7 @@ #include "flint_theme.h" #include "flint_ui.h" #include "raylib.h" +#include "screens/practice_screen.h" extern int view_width; extern int view_height; @@ -340,14 +341,9 @@ whm_config_scroll_page_content_height(int content_w, void *user_data) void whm_config_screen_draw(InbeApp *app) { - int integrated = app->inbe.screen == InbeScreenStart && - app->modal.type != UIModalPracticeConfig; - int title_h = integrated ? app_content_top_reserved(app) : flint_ui_title_bar_height(); + PracticeSubscreenLayout layout; int config_tab_h = flint_px(40); int config_tab_gap = flint_px(14); - int scroll_y; - int scroll_h; - int bottom_reserved = integrated ? app_content_bottom_reserved(app) : 0; int draw_breath_animation_menu = 0; int clicked_config_tab = -1; const char *config_tabs[] = { @@ -360,37 +356,23 @@ whm_config_screen_draw(InbeApp *app) if(app->practice_config_tab < 0 || app->practice_config_tab > 1) app->practice_config_tab = 0; - if(!integrated) { - if(flint_ui_return_title_bar(app->icons[UI_ICON_TYPE_RETURN], locale_get("practice_config_title"), title_h)) { - if(app->modal.active && app->modal.type == UIModalPracticeConfig) { - app_close_modal(app); - } else { - if(app->settings_dirty) - save_settings(app); - app->settings_scroll = 0; - app->practice_tab = PRACTICE_TAB_PLAY; - app_switch_screen(app, InbeScreenStart); - } - } - } + practice_screen_config_layout(app, UIModalPracticeConfig, + config_tab_h + config_tab_gap, &layout); + practice_screen_handle_config_title(app, locale_get("practice_config_title"), + UIModalPracticeConfig, NULL); - clicked_config_tab = whm_draw_subtab_bar(title_h, config_tab_h, config_tabs, 2, + clicked_config_tab = whm_draw_subtab_bar(layout.title_h, config_tab_h, config_tabs, 2, app->practice_config_tab); if(clicked_config_tab >= 0 && clicked_config_tab != app->practice_config_tab) { app->practice_config_tab = clicked_config_tab; app->settings_scroll = 0; } - scroll_y = title_h + config_tab_h + config_tab_gap; - scroll_h = view_height - scroll_y - bottom_reserved - - (integrated ? flint_px(8) : 0); - if(scroll_h < 0) - scroll_h = 0; { WhmConfigScrollPageContext page_ctx = {app}; FlintUIScrollPage page = ui_scroll_page_begin((FlintUIScrollPageSpec){ - .y = scroll_y, - .height = scroll_h, + .y = layout.scroll_y, + .height = layout.scroll_h, .max_content_width = flint_px(CONTENT_MAX_W), .min_content_width = flint_px(320), .scroll_offset = &app->settings_scroll, diff --git a/src/practices/whm/whm_manual.c b/src/practices/whm/whm_manual.c index af825c4a2..3ae4ec6d7 100644 --- a/src/practices/whm/whm_manual.c +++ b/src/practices/whm/whm_manual.c @@ -1,6 +1,7 @@ #include "whm_practice.h" #include "app.h" #include "screens/manual_screen.h" +#include "screens/practice_screen.h" #include "whm_session.h" #include "flint_locale.h" #include "flint_theme.h" @@ -173,17 +174,9 @@ manual_screen_start_exercise(InbeApp *app) void whm_manual_draw(InbeApp *app) { - int integrated = app->inbe.screen == InbeScreenStart && - app->modal.type != UIModalPracticeManual; - int title_h = integrated ? app_content_top_reserved(app) : flint_ui_title_bar_height(); - int nav_h = manual_screen_guide_nav_height(); - int bottom_reserved = integrated ? app_content_bottom_reserved(app) : 0; - int nav_y = view_height - bottom_reserved - nav_h; - int content_y = title_h; - int viewport_h = nav_y - content_y; + PracticeManualLayout layout; int body_font = flint_ui_font(); int footer_content_pad = flint_ui_font() / 2; - int content_area_h = viewport_h - footer_content_pad; /* For scissor mode and scroll calculations */ const char *title = locale_get("tutorial_title"); int step = app->tutorial_step; @@ -199,8 +192,9 @@ whm_manual_draw(InbeApp *app) default: break; } - if(!integrated && - flint_ui_return_title_bar(app->icons[UI_ICON_TYPE_RETURN], title, title_h)) + practice_screen_manual_layout(app, UIModalPracticeManual, (int)TUTORIAL_STEPS_COUNT, + 0, footer_content_pad, 0, &layout); + if(flint_ui_return_title_bar(app->icons[UI_ICON_TYPE_RETURN], title, layout.title_h)) whm_manual_close(app, 0); { @@ -217,8 +211,8 @@ whm_manual_draw(InbeApp *app) page_ctx = (WhmManualScrollPageContext){app, step, body_font, top_padding}; page = ui_scroll_page_begin((FlintUIScrollPageSpec){ - .y = content_y, - .height = content_area_h, + .y = layout.content_y, + .height = layout.content_h, .max_content_width = responsive_max_w, .min_content_width = flint_px(280), .scroll_offset = &app->manual_scroll, @@ -286,8 +280,8 @@ whm_manual_draw(InbeApp *app) manual_screen_guide_draw_nav(app, (ManualGuideNav){ .page = step, .page_count = (int)TUTORIAL_STEPS_COUNT, - .y = nav_y, - .h = nav_h, + .y = layout.nav_y, + .h = layout.nav_h, .show_left_on_first = 1, .start = manual_screen_start_exercise, .close = whm_manual_close diff --git a/src/practices/whm/whm_session.c b/src/practices/whm/whm_session.c index e7f1ce5d7..7ef93b5b1 100644 --- a/src/practices/whm/whm_session.c +++ b/src/practices/whm/whm_session.c @@ -782,19 +782,21 @@ stop_android_background_session(InbeApp *app) void session_update_screen(InbeApp *app, int center_x, int center_y, int *hover) { - int modal_result = 0; int breath_max_y = view_height - flint_px(44); int title_h = flint_ui_title_bar_height(); char title[32]; session_round_label(app, title, sizeof(title)); - if(flint_ui_return_title_bar(app->icons[UI_ICON_TYPE_RETURN], title, title_h)) { + if(app->show_session_return_button && + flint_ui_return_title_bar(app->icons[UI_ICON_TYPE_RETURN], title, title_h)) { if(app->session_paused) { stop_android_background_session(app); app_init(app); } else { app_open_modal(app, UIModalConfirmExitSession); } + } else if(!app->show_session_return_button) { + flint_ui_title_bar(title, title_h); } if(app->show_session_volume_control) { @@ -821,36 +823,18 @@ session_update_screen(InbeApp *app, int center_x, int center_y, int *hover) } if(app->modal.active && app->modal.type == UIModalConfirmExitSession) { - if(session_has_completed_rounds(app)) { - modal_result = ui_draw_modal_3btn(locale_get("exit_session_title"), - locale_get("save_completed_rounds_message"), - locale_get("cancel_button"), - locale_get("save_button"), - locale_get("discard_button")); - if(modal_result == 1) { - app_close_modal(app); - } else if(modal_result == 2) { + SessionExitModalResult result = + app_draw_session_exit_modal(session_has_completed_rounds(app), + locale_get("save_completed_rounds_message"), + locale_get("all_progress_lost_message")); + if(result == SessionExitModalCancel) { + app_close_modal(app); + } else if(result == SessionExitModalSave || result == SessionExitModalDiscard) { + if(result == SessionExitModalSave) session_ensure_results_saved(app); - stop_android_background_session(app); - app_close_modal(app); - app_init(app); - } else if(modal_result == 3) { - stop_android_background_session(app); - app_close_modal(app); - app_init(app); - } - } else { - modal_result = ui_draw_modal(locale_get("exit_session_title"), - locale_get("all_progress_lost_message"), - locale_get("cancel_button"), - locale_get("exit_button")); - if(modal_result == 1) { - app_close_modal(app); - } else if(modal_result == 2) { - stop_android_background_session(app); - app_close_modal(app); - app_init(app); - } + stop_android_background_session(app); + app_close_modal(app); + app_init(app); } return; } diff --git a/src/screens/habits_screen.c b/src/screens/habits_screen.c index 7d474522c..d979d37fd 100644 --- a/src/screens/habits_screen.c +++ b/src/screens/habits_screen.c @@ -414,7 +414,6 @@ habits_add_custom(InbeHabits *habits, const char *name, Color color, int sync_mode, int sync_activity) { InbeHabit *habit; - int number; char unique_name[INBE_HABIT_NAME_SIZE]; if(habits == NULL || habits->count >= INBE_HABIT_MAX) @@ -427,10 +426,9 @@ habits_add_custom(InbeHabits *habits, const char *name, Color color, final_name = unique_name; } - number = habits->count + 1; habit = &habits->items[habits->count]; memset(habit, 0, sizeof(*habit)); - snprintf(habit->id, sizeof(habit->id), "habit-%d", number); + storage_make_uuid(habit->id); copy_text(habit->name, sizeof(habit->name), final_name); habit->color = color; habit->color.a = 255; @@ -1084,6 +1082,37 @@ habits_overview_cell_size(int content_w) return cell; } +static int +habits_button_label_fits(const char *label, int button_w) +{ + int pad = flint_px(20); + + return flint_text_measure(label != NULL ? label : "", flint_ui_font_small()) + pad <= + button_w; +} + +static int +habits_overview_actions_stack(int content_w) +{ + int btn_gap = flint_px(8); + int half_w = (content_w - btn_gap) / 2; + + return !habits_button_label_fits(locale_get("habit_new_button"), half_w) || + !habits_button_label_fits(locale_get("habit_reorder_title"), half_w); +} + +static int +habits_reorder_move_buttons_stack(int content_w) +{ + int btn_w = flint_px(74); + int gap = flint_px(8); + + return content_w < flint_px(260) || + content_w < btn_w * 2 + gap || + !habits_button_label_fits(locale_get("move_up_button"), btn_w) || + !habits_button_label_fits(locale_get("move_down_button"), btn_w); +} + static int habits_overview_week_day_index(int offset) { @@ -1112,18 +1141,26 @@ habits_overview_content_height(int content_w, void *user_data) InbeApp *app = user_data; int rows = app != NULL && app->habits.count > 0 ? app->habits.count : 1; int cell = habits_overview_cell_size(content_w); + int action_h = flint_px(34); + + if(habits_overview_actions_stack(content_w)) + action_h = action_h * 2 + flint_px(8); return flint_px(52) + flint_px(20) + rows * (cell + flint_px(8)) + - flint_px(58); + flint_px(24) + action_h; } static int habits_reorder_content_height(int content_w, void *user_data) { InbeApp *app = user_data; - int row_h = content_w < flint_px(260) ? flint_px(78) : flint_px(48); + int row_h; int count = app != NULL ? app->habits.count : 0; + if(habits_reorder_move_buttons_stack(content_w)) + row_h = flint_px(36) + flint_px(32) * 2 + flint_px(8) * 2; + else + row_h = flint_px(48); return flint_px(70) + row_h * (count > 0 ? count : 1); } @@ -1169,9 +1206,9 @@ draw_habits_reorder(InbeApp *app, int content_top) int font = flint_ui_font(); int small = flint_ui_font_small(); int btn_h = flint_px(32); - int btn_w = flint_px(74); + int fixed_btn_w = flint_px(74); int gap = flint_px(8); - int stack_rows = w < flint_px(260); + int stack_rows = habits_reorder_move_buttons_stack(w); y = page.content_y + flint_px(16); @@ -1186,15 +1223,16 @@ draw_habits_reorder(InbeApp *app, int content_top) int row_y = y; int up_hover = 0; int down_hover = 0; - int controls_w = btn_w * 2 + gap; + int controls_w = fixed_btn_w * 2 + gap; int name_w = stack_rows ? w : w - controls_w - gap; habits_draw_fitted_text(app->habits.items[i].name, x, row_y + flint_px(7), name_w, font, flint_theme_get_text()); - if(stack_rows) + if(stack_rows) { row_y += flint_px(36); - if(ui_draw_generic_button(stack_rows ? x : x + w - btn_w * 2 - gap, - row_y, btn_w, btn_h, + } + if(ui_draw_generic_button(stack_rows ? x : x + w - fixed_btn_w * 2 - gap, + row_y, stack_rows ? w : fixed_btn_w, btn_h, locale_get("move_up_button"), UI_BUTTON_STYLE_SECONDARY, i == 0, &up_hover)) { if(habits_move(&app->habits, i, i - 1)) { @@ -1204,8 +1242,10 @@ draw_habits_reorder(InbeApp *app, int content_top) ui_scroll_page_end(page); return; } - if(ui_draw_generic_button(stack_rows ? x + btn_w + gap : x + w - btn_w, - row_y, btn_w, btn_h, + if(stack_rows) + row_y += btn_h + gap; + if(ui_draw_generic_button(stack_rows ? x : x + w - fixed_btn_w, + row_y, stack_rows ? w : fixed_btn_w, btn_h, locale_get("move_down_button"), UI_BUTTON_STYLE_SECONDARY, i == app->habits.count - 1, &down_hover)) { @@ -1216,7 +1256,7 @@ draw_habits_reorder(InbeApp *app, int content_top) ui_scroll_page_end(page); return; } - y += stack_rows ? flint_px(78) : flint_px(46); + y += stack_rows ? flint_px(108) : flint_px(46); habits_draw_divider(x, w, y - flint_px(6)); } @@ -1316,8 +1356,8 @@ draw_habits_overview(InbeApp *app, int content_top) done_count = habits_overview_done_today(app); snprintf(progress, sizeof(progress), locale_get("habits_done_count_label"), done_count, app->habits.count); - flint_text_draw(progress, content_x, y, FLINT_TEXT_24, flint_theme_get_text()); - y += flint_px(34); + flint_text_draw(progress, content_x, y, font, flint_theme_get_text()); + y += flint_px(28); if(app->habits.count <= 0) { flint_text_draw(locale_get("habit_empty_title"), content_x, y, font, @@ -1464,22 +1504,42 @@ draw_habits_overview(InbeApp *app, int content_top) } y += flint_px(10); - half_w = (content_w - btn_gap) / 2; - if(ui_draw_generic_button(content_x, y, half_w, btn_h, - locale_get("habit_new_button"), - UI_BUTTON_STYLE_SECONDARY, - app->habits.count >= INBE_HABIT_MAX, - &add_hover)) { - habit_edit_begin_new(app); - app->habits.screen_mode = HABITS_SCREEN_DETAIL; - app->habits.tab = HABIT_TAB_EDIT; - habits_persist_view_state(app); - } - if(ui_draw_generic_button(content_x + half_w + btn_gap, y, half_w, btn_h, - locale_get("habit_reorder_title"), - UI_BUTTON_STYLE_SECONDARY, - app->habits.count <= 0, &reorder_hover)) { - habits_enter_reorder(app); + if(habits_overview_actions_stack(content_w)) { + if(ui_draw_generic_button(content_x, y, content_w, btn_h, + locale_get("habit_new_button"), + UI_BUTTON_STYLE_SECONDARY, + app->habits.count >= INBE_HABIT_MAX, + &add_hover)) { + habit_edit_begin_new(app); + app->habits.screen_mode = HABITS_SCREEN_DETAIL; + app->habits.tab = HABIT_TAB_EDIT; + habits_persist_view_state(app); + } + y += btn_h + btn_gap; + if(ui_draw_generic_button(content_x, y, content_w, btn_h, + locale_get("habit_reorder_title"), + UI_BUTTON_STYLE_SECONDARY, + app->habits.count <= 0, &reorder_hover)) { + habits_enter_reorder(app); + } + } else { + half_w = (content_w - btn_gap) / 2; + if(ui_draw_generic_button(content_x, y, half_w, btn_h, + locale_get("habit_new_button"), + UI_BUTTON_STYLE_SECONDARY, + app->habits.count >= INBE_HABIT_MAX, + &add_hover)) { + habit_edit_begin_new(app); + app->habits.screen_mode = HABITS_SCREEN_DETAIL; + app->habits.tab = HABIT_TAB_EDIT; + habits_persist_view_state(app); + } + if(ui_draw_generic_button(content_x + half_w + btn_gap, y, half_w, btn_h, + locale_get("habit_reorder_title"), + UI_BUTTON_STYLE_SECONDARY, + app->habits.count <= 0, &reorder_hover)) { + habits_enter_reorder(app); + } } ui_scroll_page_end(page); diff --git a/src/screens/habits_screen.h b/src/screens/habits_screen.h index 5952583ca..08b610b63 100644 --- a/src/screens/habits_screen.h +++ b/src/screens/habits_screen.h @@ -15,7 +15,7 @@ enum { /* Habits-specific constants */ enum { INBE_HABIT_MAX = 10, - INBE_HABIT_ID_SIZE = 32, + INBE_HABIT_ID_SIZE = 40, INBE_HABIT_NAME_SIZE = 40, INBE_HABIT_DESCRIPTION_SIZE = 256, HABIT_LINKED_ENTRY_MAX = 128, diff --git a/src/screens/practice_screen.c b/src/screens/practice_screen.c index 9a47999cb..0397a739b 100644 --- a/src/screens/practice_screen.c +++ b/src/screens/practice_screen.c @@ -84,6 +84,92 @@ practice_activity_for_tab(int tab, int index) return index; } +int +practice_screen_subscreen_integrated(const InbeApp *app, int modal_type) +{ + return app != NULL && + app->inbe.screen == InbeScreenStart && + (int)app->modal.type != modal_type; +} + +void +practice_screen_config_layout(InbeApp *app, int modal_type, int content_top_gap, + PracticeSubscreenLayout *layout) +{ + int integrated = practice_screen_subscreen_integrated(app, modal_type); + int title_h = integrated ? app_content_top_reserved(app) : flint_ui_title_bar_height(); + int scroll_y = title_h + content_top_gap; + int bottom_reserved = integrated ? app_content_bottom_reserved(app) : 0; + int scroll_h = view_height - scroll_y - bottom_reserved - + (integrated ? flint_px(8) : 0); + + if(layout == NULL) + return; + if(scroll_h < 0) + scroll_h = 0; + *layout = (PracticeSubscreenLayout){ + integrated, + title_h, + scroll_y, + scroll_h + }; +} + +void +practice_screen_manual_layout(InbeApp *app, int modal_type, int page_count, + int content_top_gap, int content_bottom_gap, + int min_content_h, PracticeManualLayout *layout) +{ + int integrated = practice_screen_subscreen_integrated(app, modal_type); + int title_h = integrated ? app_content_top_reserved(app) : flint_ui_title_bar_height(); + int nav_h = page_count > 1 ? manual_screen_guide_nav_height() : 0; + int bottom_reserved = integrated ? app_content_bottom_reserved(app) : 0; + int nav_y = view_height - bottom_reserved - nav_h; + int content_y = title_h + content_top_gap; + int content_h = nav_y - content_y - content_bottom_gap; + + if(layout == NULL) + return; + if(content_h < min_content_h) + content_h = min_content_h; + *layout = (PracticeManualLayout){ + integrated, + title_h, + nav_y, + nav_h, + content_y, + content_h + }; +} + +int +practice_screen_handle_config_title(InbeApp *app, const char *title, int modal_type, + void (*leave_config)(InbeApp *app)) +{ + int title_h; + + if(app == NULL) + return 0; + title_h = practice_screen_subscreen_integrated(app, modal_type) + ? app_content_top_reserved(app) + : flint_ui_title_bar_height(); + if(!flint_ui_return_title_bar(app->icons[UI_ICON_TYPE_RETURN], title, title_h)) + return 0; + + if(app->modal.active && (int)app->modal.type == modal_type) { + app_close_modal(app); + } else { + if(app->settings_dirty) + save_settings(app); + if(leave_config != NULL) + leave_config(app); + app->settings_scroll = 0; + app->practice_tab = PRACTICE_TAB_PLAY; + app_switch_screen(app, InbeScreenStart); + } + return 1; +} + static Color practice_card_color_top(int exercise) { @@ -240,6 +326,7 @@ practice_select_home_card(InbeApp *app, int exercise) app->practice_tab = PRACTICE_TAB_PLAY; app->manual_scroll = 0; app->settings_scroll = 0; + app->practice_home_scroll = 0; app->tutorial_step = 0; app->practice_config_tab = 0; save_settings(app); @@ -284,14 +371,107 @@ practice_screen_draw_music_modal(InbeApp *app) meditation_music_draw_dropdown_menu(app); } +static int +practice_home_card_height(int y, int bottom_reserved) +{ + int card_h = view_height - y - bottom_reserved - flint_px(176); + + if(card_h < flint_px(180)) + card_h = flint_px(180); + if(card_h > flint_px(300)) + card_h = flint_px(300); + return card_h; +} + +static int +practice_home_action_gap(int content_w) +{ + return content_w < flint_px(340) ? flint_px(6) : flint_px(8); +} + +static int +practice_home_action_row_widths(int content_w, int *manual_w, int *config_w) +{ + int font = flint_ui_font_small(); + int pad = flint_px(8); + int gap = practice_home_action_gap(content_w); + int manual_min = flint_text_measure(locale_get("practice_manual_button"), font) + pad * 2; + int config_min = flint_text_measure(locale_get("practice_configure_button"), font) + pad * 2; + int half_w; + int available_w; + + if(content_w < manual_min + config_min + gap) + return 0; + + available_w = content_w - gap; + half_w = available_w / 2; + if(half_w >= manual_min && available_w - half_w >= config_min) { + *manual_w = half_w; + *config_w = available_w - half_w; + return 1; + } + + *manual_w = manual_min; + *config_w = available_w - *manual_w; + if(*config_w < config_min) { + *config_w = config_min; + *manual_w = available_w - *config_w; + } + return *manual_w >= manual_min && *config_w >= config_min; +} + +static int +practice_home_actions_share_row(const PracticeDefinition *practice, int content_w) +{ + int manual_w; + int config_w; + + return practice != NULL && + practice->draw_manual != NULL && + practice->draw_config != NULL && + practice_home_action_row_widths(content_w, &manual_w, &config_w); +} + +static int +practice_home_content_height(int content_w, void *user_data) +{ + InbeApp *app = user_data; + const PracticeDefinition *practice; + int scroll_y = app_content_top_reserved(app); + int bottom_reserved = app_content_bottom_reserved(app); + int y = flint_px(14); + int btn_h = flint_px(42); + int gap = practice_home_action_gap(content_w); + + (void)content_w; + if(app == NULL) + return 0; + + practice = practice_get(app->exercise_type); + y += btn_h + flint_px(18); + y += practice_home_card_height(scroll_y + y, bottom_reserved) + flint_px(18); + y += btn_h; + if(practice_home_actions_share_row(practice, content_w)) { + y += gap + btn_h; + } else { + if(practice->draw_manual != NULL) + y += gap + btn_h; + if(practice->draw_config != NULL) + y += gap + btn_h; + } + return y + flint_px(14); +} + void practice_screen_draw_home(InbeApp *app) { const PracticeDefinition *practice; - int top = app_content_top_reserved(app) + flint_px(14); + int scroll_y; + int scroll_h; int bottom_reserved = app_content_bottom_reserved(app); - int content_w = view_width - flint_px(32); - int max_w = flint_px(480); + FlintUIScrollPage page = {0}; + int use_scroll = 0; + int content_w; int x; int y; int card_w; @@ -308,13 +488,36 @@ practice_screen_draw_home(InbeApp *app) practice_clamp_activity_to_tab(app); flint_ui_title_bar(locale_get("practice_title"), app_content_top_reserved(app)); + scroll_y = app_content_top_reserved(app); + scroll_h = view_height - scroll_y - bottom_reserved; + if(scroll_h < 0) + scroll_h = 0; practice = practice_get(app->exercise_type); - if(content_w > max_w) - content_w = max_w; + content_w = view_width - flint_px(24); + if(content_w > flint_px(480)) + content_w = flint_px(480); if(content_w < flint_px(260)) - content_w = view_width - flint_px(20); + content_w = view_width - flint_px(16); x = (view_width - content_w) / 2; - y = top; + y = scroll_y + flint_px(14); + + if(practice_home_content_height(content_w, app) > scroll_h) { + use_scroll = 1; + page = ui_scroll_page_begin((FlintUIScrollPageSpec){ + .y = scroll_y, + .height = scroll_h, + .max_content_width = flint_px(480), + .min_content_width = flint_px(260), + .scroll_offset = &app->practice_home_scroll, + .content_height = practice_home_content_height, + .user_data = app + }); + content_w = page.content_w; + x = page.content_x; + y = page.content_y + flint_px(14); + } else { + app->practice_home_scroll = 0; + } if(ui_draw_generic_button(x, y, content_w, btn_h, locale_get("practice_music_title"), UI_BUTTON_STYLE_SECONDARY, 0, &hover)) { @@ -324,11 +527,7 @@ practice_screen_draw_home(InbeApp *app) y += btn_h + flint_px(18); card_w = content_w; - card_h = view_height - y - bottom_reserved - flint_px(176); - if(card_h < flint_px(180)) - card_h = flint_px(180); - if(card_h > flint_px(300)) - card_h = flint_px(300); + card_h = practice_home_card_height(y, bottom_reserved); card = (Rectangle){(float)x, (float)y, (float)card_w, (float)card_h}; banner = practice_card_banner(app, app->exercise_type); if(banner.id != 0) { @@ -381,15 +580,35 @@ practice_screen_draw_home(InbeApp *app) practice->start(app); } y += btn_h + gap; - if(practice->draw_manual != NULL && - ui_draw_generic_button(x, y, content_w, btn_h, locale_get("practice_manual_button"), - UI_BUTTON_STYLE_SECONDARY, 0, &hover)) - practice_screen_open_tab(app, PRACTICE_TAB_MANUAL); - y += btn_h + gap; - if(practice->draw_config != NULL && - ui_draw_generic_button(x, y, content_w, btn_h, locale_get("practice_configure_button"), - UI_BUTTON_STYLE_SECONDARY, 0, &hover)) - practice_screen_open_tab(app, PRACTICE_TAB_CONFIG); + if(practice_home_actions_share_row(practice, content_w)) { + int row_gap = practice_home_action_gap(content_w); + int manual_w; + int config_w; + practice_home_action_row_widths(content_w, &manual_w, &config_w); + if(ui_draw_generic_button(x, y, manual_w, btn_h, locale_get("practice_manual_button"), + UI_BUTTON_STYLE_SECONDARY, 0, &hover)) + practice_screen_open_tab(app, PRACTICE_TAB_MANUAL); + if(ui_draw_generic_button(x + manual_w + row_gap, y, config_w, + btn_h, locale_get("practice_configure_button"), + UI_BUTTON_STYLE_SECONDARY, 0, &hover)) + practice_screen_open_tab(app, PRACTICE_TAB_CONFIG); + } else { + if(practice->draw_manual != NULL && + ui_draw_generic_button(x, y, content_w, btn_h, locale_get("practice_manual_button"), + UI_BUTTON_STYLE_SECONDARY, 0, &hover)) { + practice_screen_open_tab(app, PRACTICE_TAB_MANUAL); + } + if(practice->draw_manual != NULL) + y += btn_h + gap; + if(practice->draw_config != NULL && + ui_draw_generic_button(x, y, content_w, btn_h, locale_get("practice_configure_button"), + UI_BUTTON_STYLE_SECONDARY, 0, &hover)) { + practice_screen_open_tab(app, PRACTICE_TAB_CONFIG); + } + } + + if(use_scroll) + ui_scroll_page_end(page); } const char * @@ -432,7 +651,6 @@ practice_screen_open_tab(InbeApp *app, int tab) app->practice_tab = PRACTICE_TAB_MANUAL; app->tutorial_step = 0; app->manual_scroll = 0; - app_open_modal(app, UIModalPracticeManual); app_switch_screen(app, InbeScreenStart); } else if(tab == PRACTICE_TAB_CONFIG) { if(practice_get(app->exercise_type)->draw_config == NULL) @@ -443,7 +661,6 @@ practice_screen_open_tab(InbeApp *app, int tab) app->practice_config_tab = 0; } app->practice_tab = PRACTICE_TAB_CONFIG; - app_open_modal(app, UIModalPracticeConfig); app_switch_screen(app, InbeScreenStart); } } @@ -529,6 +746,7 @@ practice_screen_draw_top_bar(InbeApp *app, int draw_menu) app->exercise_type = exercise_values[activity_index]; app->manual_scroll = 0; app->settings_scroll = 0; + app->practice_home_scroll = 0; app->tutorial_step = 0; app->practice_config_tab = 0; save_settings(app); @@ -545,6 +763,7 @@ practice_screen_draw_top_bar(InbeApp *app, int draw_menu) app->exercise_type = clicked_exercise; app->manual_scroll = 0; app->settings_scroll = 0; + app->practice_home_scroll = 0; app->tutorial_step = 0; app->practice_config_tab = 0; save_settings(app); @@ -642,18 +861,20 @@ practice_home_layout(InbeApp *app, Rectangle *music, Rectangle *card, Rectangle { int top = app_content_top_reserved(app) + flint_px(14); int bottom_reserved = ui_bottom_nav_height(); - int content_w = view_width - flint_px(32); + int content_w = view_width - flint_px(24); int max_w = flint_px(480); + const PracticeDefinition *practice = practice_get(app->exercise_type); int x; int y; int card_h; int btn_h = flint_px(42); - int gap = flint_px(12); + int gap; if(content_w > max_w) content_w = max_w; if(content_w < flint_px(260)) - content_w = view_width - flint_px(20); + content_w = view_width - flint_px(16); + gap = practice_home_action_gap(content_w); x = (view_width - content_w) / 2; y = top; @@ -674,12 +895,23 @@ practice_home_layout(InbeApp *app, Rectangle *music, Rectangle *card, Rectangle *start = (Rectangle){(float)x, (float)y, (float)content_w, (float)btn_h}; y += btn_h + gap; - if(manual != NULL) - *manual = (Rectangle){(float)x, (float)y, (float)content_w, (float)btn_h}; - y += btn_h + gap; - - if(config != NULL) - *config = (Rectangle){(float)x, (float)y, (float)content_w, (float)btn_h}; + if(practice_home_actions_share_row(practice, content_w)) { + int row_gap = practice_home_action_gap(content_w); + int manual_w; + int config_w; + practice_home_action_row_widths(content_w, &manual_w, &config_w); + if(manual != NULL) + *manual = (Rectangle){(float)x, (float)y, (float)manual_w, (float)btn_h}; + if(config != NULL) + *config = (Rectangle){(float)(x + manual_w + row_gap), (float)y, + (float)config_w, (float)btn_h}; + } else { + if(manual != NULL) + *manual = (Rectangle){(float)x, (float)y, (float)content_w, (float)btn_h}; + y += btn_h + gap; + if(config != NULL) + *config = (Rectangle){(float)x, (float)y, (float)content_w, (float)btn_h}; + } } static void diff --git a/src/screens/practice_screen.h b/src/screens/practice_screen.h index 9f72de1d5..1de892744 100644 --- a/src/screens/practice_screen.h +++ b/src/screens/practice_screen.h @@ -8,6 +8,22 @@ #define PRACTICE_CATEGORY_TOAST_TICKS 120 #define PRACTICE_CONFIG_TAB_LIST (-1) +typedef struct PracticeSubscreenLayout { + int integrated; + int title_h; + int scroll_y; + int scroll_h; +} PracticeSubscreenLayout; + +typedef struct PracticeManualLayout { + int integrated; + int title_h; + int nav_y; + int nav_h; + int content_y; + int content_h; +} PracticeManualLayout; + int practice_activity_count_for_tab(int tab); int practice_activity_for_tab(int tab, int index); const char *practice_activity_label(int exercise); @@ -16,6 +32,14 @@ int practice_is_visible(const InbeApp *app, int exercise); void practice_set_visible(InbeApp *app, int exercise, int visible); void practice_clamp_activity_to_tab(InbeApp *app); void practice_screen_open_tab(InbeApp *app, int tab); +int practice_screen_subscreen_integrated(const InbeApp *app, int modal_type); +void practice_screen_config_layout(InbeApp *app, int modal_type, int content_top_gap, + PracticeSubscreenLayout *layout); +void practice_screen_manual_layout(InbeApp *app, int modal_type, int page_count, + int content_top_gap, int content_bottom_gap, + int min_content_h, PracticeManualLayout *layout); +int practice_screen_handle_config_title(InbeApp *app, const char *title, int modal_type, + void (*leave_config)(InbeApp *app)); void practice_screen_draw_home(InbeApp *app); void practice_screen_draw_top_bar(InbeApp *app, int draw_menu); void practice_screen_draw_floating_actions(InbeApp *app); diff --git a/src/screens/profile_screen.c b/src/screens/profile_screen.c index 172b6dfc7..39ed8d97d 100644 --- a/src/screens/profile_screen.c +++ b/src/screens/profile_screen.c @@ -26,6 +26,23 @@ enum { PROFILE_GUIDE_STEPS = 3 }; +static Rectangle +profile_expanded_anchor(int x, int y, int w, int h) +{ + int pad = flint_px(6); + + return (Rectangle){(float)(x - pad), (float)(y - pad), + (float)(w + pad * 2), (float)(h + pad * 2)}; +} + +static void +profile_set_guide_anchor(Rectangle *anchor, int x, int y, int w, int h) +{ + if(anchor == NULL) + return; + *anchor = profile_expanded_anchor(x, y, w, h); +} + static void profile_format_size(char *out, size_t out_size, long long bytes) { @@ -69,8 +86,7 @@ profile_data_content_height(int content_w) static int profile_sync_content_height(int content_w) { - (void)content_w; - return flint_px(430); + return settings_sync_account_config_content_height(content_w); } static int @@ -175,49 +191,6 @@ profile_tab_title(int tab) } } -static void -profile_overview_column(int *x, int *w) -{ - flint_centered_column(flint_px(CONTENT_MAX_W), flint_page_side_padding(), x, w); -} - -static Rectangle -profile_guide_account_anchor(void) -{ - int x; - int w; - - profile_overview_column(&x, &w); - return (Rectangle){(float)(x - flint_px(6)), (float)flint_px(8), - (float)(w + flint_px(12)), (float)flint_px(70)}; -} - -static Rectangle -profile_guide_data_anchor(InbeApp *app) -{ - int x; - int w; - - (void)app; - profile_overview_column(&x, &w); - return (Rectangle){(float)(x - flint_px(6)), - (float)(flint_px(82) - flint_px(6)), - (float)(w + flint_px(12)), (float)flint_px(190)}; -} - -static Rectangle -profile_guide_social_anchor(InbeApp *app) -{ - int x; - int w; - - (void)app; - profile_overview_column(&x, &w); - return (Rectangle){(float)(x - flint_px(6)), - (float)(flint_px(278) - flint_px(6)), - (float)(w + flint_px(12)), (float)flint_px(102)}; -} - static void profile_screen_finish_first_run_guide(InbeApp *app) { @@ -254,25 +227,23 @@ profile_screen_draw_first_run_guide(InbeApp *app) { FlintUIGuideStep steps[PROFILE_GUIDE_STEPS]; FlintUIGuideResult result; - const char *social_guide_key; if(!profile_screen_first_run_guide_active(app)) return; + if(!app->profile_guide_anchors.valid) + return; - social_guide_key = sync_account_load(&(InbeSyncAccount){0}) - ? "profile_guide_social" - : "profile_guide_social_no_account"; steps[0] = (FlintUIGuideStep){ - .anchor = profile_guide_account_anchor(), + .anchor = app->profile_guide_anchors.account, .text = locale_get("profile_guide_account") }; steps[1] = (FlintUIGuideStep){ - .anchor = profile_guide_data_anchor(app), + .anchor = app->profile_guide_anchors.data, .text = locale_get("profile_guide_data") }; steps[2] = (FlintUIGuideStep){ - .anchor = profile_guide_social_anchor(app), - .text = locale_get(social_guide_key) + .anchor = app->profile_guide_anchors.social, + .text = locale_get("profile_guide_social_no_account") }; result = flint_ui_draw_guide_overlay((FlintUIGuideOverlay){ @@ -345,6 +316,9 @@ profile_draw_overview(InbeApp *app, int x, int w, int *y) int font = flint_ui_font(); int small = flint_ui_font_small(); int btn_h = flint_px(34); + int account_y; + int data_y; + int social_y; int hover_account = 0; int hover_data = 0; int hover_practices = 0; @@ -359,6 +333,7 @@ profile_draw_overview(InbeApp *app, int x, int w, int *y) char friend_text[64]; *y += flint_px(14); + account_y = *y; has_account = sync_account_load(&account); alias = storage_get_setting_text("sync_account_alias"); account_text[0] = '\0'; @@ -396,8 +371,11 @@ profile_draw_overview(InbeApp *app, int x, int w, int *y) *y += flint_px(38); } profile_draw_divider(x, w, *y); + profile_set_guide_anchor(&app->profile_guide_anchors.account, x, account_y, w, + *y - account_y); *y += flint_px(18); + data_y = *y; flint_text_draw(locale_get("profile_data_section"), x, *y, small, flint_darken(flint_theme_get_text(), 35)); *y += flint_px(24); @@ -418,8 +396,11 @@ profile_draw_overview(InbeApp *app, int x, int w, int *y) } *y += btn_h + flint_px(20); profile_draw_divider(x, w, *y); + profile_set_guide_anchor(&app->profile_guide_anchors.data, x, data_y, w, + *y - data_y); *y += flint_px(18); + social_y = *y; snprintf(friend_text, sizeof(friend_text), locale_get("profile_friends_count_format"), profile_social_friends_count(app)); snprintf(pending_text, sizeof(pending_text), locale_get("profile_pending_count_format"), @@ -443,6 +424,9 @@ profile_draw_overview(InbeApp *app, int x, int w, int *y) app->profile_scroll = 0; } *y += btn_h + flint_px(16); + profile_set_guide_anchor(&app->profile_guide_anchors.social, x, social_y, w, + *y - social_y); + app->profile_guide_anchors.valid = 1; } static void @@ -534,6 +518,8 @@ profile_screen_draw(InbeApp *app) FlintUIScrollPage page; int y; + app->profile_guide_anchors.valid = 0; + #if ANDROID_BUILD settings_data_handle_android_import(app); #elif defined(PLATFORM_WEB) diff --git a/src/screens/settings/settings_data.c b/src/screens/settings/settings_data.c index 742a5ee04..a4b1251a5 100644 --- a/src/screens/settings/settings_data.c +++ b/src/screens/settings/settings_data.c @@ -354,7 +354,9 @@ settings_data_draw_sync_status(int x, int w, int *y) flint_text_draw(line, x + left_w, row_y, font, text_color); row_y += flint_px(22); - if(status.review_pending) + if(status.protocol_upgrade_available) + snprintf(line, sizeof(line), "Upgrade Inner Breeze"); + else if(status.review_pending) snprintf(line, sizeof(line), "Review pending"); else if(status.repair_pending) snprintf(line, sizeof(line), "Repair sync pending"); @@ -365,7 +367,8 @@ settings_data_draw_sync_status(int x, int w, int *y) else snprintf(line, sizeof(line), "Ready"); flint_text_draw(line, x, row_y, font, - (status.review_pending || status.repair_pending) ? warn_color : text_color); + (status.protocol_upgrade_available || status.review_pending || + status.repair_pending) ? warn_color : text_color); *y += flint_px(74); } diff --git a/src/screens/settings/settings_device.c b/src/screens/settings/settings_device.c index 8042afc0e..cd04c90f7 100644 --- a/src/screens/settings/settings_device.c +++ b/src/screens/settings/settings_device.c @@ -23,19 +23,25 @@ int settings_device_content_height(int content_w) { int height = flint_px(76) + flint_px(76) + flint_px(40); +#if !ANDROID_BUILD && !defined(PLATFORM_WEB) int label_w = content_w > 0 ? content_w : flint_px(240); +#endif #if !ANDROID_BUILD && !defined(PLATFORM_WEB) height += flint_px(50); #endif +#if !ANDROID_BUILD && !defined(PLATFORM_WEB) height += settings_ui_toggle_row_height(locale_get("on_screen_keyboard_label"), label_w); +#endif return height; } void settings_device_draw(InbeApp *app, int x, int w, int *y, SettingsDeviceState *state) { +#if !ANDROID_BUILD && !defined(PLATFORM_WEB) int keyboard_toggle; +#endif const char *orientation_options[] = { locale_get("orientation_system"), locale_get("orientation_portrait"), @@ -47,7 +53,11 @@ settings_device_draw(InbeApp *app, int x, int w, int *y, SettingsDeviceState *st if(app == NULL || y == NULL || state == NULL) return; +#if ANDROID_BUILD || defined(PLATFORM_WEB) + app->on_screen_keyboard_enabled = 1; +#else keyboard_toggle = app->on_screen_keyboard_enabled; +#endif flint_text_draw(locale_get("language_label"), x, *y, flint_ui_font(), flint_theme_get_text()); if(language_dropdown_button(app, 101, x, *y + flint_px(26), w, flint_px(36), @@ -81,11 +91,12 @@ settings_device_draw(InbeApp *app, int x, int w, int *y, SettingsDeviceState *st *y += flint_px(50); #endif - if(settings_ui_draw_toggle_row(x, w, y, locale_get("on_screen_keyboard_label"), - &keyboard_toggle)) { +#if !ANDROID_BUILD && !defined(PLATFORM_WEB) + if(settings_ui_commit_toggle_row(app, x, w, y, locale_get("on_screen_keyboard_label"), + &keyboard_toggle, 0)) { app->on_screen_keyboard_enabled = keyboard_toggle; - app->settings_dirty = 1; } +#endif } void diff --git a/src/screens/settings/settings_screen.c b/src/screens/settings/settings_screen.c index c847cd55d..ee775434b 100644 --- a/src/screens/settings/settings_screen.c +++ b/src/screens/settings/settings_screen.c @@ -251,11 +251,13 @@ settings_screen_draw(InbeApp *app) } ui_set_dropdown_clip_top(tab_content_start_y); + ui_set_dropdown_clip_bottom(view_height - app_content_bottom_reserved(app)); if(app->settings_tab == SETTINGS_TAB_THEME) settings_theme_handle_overlays(app, &app->theme_state); else if(app->settings_tab == SETTINGS_TAB_DEVICE) settings_device_handle_overlays(app, &device_state); ui_set_dropdown_clip_top(0); + ui_set_dropdown_clip_bottom(0); if(IsMouseButtonReleased(MOUSE_BUTTON_LEFT) && app->settings_dirty) save_settings(app); diff --git a/src/screens/settings/settings_session.c b/src/screens/settings/settings_session.c index 282aaf6ab..3eedfba1b 100644 --- a/src/screens/settings/settings_session.c +++ b/src/screens/settings/settings_session.c @@ -16,6 +16,8 @@ settings_session_content_height(int content_w) height += settings_ui_toggle_row_height(locale_get("show_session_volume_control_label"), label_w); + height += settings_ui_toggle_row_height(locale_get("show_session_return_button_label"), + label_w); height += settings_ui_toggle_row_height(locale_get("play_in_background_label"), label_w); return height; @@ -26,34 +28,43 @@ settings_session_draw(InbeApp *app, int x, int w, int *y) { int sound_volume; int show_session_volume; + int show_session_return; int play_in_background; if(app == NULL || y == NULL) return; sound_volume = app->sound_volume; - if(ui_draw_slider(6, x, *y, w, locale_get("volume_label"), - SETTINGS_VOLUME_MIN, SETTINGS_VOLUME_MAX, &sound_volume, "")) { + if(settings_ui_commit_slider_row(app, 6, x, w, y, + flint_px(SETTINGS_SESSION_SLIDER_ROW_H), + locale_get("volume_label"), + SETTINGS_VOLUME_MIN, SETTINGS_VOLUME_MAX, + &sound_volume, "", 0)) { app->sound_volume = sound_volume; - app->settings_dirty = 1; save_settings(app); } - *y += flint_px(SETTINGS_SESSION_SLIDER_ROW_H); show_session_volume = app->show_session_volume_control; - if(settings_ui_draw_toggle_row(x, w, y, - locale_get("show_session_volume_control_label"), - &show_session_volume)) { + if(settings_ui_commit_toggle_row(app, x, w, y, + locale_get("show_session_volume_control_label"), + &show_session_volume, 0)) { app->show_session_volume_control = show_session_volume; - app->settings_dirty = 1; + save_settings(app); + } + + show_session_return = app->show_session_return_button; + if(settings_ui_commit_toggle_row(app, x, w, y, + locale_get("show_session_return_button_label"), + &show_session_return, 0)) { + app->show_session_return_button = show_session_return; save_settings(app); } play_in_background = app->inbe.play_in_background; - if(settings_ui_draw_toggle_row(x, w, y, locale_get("play_in_background_label"), - &play_in_background)) { + if(settings_ui_commit_toggle_row(app, x, w, y, + locale_get("play_in_background_label"), + &play_in_background, 0)) { app->inbe.play_in_background = play_in_background; - app->settings_dirty = 1; save_settings(app); } } diff --git a/src/screens/settings/settings_sync_account.c b/src/screens/settings/settings_sync_account.c index 48275ffa0..87df20aaf 100644 --- a/src/screens/settings/settings_sync_account.c +++ b/src/screens/settings/settings_sync_account.c @@ -359,6 +359,164 @@ settings_sync_text_style(void) }; } +static int +settings_sync_button_min_width(const char *label) +{ + return flint_text_measure(label != NULL ? label : "", flint_ui_font_small()) + + flint_px(20); +} + +static int +settings_sync_button_group_fits(const FlintUIButtonRowItem *items, int start, int count, + int width, int gap) +{ + int button_w; + + if(items == NULL || count <= 0 || width <= 0) + return 0; + button_w = (width - gap * (count - 1)) / count; + if(button_w <= 0) + return 0; + for(int i = 0; i < count; i++) { + if(settings_sync_button_min_width(items[start + i].label) > button_w) + return 0; + } + return 1; +} + +static int +settings_sync_button_group_count(const FlintUIButtonRowItem *items, int start, int count, + int width, int gap) +{ + for(int row_count = count; row_count > 1; row_count--) { + if(settings_sync_button_group_fits(items, start, row_count, width, gap)) + return row_count; + } + return 1; +} + +static int +settings_sync_draw_adaptive_button_row(FlintUIButtonRow row, int *height_out) +{ + int clicked = -1; + int gap = row.gap > 0 ? row.gap : flint_px(10); + int draw_y = row.y; + int index = 0; + + if(height_out != NULL) + *height_out = 0; + if(row.items == NULL || row.count <= 0 || row.width <= 0 || row.height <= 0) + return -1; + + while(index < row.count) { + int count = settings_sync_button_group_count(row.items, index, + row.count - index, + row.width, gap); + int button_w = (row.width - gap * (count - 1)) / count; + + for(int i = 0; i < count; i++) { + int hover = 0; + int item_index = index + i; + int button_x = row.x + i * (button_w + gap); + int draw_w = i == count - 1 ? row.x + row.width - button_x : button_w; + + if(ui_draw_generic_button(button_x, draw_y, draw_w, row.height, + row.items[item_index].label, + row.items[item_index].style, + row.items[item_index].disabled, + &hover)) + clicked = item_index; + } + index += count; + draw_y += row.height; + if(index < row.count) + draw_y += gap; + } + + if(height_out != NULL) + *height_out = draw_y - row.y; + return clicked; +} + +static int +settings_sync_adaptive_button_row_height(const FlintUIButtonRowItem *items, int count, + int width, int button_h, int gap) +{ + int height = 0; + int index = 0; + + if(items == NULL || count <= 0 || width <= 0 || button_h <= 0) + return 0; + while(index < count) { + int row_count = settings_sync_button_group_count(items, index, count - index, + width, gap); + height += button_h; + index += row_count; + if(index < count) + height += gap; + } + return height; +} + +int +settings_sync_account_config_content_height(int content_w) +{ + InbeSyncAccount account; + int has_account = sync_account_load(&account); + int btn_h = flint_px(36); + int gap = flint_px(10); + int h = 0; + char display[96]; + const char *alias; + + if(content_w <= 0) + content_w = flint_px(320); + + if(!has_account) { + FlintUIButtonRowItem buttons[2] = { + {locale_get("sync_create_account_button"), UI_BUTTON_STYLE_PRIMARY, 0}, + {locale_get("sync_import_key_button"), UI_BUTTON_STYLE_PRIMARY, 0} + }; + h += flint_px(12); + h += settings_sync_adaptive_button_row_height(buttons, 2, content_w, btn_h, gap); + h += flint_px(18); + h += flint_px(42); + return h; + } + + alias = storage_get_setting_text(INBE_SYNC_ACCOUNT_ALIAS_KEY); + if(alias != NULL && alias[0] != '\0') + snprintf(display, sizeof(display), "@%s", alias); + else + settings_compact_public_id(account.public_id, display, sizeof(display)); + + h += flint_px(18); + h += flint_ui_readonly_text_box_height(display, flint_ui_font_small(), + content_w, settings_sync_text_style(), 0); + h += flint_px(8); + h += flint_px(18) + btn_h + flint_px(12); + h += btn_h + flint_px(12); + { + FlintUIButtonRowItem buttons[3] = { + {locale_get("sync_copy_id_button"), UI_BUTTON_STYLE_SECONDARY, 0}, + {locale_get("sync_alias_button"), UI_BUTTON_STYLE_SECONDARY, 0}, + {locale_get("sync_backup_key_button"), UI_BUTTON_STYLE_SECONDARY, 0} + }; + h += settings_sync_adaptive_button_row_height(buttons, 3, content_w, btn_h, gap); + h += flint_px(12); + } + { + FlintUIButtonRowItem buttons[2] = { + {locale_get("sync_logout_button"), UI_BUTTON_STYLE_SECONDARY, 0}, + {locale_get("sync_clear_remote_data_button"), UI_BUTTON_STYLE_DANGER, 0} + }; + h += settings_sync_adaptive_button_row_height(buttons, 2, content_w, btn_h, gap); + h += flint_px(12); + } + h += flint_px(42); + return h; +} + void settings_sync_account_draw(InbeApp *app, int x, int w, int *y) { @@ -395,7 +553,8 @@ settings_sync_account_draw(InbeApp *app, int x, int w, int *y) {locale_get("sync_alias_button"), UI_BUTTON_STYLE_SECONDARY, 0}, {locale_get("sync_backup_key_button"), UI_BUTTON_STYLE_PRIMARY, 0} }; - int clicked = ui_draw_button_row((FlintUIButtonRow){ + int row_h = 0; + int clicked = settings_sync_draw_adaptive_button_row((FlintUIButtonRow){ .x = x, .y = *y, .width = w, @@ -403,7 +562,7 @@ settings_sync_account_draw(InbeApp *app, int x, int w, int *y) .gap = gap, .items = buttons, .count = 3 - }); + }, &row_h); if(clicked == 0) { SetClipboardText(account.public_id); @@ -413,8 +572,9 @@ settings_sync_account_draw(InbeApp *app, int x, int w, int *y) } else if(clicked == 2) { app_open_modal(app, UIModalSyncAccountBackup); } + *y += row_h; } - *y += btn_h + flint_px(16); + *y += flint_px(16); } void @@ -436,9 +596,10 @@ settings_sync_account_draw_config(InbeApp *app, int x, int w, int *y) {locale_get("sync_import_key_button"), UI_BUTTON_STYLE_PRIMARY, 0} }; int clicked; + int row_h = 0; *y += flint_px(12); - clicked = ui_draw_button_row((FlintUIButtonRow){ + clicked = settings_sync_draw_adaptive_button_row((FlintUIButtonRow){ .x = x, .y = *y, .width = w, @@ -446,14 +607,14 @@ settings_sync_account_draw_config(InbeApp *app, int x, int w, int *y) .gap = gap, .items = buttons, .count = 2 - }); + }, &row_h); if(clicked == 0) { has_account = settings_sync_create_account(app, &account); } else if(clicked == 1) { if(!settings_start_sync_key_import(app)) settings_screen_set_status_error(locale_get("sync_private_key_import_failed")); } - *y += btn_h + flint_px(18); + *y += row_h + flint_px(18); } if(!has_account) { @@ -501,7 +662,8 @@ settings_sync_account_draw_config(InbeApp *app, int x, int w, int *y) {locale_get("sync_alias_button"), UI_BUTTON_STYLE_SECONDARY, 0}, {locale_get("sync_backup_key_button"), UI_BUTTON_STYLE_SECONDARY, 0} }; - int clicked = ui_draw_button_row((FlintUIButtonRow){ + int row_h = 0; + int clicked = settings_sync_draw_adaptive_button_row((FlintUIButtonRow){ .x = x, .y = *y, .width = w, @@ -509,7 +671,7 @@ settings_sync_account_draw_config(InbeApp *app, int x, int w, int *y) .gap = gap, .items = buttons, .count = 3 - }); + }, &row_h); if(clicked == 0) { SetClipboardText(account.public_id); @@ -519,15 +681,17 @@ settings_sync_account_draw_config(InbeApp *app, int x, int w, int *y) } else if(clicked == 2) { app_open_modal(app, UIModalSyncAccountBackup); } + *y += row_h; } - *y += btn_h + flint_px(12); + *y += flint_px(12); { FlintUIButtonRowItem buttons[2] = { {locale_get("sync_logout_button"), UI_BUTTON_STYLE_SECONDARY, 0}, {locale_get("sync_clear_remote_data_button"), UI_BUTTON_STYLE_DANGER, 0} }; - int clicked = ui_draw_button_row((FlintUIButtonRow){ + int row_h = 0; + int clicked = settings_sync_draw_adaptive_button_row((FlintUIButtonRow){ .x = x, .y = *y, .width = w, @@ -535,14 +699,15 @@ settings_sync_account_draw_config(InbeApp *app, int x, int w, int *y) .gap = gap, .items = buttons, .count = 2 - }); + }, &row_h); if(clicked == 0) { settings_sync_account_logout(app); } else if(clicked == 1) { app_open_modal(app, UIModalConfirmDeleteSyncAccount); } + *y += row_h; } - *y += btn_h + flint_px(12); + *y += flint_px(12); settings_screen_draw_status_reserved(x, y, flint_px(42)); (void)font; @@ -662,7 +827,7 @@ settings_sync_account_draw_alias_modal(InbeApp *app) UI_BUTTON_STYLE_PRIMARY, !settings_sync_alias_valid(app->sync_alias_input) || unchanged_alias} }; - int clicked = ui_draw_button_row((FlintUIButtonRow){ + int clicked = settings_sync_draw_adaptive_button_row((FlintUIButtonRow){ .x = frame.content_x, .y = y, .width = frame.content_w, @@ -670,7 +835,7 @@ settings_sync_account_draw_alias_modal(InbeApp *app) .gap = gap, .items = buttons, .count = 2 - }); + }, NULL); if(clicked == 0) return 3; if(clicked == 1 || (commit && settings_sync_alias_valid(app->sync_alias_input) && !unchanged_alias)) { @@ -730,7 +895,7 @@ settings_sync_account_draw_public_id_modal(InbeApp *app) {locale_get("sync_copy_id_button"), UI_BUTTON_STYLE_PRIMARY, 0}, {locale_get("close_button"), UI_BUTTON_STYLE_SECONDARY, 0} }; - int clicked = ui_draw_button_row((FlintUIButtonRow){ + int clicked = settings_sync_draw_adaptive_button_row((FlintUIButtonRow){ .x = frame.content_x, .y = y, .width = frame.content_w, @@ -738,7 +903,7 @@ settings_sync_account_draw_public_id_modal(InbeApp *app) .gap = gap, .items = buttons, .count = 2 - }); + }, NULL); if(clicked == 0) { SetClipboardText(account.public_id); settings_screen_set_status_success(locale_get("sync_public_id_copied"), NULL); diff --git a/src/screens/settings/settings_sync_account.h b/src/screens/settings/settings_sync_account.h index f29867396..c79fea087 100644 --- a/src/screens/settings/settings_sync_account.h +++ b/src/screens/settings/settings_sync_account.h @@ -9,6 +9,7 @@ typedef int (*SettingsSyncKeyImportDialog)(InbeApp *app); void settings_sync_account_set_save_dialog(SettingsSyncKeySaveDialog callback); void settings_sync_account_set_import_dialog(SettingsSyncKeyImportDialog callback); void settings_sync_account_draw(InbeApp *app, int x, int w, int *y); +int settings_sync_account_config_content_height(int content_w); void settings_sync_account_draw_config(InbeApp *app, int x, int w, int *y); void settings_sync_account_clear_remote_confirmed(InbeApp *app); int settings_sync_account_draw_backup_modal(InbeApp *app); diff --git a/src/screens/settings/settings_theme.c b/src/screens/settings/settings_theme.c index 9a9c689df..5df770a78 100644 --- a/src/screens/settings/settings_theme.c +++ b/src/screens/settings/settings_theme.c @@ -15,7 +15,11 @@ int settings_theme_content_height(int content_w) { (void)content_w; +#if defined(PLATFORM_WEB) + return flint_px(228); +#else return flint_px(228) + flint_px(60); +#endif } void @@ -36,6 +40,10 @@ settings_theme_draw(InbeApp *app, int x, int w, int *y, SettingsThemeState *stat state->draw_theme_mode_menu = 1; *y += flint_px(76); +#if defined(PLATFORM_WEB) + app->transition_mode = APP_TRANSITION_NONE; + state->draw_transition_menu = 0; +#else { const char *transition_options[2]; transition_options[APP_TRANSITION_NONE] = locale_get("transition_none"); @@ -47,6 +55,7 @@ settings_theme_draw(InbeApp *app, int x, int w, int *y, SettingsThemeState *stat } state->draw_transition_menu = 1; *y += flint_px(76); +#endif // Draw single theme circle button flint_text_draw(locale_get("theme_label"), x, *y, flint_ui_font(), flint_theme_get_text()); @@ -102,6 +111,7 @@ settings_theme_handle_overlays(InbeApp *app, SettingsThemeState *state) save_settings(app); } +#if !defined(PLATFORM_WEB) if(state->draw_transition_menu && ui_draw_dropdown_menu(104)) transition_changed = 1; if(transition_changed) { @@ -109,6 +119,10 @@ settings_theme_handle_overlays(InbeApp *app, SettingsThemeState *state) app->settings_dirty = 1; save_settings(app); } +#else + (void)transition_changed; + app->transition_mode = APP_TRANSITION_NONE; +#endif } void diff --git a/src/screens/settings/settings_ui.c b/src/screens/settings/settings_ui.c index 63450d85f..838ef2e0b 100644 --- a/src/screens/settings/settings_ui.c +++ b/src/screens/settings/settings_ui.c @@ -1,5 +1,6 @@ #include "settings_ui.h" +#include "app.h" #include "flint_locale.h" #include "flint_ui.h" @@ -55,3 +56,37 @@ settings_ui_draw_toggle_row(int x, int w, int *y, const char *label, int *value) *y += row_h; return 0; } + +int +settings_ui_commit_toggle_row(InbeApp *app, int x, int w, int *y, + const char *label, int *value, int save_now) +{ + if(settings_ui_draw_toggle_row(x, w, y, label, value)) { + if(app != NULL) { + app->settings_dirty = 1; + if(save_now) + save_settings(app); + } + return 1; + } + return 0; +} + +int +settings_ui_commit_slider_row(InbeApp *app, int id, int x, int w, int *y, + int row_h, const char *label, int min, int max, + int *value, const char *suffix, int save_now) +{ + int changed; + + if(y == NULL) + return 0; + changed = ui_draw_slider(id, x, *y, w, label, min, max, value, suffix); + if(changed && app != NULL) { + app->settings_dirty = 1; + if(save_now) + save_settings(app); + } + *y += row_h; + return changed; +} diff --git a/src/screens/settings/settings_ui.h b/src/screens/settings/settings_ui.h index 962123b82..af06d9e7e 100644 --- a/src/screens/settings/settings_ui.h +++ b/src/screens/settings/settings_ui.h @@ -1,7 +1,14 @@ #ifndef INBE_SETTINGS_UI_H #define INBE_SETTINGS_UI_H +#include "app_fwd.h" + int settings_ui_toggle_row_height(const char *label, int w); int settings_ui_draw_toggle_row(int x, int w, int *y, const char *label, int *value); +int settings_ui_commit_toggle_row(InbeApp *app, int x, int w, int *y, + const char *label, int *value, int save_now); +int settings_ui_commit_slider_row(InbeApp *app, int id, int x, int w, int *y, + int row_h, const char *label, int min, int max, + int *value, const char *suffix, int save_now); #endif diff --git a/src/storage/db.c b/src/storage/db.c index 55f69585f..34163c602 100644 --- a/src/storage/db.c +++ b/src/storage/db.c @@ -186,7 +186,7 @@ schema_create(void) " updated_at INTEGER NOT NULL," " PRIMARY KEY(user_id,key)" ");" - "CREATE TABLE IF NOT EXISTS social_cache(" + "CREATE TABLE IF NOT EXISTS social_snapshots(" " user_id TEXT NOT NULL," " kind TEXT NOT NULL," " json TEXT NOT NULL," @@ -456,7 +456,7 @@ migrate_schema(void) " sent_at INTEGER NOT NULL DEFAULT 0," " acked_at INTEGER NOT NULL DEFAULT 0" ");" - "CREATE TABLE IF NOT EXISTS social_cache(" + "CREATE TABLE IF NOT EXISTS social_snapshots(" " user_id TEXT NOT NULL," " kind TEXT NOT NULL," " json TEXT NOT NULL," @@ -464,6 +464,11 @@ migrate_schema(void) " PRIMARY KEY(user_id,kind)" ");")) return 0; + if(table_exists("social_cache")) { + exec_sql("INSERT OR REPLACE INTO social_snapshots(user_id,kind,json,updated_at) " + "SELECT user_id,kind,json,updated_at FROM social_cache;" + "DROP TABLE social_cache;"); + } if(!had_outbox) { if(!exec_sql( "INSERT OR IGNORE INTO sync_outbox(entity_type,entity_id,local_date,queued_at) " @@ -499,6 +504,7 @@ storage_init(const char *root) if(!schema_create() || !migrate_schema() || !load_or_create_user()) return 0; storage_migrate_default_habit_ids(); + storage_migrate_habit_ids_to_uuid(); storage_materialize_session_habit_days(); migrate_legacy_file_sessions_once(); return 1; diff --git a/src/storage/db.h b/src/storage/db.h index d7731d06f..4fd21521f 100644 --- a/src/storage/db.h +++ b/src/storage/db.h @@ -45,6 +45,7 @@ int storage_enqueue_sync_session(const char *session_id); int storage_has_sync_account(void); int storage_materialize_session_habit_days(void); int storage_migrate_default_habit_ids(void); +int storage_migrate_habit_ids_to_uuid(void); int storage_sync_review_write_json(const char *json); void storage_sync_review_delete_json(void); int insert_session_at_ex(long long started_at, int local_date, const int *round_times, diff --git a/src/storage/import.c b/src/storage/import.c index 03eaa21bd..34875f467 100644 --- a/src/storage/import.c +++ b/src/storage/import.c @@ -216,6 +216,79 @@ resolve_import_habit_id(const char *import_id, const char *name, return out[0] != '\0'; } +static int +import_prepare_habit_upsert(sqlite3_stmt **stmt) +{ + if(stmt == NULL || g_storage.db == NULL) + return 0; + return sqlite3_prepare_v2(g_storage.db, + "INSERT OR REPLACE INTO habits(id,user_id,name,color_r,color_g,color_b,sync_mode,sync_activity,counter_enabled,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,?10,0,?11)", + -1, stmt, NULL) == SQLITE_OK; +} + +static int +import_upsert_habit(sqlite3_stmt *stmt, const char *id, const char *name, + Color color, int sync_mode, int sync_activity, + int counter_enabled, int sort_order, long long updated_at) +{ + int rc; + + if(stmt == NULL || id == NULL || id[0] == '\0' || + name == NULL || name[0] == '\0') + return 0; + sqlite3_reset(stmt); + sqlite3_clear_bindings(stmt); + bind_text(stmt, 1, id); + bind_text(stmt, 2, g_storage.user_id); + bind_text(stmt, 3, name); + sqlite3_bind_int(stmt, 4, color.r); + sqlite3_bind_int(stmt, 5, color.g); + sqlite3_bind_int(stmt, 6, color.b); + sqlite3_bind_int(stmt, 7, sync_mode); + sqlite3_bind_int(stmt, 8, sync_activity); + sqlite3_bind_int(stmt, 9, counter_enabled ? 1 : 0); + sqlite3_bind_int(stmt, 10, sort_order); + sqlite3_bind_int64(stmt, 11, updated_at); + rc = sqlite3_step(stmt); + return rc == SQLITE_DONE; +} + +static int +import_prepare_habit_day_upsert(sqlite3_stmt **stmt) +{ + if(stmt == NULL || g_storage.db == NULL) + return 0; + return sqlite3_prepare_v2(g_storage.db, + "INSERT INTO habit_days(habit_id,local_date,completed,count,updated_at) " + "VALUES(?1,?2,?3,?4,?5) " + "ON CONFLICT(habit_id,local_date) DO UPDATE SET " + "count=CASE WHEN habit_days.count>excluded.count THEN habit_days.count ELSE excluded.count END," + "completed=CASE WHEN habit_days.count>0 OR excluded.count>0 OR habit_days.completed!=0 OR excluded.completed!=0 THEN 1 ELSE 0 END," + "updated_at=CASE WHEN excluded.count>habit_days.count THEN excluded.updated_at ELSE habit_days.updated_at END", + -1, stmt, NULL) == SQLITE_OK; +} + +static int +import_upsert_habit_day(sqlite3_stmt *stmt, const char *habit_id, int local_date, + int completed, int count, long long updated_at) +{ + int rc; + + if(stmt == NULL || habit_id == NULL || habit_id[0] == '\0' || local_date <= 0) + return 0; + sqlite3_reset(stmt); + sqlite3_clear_bindings(stmt); + bind_text(stmt, 1, habit_id); + sqlite3_bind_int(stmt, 2, local_date); + sqlite3_bind_int(stmt, 3, completed ? 1 : 0); + sqlite3_bind_int(stmt, 4, count); + sqlite3_bind_int64(stmt, 5, updated_at); + rc = sqlite3_step(stmt); + return rc == SQLITE_DONE; +} + int storage_export_zip(const char *path) { @@ -644,6 +717,10 @@ import_tickmate_db(sqlite3 *src) if(sqlite3_prepare_v2(src, track_sql, -1, &stmt, NULL) != SQLITE_OK) return 0; + if(!import_prepare_habit_upsert(&write_stmt)) { + sqlite3_finalize(stmt); + return 0; + } exec_sql("BEGIN IMMEDIATE"); while(sqlite3_step(stmt) == SQLITE_ROW) { @@ -662,30 +739,15 @@ import_tickmate_db(sqlite3 *src) if(!resolve_import_habit_id(import_habit_id, name, local_habit_id, sizeof(local_habit_id))) continue; - if(sqlite3_prepare_v2(g_storage.db, - "INSERT OR REPLACE INTO habits(id,user_id,name,color_r,color_g,color_b,sync_mode,sync_activity,counter_enabled,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,?10,0,?11)", - -1, &write_stmt, NULL) != SQLITE_OK) - continue; - bind_text(write_stmt, 1, local_habit_id); - bind_text(write_stmt, 2, g_storage.user_id); - bind_text(write_stmt, 3, name); - sqlite3_bind_int(write_stmt, 4, color.r); - sqlite3_bind_int(write_stmt, 5, color.g); - sqlite3_bind_int(write_stmt, 6, color.b); - sqlite3_bind_int(write_stmt, 7, INBE_HABIT_SYNC_NONE); - sqlite3_bind_int(write_stmt, 8, 0); - sqlite3_bind_int(write_stmt, 9, counter_enabled ? 1 : 0); - sqlite3_bind_int(write_stmt, 10, sort_order); - sqlite3_bind_int64(write_stmt, 11, imported_at); - if(sqlite3_step(write_stmt) == SQLITE_DONE) + if(import_upsert_habit(write_stmt, local_habit_id, name, color, + INBE_HABIT_SYNC_NONE, 0, counter_enabled, + sort_order, imported_at)) ok = 1; - sqlite3_finalize(write_stmt); - write_stmt = NULL; } sqlite3_finalize(stmt); stmt = NULL; + sqlite3_finalize(write_stmt); + write_stmt = NULL; if(sqlite3_prepare_v2(src, "SELECT ticks._track_id,tracks.name,ticks.year,ticks.month,ticks.day,COUNT(*) " @@ -693,14 +755,7 @@ import_tickmate_db(sqlite3 *src) "WHERE tracks.enabled!=0 " "GROUP BY ticks._track_id,ticks.year,ticks.month,ticks.day", -1, &stmt, NULL) == SQLITE_OK) { - if(sqlite3_prepare_v2(g_storage.db, - "INSERT INTO habit_days(habit_id,local_date,completed,count,updated_at) " - "VALUES(?1,?2,1,?3,?4) " - "ON CONFLICT(habit_id,local_date) DO UPDATE SET " - "count=CASE WHEN habit_days.count>excluded.count THEN habit_days.count ELSE excluded.count END," - "completed=CASE WHEN habit_days.count>0 OR excluded.count>0 OR habit_days.completed!=0 THEN 1 ELSE 0 END," - "updated_at=CASE WHEN excluded.count>habit_days.count THEN excluded.updated_at ELSE habit_days.updated_at END", - -1, &write_stmt, NULL) != SQLITE_OK) { + if(!import_prepare_habit_day_upsert(&write_stmt)) { sqlite3_finalize(stmt); stmt = NULL; goto finish; @@ -726,13 +781,8 @@ import_tickmate_db(sqlite3 *src) if(!resolve_import_habit_id(import_habit_id, name, local_habit_id, sizeof(local_habit_id))) continue; - sqlite3_reset(write_stmt); - sqlite3_clear_bindings(write_stmt); - bind_text(write_stmt, 1, local_habit_id); - sqlite3_bind_int(write_stmt, 2, local_date); - sqlite3_bind_int(write_stmt, 3, count > 0 ? count : 1); - sqlite3_bind_int64(write_stmt, 4, imported_at); - if(sqlite3_step(write_stmt) == SQLITE_DONE) + if(import_upsert_habit_day(write_stmt, local_habit_id, local_date, + 1, count > 0 ? count : 1, imported_at)) ok = 1; } } @@ -756,6 +806,16 @@ import_settings_from_source(sqlite3 *src) if(sqlite3_prepare_v2(src, "SELECT key,value FROM settings", -1, &stmt, NULL) != SQLITE_OK) return 0; + if(sqlite3_prepare_v2(g_storage.db, + "INSERT INTO settings(user_id,key,value,updated_at) VALUES(?1,?2,?3,?4) " + "ON CONFLICT(user_id,key) DO UPDATE SET " + "value=CASE WHEN excluded.value!='' OR settings.value='' THEN excluded.value ELSE settings.value END," + "updated_at=CASE WHEN excluded.value!='' OR settings.value='' THEN excluded.updated_at ELSE settings.updated_at END", + -1, &write_stmt, NULL) != SQLITE_OK) { + sqlite3_finalize(stmt); + return 0; + } + exec_sql("BEGIN IMMEDIATE"); while(sqlite3_step(stmt) == SQLITE_ROW) { const char *key = (const char *)sqlite3_column_text(stmt, 0); @@ -763,21 +823,14 @@ import_settings_from_source(sqlite3 *src) if(!setting_key_importable(key)) continue; - if(sqlite3_prepare_v2(g_storage.db, - "INSERT INTO settings(user_id,key,value,updated_at) VALUES(?1,?2,?3,?4) " - "ON CONFLICT(user_id,key) DO UPDATE SET " - "value=CASE WHEN excluded.value!='' OR settings.value='' THEN excluded.value ELSE settings.value END," - "updated_at=CASE WHEN excluded.value!='' OR settings.value='' THEN excluded.updated_at ELSE settings.updated_at END", - -1, &write_stmt, NULL) != SQLITE_OK) - continue; + sqlite3_reset(write_stmt); + sqlite3_clear_bindings(write_stmt); bind_text(write_stmt, 1, g_storage.user_id); bind_text(write_stmt, 2, key); bind_text(write_stmt, 3, value != NULL ? value : ""); sqlite3_bind_int64(write_stmt, 4, imported_at); if(sqlite3_step(write_stmt) == SQLITE_DONE) imported++; - sqlite3_finalize(write_stmt); - write_stmt = NULL; } sqlite3_finalize(stmt); sqlite3_finalize(write_stmt); @@ -832,9 +885,12 @@ import_sqlite_db_file(const char *db_path, InbeStorageImportMode mode) sqlite3 *src = NULL; sqlite3_stmt *stmt = NULL; sqlite3_stmt *hstmt = NULL; + sqlite3_stmt *habit_write_stmt = NULL; + sqlite3_stmt *day_write_stmt = NULL; int ok = 0; int imported_settings = 0; int deferred_materialize = 0; + long long imported_at = now_seconds(); if(db_path == NULL || db_path[0] == '\0') return 0; @@ -881,6 +937,10 @@ import_sqlite_db_file(const char *db_path, InbeStorageImportMode mode) int has_sync_activity = source_table_has_column(src, "habits", "sync_activity"); int has_counter_enabled = source_table_has_column(src, "habits", "counter_enabled"); int has_day_count = source_table_has_column(src, "habit_days", "count"); + const char *day_sql = + has_day_count + ? "SELECT local_date,completed,count FROM habit_days WHERE habit_id=?1" + : "SELECT local_date,completed,CASE WHEN completed!=0 THEN 1 ELSE 0 END FROM habit_days WHERE habit_id=?1"; const char *habit_sql = has_sync_activity && has_counter_enabled ? "SELECT id,name,color_r,color_g,color_b,sync_mode,sync_activity,counter_enabled,sort_order FROM habits WHERE deleted_at=0 ORDER BY sort_order,id" @@ -891,11 +951,18 @@ import_sqlite_db_file(const char *db_path, InbeStorageImportMode mode) : "SELECT id,name,color_r,color_g,color_b,sync_mode,0,0,sort_order FROM habits WHERE deleted_at=0 ORDER BY sort_order,id"; if(sqlite3_prepare_v2(src, habit_sql, -1, &stmt, NULL) != SQLITE_OK) goto after_habits; + if(!import_prepare_habit_upsert(&habit_write_stmt) || + !import_prepare_habit_day_upsert(&day_write_stmt)) + goto after_habits; + sqlite3_prepare_v2(src, day_sql, -1, &hstmt, NULL); exec_sql("BEGIN IMMEDIATE"); while(sqlite3_step(stmt) == SQLITE_ROW) { const char *import_habit_id = (const char *)sqlite3_column_text(stmt, 0); const char *name = (const char *)sqlite3_column_text(stmt, 1); char local_habit_id[INBE_STORAGE_ID_SIZE]; + Color color = {(unsigned char)sqlite3_column_int(stmt, 2), + (unsigned char)sqlite3_column_int(stmt, 3), + (unsigned char)sqlite3_column_int(stmt, 4), 255}; int sync_activity = sqlite3_column_int(stmt, 6); int counter_enabled = sqlite3_column_int(stmt, 7) != 0; int sort_order = sqlite3_column_int(stmt, 8); @@ -906,60 +973,39 @@ import_sqlite_db_file(const char *db_path, InbeStorageImportMode mode) if(!resolve_import_habit_id(import_habit_id, name, local_habit_id, sizeof(local_habit_id))) continue; - if(sqlite3_prepare_v2(g_storage.db, - "INSERT OR REPLACE INTO habits(id,user_id,name,color_r,color_g,color_b,sync_mode,sync_activity,counter_enabled,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,?10,0,?11)", - -1, &hstmt, NULL) != SQLITE_OK) - continue; - bind_text(hstmt, 1, local_habit_id); - bind_text(hstmt, 2, g_storage.user_id); - bind_text(hstmt, 3, name); - sqlite3_bind_int(hstmt, 4, sqlite3_column_int(stmt, 2)); - sqlite3_bind_int(hstmt, 5, sqlite3_column_int(stmt, 3)); - sqlite3_bind_int(hstmt, 6, sqlite3_column_int(stmt, 4)); - sqlite3_bind_int(hstmt, 7, sqlite3_column_int(stmt, 5)); - sqlite3_bind_int(hstmt, 8, sync_activity); - sqlite3_bind_int(hstmt, 9, counter_enabled ? 1 : 0); - sqlite3_bind_int(hstmt, 10, sort_order); - sqlite3_bind_int64(hstmt, 11, now_seconds()); - if(sqlite3_step(hstmt) == SQLITE_DONE) + if(import_upsert_habit(habit_write_stmt, local_habit_id, name, color, + sqlite3_column_int(stmt, 5), sync_activity, + counter_enabled, sort_order, imported_at)) ok = 1; - sqlite3_finalize(hstmt); - hstmt = NULL; - if(sqlite3_prepare_v2(src, - has_day_count - ? "SELECT local_date,completed,count FROM habit_days WHERE habit_id=?1" - : "SELECT local_date,completed,CASE WHEN completed!=0 THEN 1 ELSE 0 END FROM habit_days WHERE habit_id=?1", - -1, &hstmt, NULL) == SQLITE_OK) { + if(hstmt != NULL) { + sqlite3_reset(hstmt); + sqlite3_clear_bindings(hstmt); sqlite3_bind_text(hstmt, 1, import_habit_id, -1, SQLITE_TRANSIENT); while(sqlite3_step(hstmt) == SQLITE_ROW) { - sqlite3_stmt *day_stmt = NULL; - if(sqlite3_prepare_v2(g_storage.db, - "INSERT INTO habit_days(habit_id,local_date,completed,count,updated_at) " - "VALUES(?1,?2,?3,?4,?5) " - "ON CONFLICT(habit_id,local_date) DO UPDATE SET " - "count=CASE WHEN habit_days.count>excluded.count THEN habit_days.count ELSE excluded.count END," - "completed=CASE WHEN habit_days.count>0 OR excluded.count>0 OR habit_days.completed!=0 OR excluded.completed!=0 THEN 1 ELSE 0 END," - "updated_at=CASE WHEN excluded.count>habit_days.count THEN excluded.updated_at ELSE habit_days.updated_at END", - -1, &day_stmt, NULL) != SQLITE_OK) - continue; - bind_text(day_stmt, 1, local_habit_id); - sqlite3_bind_int(day_stmt, 2, sqlite3_column_int(hstmt, 0)); - sqlite3_bind_int(day_stmt, 3, sqlite3_column_int(hstmt, 1) != 0); - sqlite3_bind_int(day_stmt, 4, sqlite3_column_int(hstmt, 2)); - sqlite3_bind_int64(day_stmt, 5, now_seconds()); - sqlite3_step(day_stmt); - sqlite3_finalize(day_stmt); + import_upsert_habit_day(day_write_stmt, local_habit_id, + sqlite3_column_int(hstmt, 0), + sqlite3_column_int(hstmt, 1) != 0, + sqlite3_column_int(hstmt, 2), + imported_at); } } - sqlite3_finalize(hstmt); - hstmt = NULL; } exec_sql("COMMIT"); + sqlite3_finalize(hstmt); + hstmt = NULL; + sqlite3_finalize(habit_write_stmt); + habit_write_stmt = NULL; + sqlite3_finalize(day_write_stmt); + day_write_stmt = NULL; } after_habits: + sqlite3_finalize(hstmt); + hstmt = NULL; + sqlite3_finalize(habit_write_stmt); + habit_write_stmt = NULL; + sqlite3_finalize(day_write_stmt); + day_write_stmt = NULL; if(mode == INBE_STORAGE_IMPORT_DATA_AND_SETTINGS) imported_settings = import_settings_from_source(src); @@ -976,6 +1022,12 @@ try_tickmate: TraceLog(LOG_WARNING, "DATA: sqlite import was neither Inbe nor supported Tickmate schema"); done: + sqlite3_finalize(hstmt); + hstmt = NULL; + sqlite3_finalize(habit_write_stmt); + habit_write_stmt = NULL; + sqlite3_finalize(day_write_stmt); + day_write_stmt = NULL; if(deferred_materialize && g_storage.materialize_defer > 0) { g_storage.materialize_defer--; if(g_storage.materialize_defer == 0 && g_storage.materialize_needed) { @@ -984,7 +1036,6 @@ done: } } sqlite3_finalize(stmt); - sqlite3_finalize(hstmt); if(src != NULL) sqlite3_close(src); if(ok) { diff --git a/src/storage/storage.c b/src/storage/storage.c index fffc24662..27b3453b2 100644 --- a/src/storage/storage.c +++ b/src/storage/storage.c @@ -34,6 +34,8 @@ static int storage_clear_local_sync_data(void); static int storage_json_valid(const char *json); +int +storage_migrate_habit_ids_to_uuid(void); #define STORAGE_SYNC_BACKFILL_KEY "sync_backfill_v2_done" #define STORAGE_SYNC_HABIT_NAME_REPAIR_KEY "sync_habit_name_repair_v1_done" @@ -42,35 +44,45 @@ storage_json_valid(const char *json); #define STORAGE_SYNC_PRIVATE_KEY_KEY "sync_private_key" #define STORAGE_SYNC_LAST_SERVER_HASH_KEY "sync_last_server_state_hash" #define STORAGE_SYNC_SERVER_CLOCK_KEY "sync_server_clock" +#define STORAGE_SYNC_LATEST_PROTOCOL_KEY "sync_latest_protocol" #define STORAGE_SYNC_PENDING_REVIEW_KEY "sync_pending_review_pending" #define STORAGE_SYNC_APPLY_REVIEW_KEY "sync_apply_pending_review" #define STORAGE_SYNC_FULL_REPLACE_KEY "sync_full_replace_requested" #define STORAGE_SYNC_ACCOUNT_ALIAS_KEY "sync_account_alias" #define STORAGE_SYNC_ZERO_HABIT_DAY_REPAIR_KEY "sync_zero_habit_day_repair_v1_done" #define STORAGE_DEFAULT_HABIT_ID_MIGRATION_KEY "default_habit_id_migration_v1_done" +#define STORAGE_HABIT_UUID_MIGRATION_KEY "habit_uuid_migration_v1_done" #define STORAGE_ACTIVITY_SUN_SALUTATION_MASK (1 << 2) +static long long +storage_select_int64(const char *sql, long long fallback) +{ + sqlite3_stmt *stmt = NULL; + long long value = fallback; + + if(g_storage.db == NULL || sql == NULL) + return fallback; + if(sqlite3_prepare_v2(g_storage.db, sql, -1, &stmt, NULL) != SQLITE_OK) + return fallback; + if(sqlite3_step(stmt) == SQLITE_ROW) + value = sqlite3_column_int64(stmt, 0); + sqlite3_finalize(stmt); + return value; +} + static long long storage_next_change_time(void) { - sqlite3_stmt *stmt = NULL; long long now = now_seconds(); - long long latest = 0; + long long latest; - if(g_storage.db == NULL) - return now; - if(sqlite3_prepare_v2(g_storage.db, - "SELECT MAX(updated_at) FROM (" - " SELECT COALESCE(MAX(updated_at),0) AS updated_at FROM habits" - " UNION ALL SELECT COALESCE(MAX(updated_at),0) FROM habit_days" - " UNION ALL SELECT COALESCE(MAX(updated_at),0) FROM sessions" - " UNION ALL SELECT COALESCE(MAX(updated_at),0) FROM social_cache" - ")", - -1, &stmt, NULL) == SQLITE_OK) { - if(sqlite3_step(stmt) == SQLITE_ROW) - latest = sqlite3_column_int64(stmt, 0); - sqlite3_finalize(stmt); - } + latest = storage_select_int64("SELECT MAX(updated_at) FROM (" + " SELECT COALESCE(MAX(updated_at),0) AS updated_at FROM habits" + " UNION ALL SELECT COALESCE(MAX(updated_at),0) FROM habit_days" + " UNION ALL SELECT COALESCE(MAX(updated_at),0) FROM sessions" + " UNION ALL SELECT COALESCE(MAX(updated_at),0) FROM social_snapshots" + ")", + 0); return latest >= now ? latest + 1 : now; } @@ -106,6 +118,32 @@ make_client_uuid(char out[37]) bytes[8], bytes[9], bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15]); } +void +storage_make_uuid(char out[37]) +{ + if(out == NULL) + return; + make_client_uuid(out); +} + +static int +storage_is_uuid(const char *id) +{ + if(id == NULL || strlen(id) != 36) + return 0; + for(int i = 0; i < 36; i++) { + char ch = id[i]; + if(i == 8 || i == 13 || i == 18 || i == 23) { + if(ch != '-') + return 0; + } else if(!((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || + (ch >= 'A' && ch <= 'F'))) { + return 0; + } + } + return 1; +} + typedef struct JsonBuilder { char *data; size_t len; @@ -398,7 +436,7 @@ storage_get_social_cache_json(const char *kind, char *out, size_t out_size) if(g_storage.db == NULL || kind == NULL || kind[0] == '\0') return 0; if(sqlite3_prepare_v2(g_storage.db, - "SELECT json FROM social_cache WHERE user_id=?1 AND kind=?2", + "SELECT json FROM social_snapshots WHERE user_id=?1 AND kind=?2", -1, &stmt, NULL) != SQLITE_OK) return 0; bind_text(stmt, 1, g_storage.user_id); @@ -424,7 +462,7 @@ storage_set_social_cache_json(const char *kind, const char *json) json == NULL || json[0] == '\0' || !storage_json_valid(json)) return 0; if(sqlite3_prepare_v2(g_storage.db, - "SELECT json=?3 FROM social_cache WHERE user_id=?1 AND kind=?2", + "SELECT json=?3 FROM social_snapshots WHERE user_id=?1 AND kind=?2", -1, &stmt, NULL) == SQLITE_OK) { bind_text(stmt, 1, g_storage.user_id); bind_text(stmt, 2, kind); @@ -438,7 +476,7 @@ storage_set_social_cache_json(const char *kind, const char *json) return 1; updated_at = storage_next_change_time(); if(sqlite3_prepare_v2(g_storage.db, - "INSERT INTO social_cache(user_id,kind,json,updated_at) " + "INSERT INTO social_snapshots(user_id,kind,json,updated_at) " "VALUES(?1,?2,?3,?4) " "ON CONFLICT(user_id,kind) DO UPDATE SET " "json=excluded.json,updated_at=excluded.updated_at", @@ -804,106 +842,55 @@ storage_materialize_session_habit_days(void) } changed_at = now_seconds(); - if(!exec_sql("BEGIN IMMEDIATE")) + if(!exec_sql("SAVEPOINT inbe_materialize_habit_days")) return 0; ok = storage_snapshot_habit_day_visible_state() && storage_build_session_habit_counts() && storage_apply_session_habit_counts(changed_at) && storage_enqueue_materialized_habit_day_changes() && exec_sql("DROP TABLE IF EXISTS temp.inbe_session_habit_counts;"); if(ok) { - exec_sql("COMMIT"); + ok = exec_sql("RELEASE inbe_materialize_habit_days"); } else { TraceLog(LOG_WARNING, "STORAGE: failed to materialize session habit counts: %s", sqlite3_errmsg(g_storage.db)); - exec_sql("ROLLBACK"); + exec_sql("ROLLBACK TO inbe_materialize_habit_days"); + exec_sql("RELEASE inbe_materialize_habit_days"); } return ok; } static void -storage_append_habits_json(JsonBuilder *json, long long through_seq) +storage_append_habit_row_json(JsonBuilder *json, sqlite3_stmt *stmt) { - sqlite3_stmt *stmt = NULL; - int first = 1; - - json_append(json, "\"habits\":["); - if(g_storage.db != NULL && - sqlite3_prepare_v2(g_storage.db, - "SELECT " - "id,name,color_r,color_g,color_b,sync_mode,sync_activity,counter_" - "enabled,sort_order,deleted_at,updated_at " - "FROM habits WHERE user_id=?1 AND id IN (" - " SELECT entity_id FROM sync_outbox WHERE entity_type='habit' AND " - "seq<=?2" - ") ORDER BY updated_at,sort_order,id", - -1, &stmt, NULL) == SQLITE_OK) { - bind_text(stmt, 1, g_storage.user_id); - sqlite3_bind_int64(stmt, 2, through_seq); - while(sqlite3_step(stmt) == SQLITE_ROW) { - if(!first) - json_append(json, ","); - first = 0; - json_append(json, "{"); - json_append_key_string(json, "id", (const char *)sqlite3_column_text(stmt, 0)); - json_append(json, ","); - json_append_key_string(json, "name", (const char *)sqlite3_column_text(stmt, 1)); - json_appendf(json, ",\"color_r\":%d,\"color_g\":%d,\"color_b\":%d", - sqlite3_column_int(stmt, 2), sqlite3_column_int(stmt, 3), - sqlite3_column_int(stmt, 4)); - json_appendf(json, - ",\"sync_mode\":%d,\"sync_activity\":%d,\"counter_enabled\":" - "%d,\"sort_order\":%d,\"deleted_at\":%lld", - sqlite3_column_int(stmt, 5), sqlite3_column_int(stmt, 6), - sqlite3_column_int(stmt, 7) != 0 ? 1 : 0, sqlite3_column_int(stmt, 8), - sqlite3_column_int64(stmt, 9)); - json_append(json, ",\"updated_at\":"); - json_append_epoch(json, sqlite3_column_int64(stmt, 10)); - json_append(json, "}"); - } - } - if(stmt != NULL) - sqlite3_finalize(stmt); - json_append(json, "]"); + json_append(json, "{"); + json_append_key_string(json, "id", (const char *)sqlite3_column_text(stmt, 0)); + json_append(json, ","); + json_append_key_string(json, "name", (const char *)sqlite3_column_text(stmt, 1)); + json_appendf(json, ",\"color_r\":%d,\"color_g\":%d,\"color_b\":%d", + sqlite3_column_int(stmt, 2), sqlite3_column_int(stmt, 3), + sqlite3_column_int(stmt, 4)); + json_appendf(json, + ",\"sync_mode\":%d,\"sync_activity\":%d,\"counter_enabled\":" + "%d,\"sort_order\":%d,\"deleted_at\":%lld", + sqlite3_column_int(stmt, 5), sqlite3_column_int(stmt, 6), + sqlite3_column_int(stmt, 7) != 0 ? 1 : 0, sqlite3_column_int(stmt, 8), + sqlite3_column_int64(stmt, 9)); + json_append(json, ",\"updated_at\":"); + json_append_epoch(json, sqlite3_column_int64(stmt, 10)); + json_append(json, "}"); } static void -storage_append_habit_days_json(JsonBuilder *json, long long through_seq) +storage_append_habit_day_row_json(JsonBuilder *json, sqlite3_stmt *stmt) { - sqlite3_stmt *stmt = NULL; - int first = 1; - - json_append(json, "\"habit_days\":["); - if(g_storage.db != NULL && - sqlite3_prepare_v2(g_storage.db, - "SELECT " - "hd.habit_id,hd.local_date,hd.completed,hd.count,hd.updated_at " - "FROM habit_days hd JOIN habits h ON h.id=hd.habit_id " - "WHERE h.user_id=?1 AND EXISTS (" - " SELECT 1 FROM sync_outbox o WHERE o.entity_type='habit_day' " - " AND o.entity_id=hd.habit_id AND o.local_date=hd.local_date AND " - "o.seq<=?2" - ") " - "ORDER BY hd.updated_at,hd.habit_id,hd.local_date", - -1, &stmt, NULL) == SQLITE_OK) { - bind_text(stmt, 1, g_storage.user_id); - sqlite3_bind_int64(stmt, 2, through_seq); - while(sqlite3_step(stmt) == SQLITE_ROW) { - if(!first) - json_append(json, ","); - first = 0; - json_append(json, "{"); - json_append_key_string(json, "habit_id", (const char *)sqlite3_column_text(stmt, 0)); - json_appendf(json, ",\"local_date\":%d,\"completed\":%s,\"count\":%d,\"updated_at\":", - sqlite3_column_int(stmt, 1), - sqlite3_column_int(stmt, 2) != 0 ? "true" : "false", - sqlite3_column_int(stmt, 3)); - json_append_epoch(json, sqlite3_column_int64(stmt, 4)); - json_append(json, "}"); - } - } - if(stmt != NULL) - sqlite3_finalize(stmt); - json_append(json, "]"); + json_append(json, "{"); + json_append_key_string(json, "habit_id", (const char *)sqlite3_column_text(stmt, 0)); + json_appendf(json, ",\"local_date\":%d,\"completed\":%s,\"count\":%d,\"updated_at\":", + sqlite3_column_int(stmt, 1), + sqlite3_column_int(stmt, 2) != 0 ? "true" : "false", + sqlite3_column_int(stmt, 3)); + json_append_epoch(json, sqlite3_column_int64(stmt, 4)); + json_append(json, "}"); } static void @@ -934,47 +921,49 @@ storage_append_session_rounds_json(JsonBuilder *json, const char *session_id) } static void -storage_append_sessions_json(JsonBuilder *json, long long through_seq) +storage_append_session_row_json(JsonBuilder *json, sqlite3_stmt *stmt) +{ + const char *id = (const char *)sqlite3_column_text(stmt, 0); + long long started_at = sqlite3_column_int64(stmt, 1); + long long updated_at = sqlite3_column_int64(stmt, 8); + + json_append(json, "{"); + json_append_key_string(json, "id", id); + json_append(json, ",\"started_at\":"); + json_append_epoch(json, started_at); + json_appendf(json, ",\"local_date\":%d,\"topic\":\"%d\",\"activity\":%d,", + sqlite3_column_int(stmt, 2), sqlite3_column_int(stmt, 3), + sqlite3_column_int(stmt, 4)); + json_append_key_string(json, "source", (const char *)sqlite3_column_text(stmt, 5)); + json_append(json, ","); + json_append_key_string(json, "rounds_hash", (const char *)sqlite3_column_text(stmt, 6)); + json_appendf(json, ",\"deleted_at\":%lld,\"updated_at\":", sqlite3_column_int64(stmt, 7)); + json_append_epoch(json, updated_at > 0 ? updated_at : started_at); + json_append(json, ","); + storage_append_session_rounds_json(json, id); + json_append(json, "}"); +} + +typedef void (*StorageJsonRowFn)(JsonBuilder *json, sqlite3_stmt *stmt); + +static void +storage_append_sync_query_array(JsonBuilder *json, const char *key, + const char *sql, long long through_seq, + StorageJsonRowFn append_row) { sqlite3_stmt *stmt = NULL; int first = 1; - json_append(json, "\"sessions\":["); - if(g_storage.db != NULL && sqlite3_prepare_v2(g_storage.db, - "SELECT " - "id,started_at,local_date,topic,activity,source," - "rounds_hash,deleted_at,updated_at " - "FROM sessions WHERE user_id=?1 AND id IN (" - " SELECT entity_id FROM sync_outbox WHERE " - "entity_type='session' AND seq<=?2" - ") " - "ORDER BY updated_at,started_at,id", - -1, &stmt, NULL) == SQLITE_OK) { + json_appendf(json, "\"%s\":[", key); + if(g_storage.db != NULL && + sqlite3_prepare_v2(g_storage.db, sql, -1, &stmt, NULL) == SQLITE_OK) { bind_text(stmt, 1, g_storage.user_id); sqlite3_bind_int64(stmt, 2, through_seq); while(sqlite3_step(stmt) == SQLITE_ROW) { - const char *id = (const char *)sqlite3_column_text(stmt, 0); - long long started_at = sqlite3_column_int64(stmt, 1); - long long updated_at = sqlite3_column_int64(stmt, 8); if(!first) json_append(json, ","); first = 0; - json_append(json, "{"); - json_append_key_string(json, "id", id); - json_append(json, ",\"started_at\":"); - json_append_epoch(json, started_at); - json_appendf(json, ",\"local_date\":%d,\"topic\":\"%d\",\"activity\":%d,", - sqlite3_column_int(stmt, 2), sqlite3_column_int(stmt, 3), - sqlite3_column_int(stmt, 4)); - json_append_key_string(json, "source", (const char *)sqlite3_column_text(stmt, 5)); - json_append(json, ","); - json_append_key_string(json, "rounds_hash", (const char *)sqlite3_column_text(stmt, 6)); - json_appendf(json, - ",\"deleted_at\":%lld,\"updated_at\":", sqlite3_column_int64(stmt, 7)); - json_append_epoch(json, updated_at > 0 ? updated_at : started_at); - json_append(json, ","); - storage_append_session_rounds_json(json, id); - json_append(json, "}"); + append_row(json, stmt); } } if(stmt != NULL) @@ -982,119 +971,132 @@ storage_append_sessions_json(JsonBuilder *json, long long through_seq) json_append(json, "]"); } +static void +storage_append_habits_json(JsonBuilder *json, long long through_seq) +{ + storage_append_sync_query_array( + json, "habits", + "SELECT " + "id,name,color_r,color_g,color_b,sync_mode,sync_activity,counter_" + "enabled,sort_order,deleted_at,updated_at " + "FROM habits WHERE user_id=?1 AND id IN (" + " SELECT entity_id FROM sync_outbox WHERE entity_type='habit' AND " + "seq<=?2" + ") ORDER BY updated_at,sort_order,id", + through_seq, storage_append_habit_row_json); +} + +static void +storage_append_habit_days_json(JsonBuilder *json, long long through_seq) +{ + storage_append_sync_query_array( + json, "habit_days", + "SELECT " + "hd.habit_id,hd.local_date,hd.completed,hd.count,hd.updated_at " + "FROM habit_days hd JOIN habits h ON h.id=hd.habit_id " + "WHERE h.user_id=?1 AND EXISTS (" + " SELECT 1 FROM sync_outbox o WHERE o.entity_type='habit_day' " + " AND o.entity_id=hd.habit_id AND o.local_date=hd.local_date AND " + "o.seq<=?2" + ") " + "ORDER BY hd.updated_at,hd.habit_id,hd.local_date", + through_seq, storage_append_habit_day_row_json); +} + +static void +storage_append_sessions_json(JsonBuilder *json, long long through_seq) +{ + storage_append_sync_query_array( + json, "sessions", + "SELECT " + "id,started_at,local_date,topic,activity,source," + "rounds_hash,deleted_at,updated_at " + "FROM sessions WHERE user_id=?1 AND id IN (" + " SELECT entity_id FROM sync_outbox WHERE " + "entity_type='session' AND seq<=?2" + ") " + "ORDER BY updated_at,started_at,id", + through_seq, storage_append_session_row_json); +} + static int -storage_append_habit_payload_json(JsonBuilder *json, const char *habit_id) +storage_append_id_payload_json(JsonBuilder *json, const char *sql, + const char *id, StorageJsonRowFn append_row) { sqlite3_stmt *stmt = NULL; int found = 0; - if(g_storage.db == NULL || habit_id == NULL) + if(g_storage.db == NULL || id == NULL) return 0; - if(sqlite3_prepare_v2(g_storage.db, - "SELECT " - "id,name,color_r,color_g,color_b,sync_mode,sync_activity,counter_" - "enabled,sort_order,deleted_at,updated_at " - "FROM habits WHERE user_id=?1 AND id=?2", - -1, &stmt, NULL) != SQLITE_OK) + if(sqlite3_prepare_v2(g_storage.db, sql, -1, &stmt, NULL) != SQLITE_OK) return 0; bind_text(stmt, 1, g_storage.user_id); - bind_text(stmt, 2, habit_id); + bind_text(stmt, 2, id); if(sqlite3_step(stmt) == SQLITE_ROW) { found = 1; - json_append(json, "{"); - json_append_key_string(json, "id", (const char *)sqlite3_column_text(stmt, 0)); - json_append(json, ","); - json_append_key_string(json, "name", (const char *)sqlite3_column_text(stmt, 1)); - json_appendf(json, ",\"color_r\":%d,\"color_g\":%d,\"color_b\":%d", - sqlite3_column_int(stmt, 2), sqlite3_column_int(stmt, 3), - sqlite3_column_int(stmt, 4)); - json_appendf(json, - ",\"sync_mode\":%d,\"sync_activity\":%d,\"counter_enabled\":%" - "d,\"sort_order\":%d,\"deleted_at\":%lld", - sqlite3_column_int(stmt, 5), sqlite3_column_int(stmt, 6), - sqlite3_column_int(stmt, 7) != 0 ? 1 : 0, sqlite3_column_int(stmt, 8), - sqlite3_column_int64(stmt, 9)); - json_append(json, ",\"updated_at\":"); - json_append_epoch(json, sqlite3_column_int64(stmt, 10)); - json_append(json, "}"); + append_row(json, stmt); } sqlite3_finalize(stmt); return found; } +static int +storage_append_dated_payload_json(JsonBuilder *json, const char *sql, + const char *id, int local_date, + StorageJsonRowFn append_row) +{ + sqlite3_stmt *stmt = NULL; + int found = 0; + + if(g_storage.db == NULL || id == NULL) + return 0; + if(sqlite3_prepare_v2(g_storage.db, sql, -1, &stmt, NULL) != SQLITE_OK) + return 0; + bind_text(stmt, 1, g_storage.user_id); + bind_text(stmt, 2, id); + sqlite3_bind_int(stmt, 3, local_date); + if(sqlite3_step(stmt) == SQLITE_ROW) { + found = 1; + append_row(json, stmt); + } + sqlite3_finalize(stmt); + return found; +} + +static int +storage_append_habit_payload_json(JsonBuilder *json, const char *habit_id) +{ + return storage_append_id_payload_json( + json, + "SELECT " + "id,name,color_r,color_g,color_b,sync_mode,sync_activity,counter_" + "enabled,sort_order,deleted_at,updated_at " + "FROM habits WHERE user_id=?1 AND id=?2", + habit_id, storage_append_habit_row_json); +} + static int storage_append_habit_day_payload_json(JsonBuilder *json, const char *habit_id, int local_date) { - sqlite3_stmt *stmt = NULL; - int found = 0; - - if(g_storage.db == NULL || habit_id == NULL) - return 0; - if(sqlite3_prepare_v2(g_storage.db, - "SELECT " - "hd.habit_id,hd.local_date,hd.completed,hd.count,hd.updated_at " - "FROM habit_days hd JOIN habits h ON h.id=hd.habit_id " - "WHERE h.user_id=?1 AND hd.habit_id=?2 AND hd.local_date=?3", - -1, &stmt, NULL) != SQLITE_OK) - return 0; - bind_text(stmt, 1, g_storage.user_id); - bind_text(stmt, 2, habit_id); - sqlite3_bind_int(stmt, 3, local_date); - if(sqlite3_step(stmt) == SQLITE_ROW) { - found = 1; - json_append(json, "{"); - json_append_key_string(json, "habit_id", (const char *)sqlite3_column_text(stmt, 0)); - json_appendf(json, ",\"local_date\":%d,\"completed\":%s,\"count\":%d,\"updated_at\":", - sqlite3_column_int(stmt, 1), - sqlite3_column_int(stmt, 2) != 0 ? "true" : "false", - sqlite3_column_int(stmt, 3)); - json_append_epoch(json, sqlite3_column_int64(stmt, 4)); - json_append(json, "}"); - } - sqlite3_finalize(stmt); - return found; + return storage_append_dated_payload_json( + json, + "SELECT " + "hd.habit_id,hd.local_date,hd.completed,hd.count,hd.updated_at " + "FROM habit_days hd JOIN habits h ON h.id=hd.habit_id " + "WHERE h.user_id=?1 AND hd.habit_id=?2 AND hd.local_date=?3", + habit_id, local_date, storage_append_habit_day_row_json); } static int storage_append_session_payload_json(JsonBuilder *json, const char *session_id) { - sqlite3_stmt *stmt = NULL; - int found = 0; - - if(g_storage.db == NULL || session_id == NULL) - return 0; - if(sqlite3_prepare_v2(g_storage.db, - "SELECT " - "id,started_at,local_date,topic,activity,source," - "rounds_hash,deleted_at,updated_at " - "FROM sessions WHERE user_id=?1 AND id=?2", - -1, &stmt, NULL) != SQLITE_OK) - return 0; - bind_text(stmt, 1, g_storage.user_id); - bind_text(stmt, 2, session_id); - if(sqlite3_step(stmt) == SQLITE_ROW) { - const char *id = (const char *)sqlite3_column_text(stmt, 0); - long long started_at = sqlite3_column_int64(stmt, 1); - long long updated_at = sqlite3_column_int64(stmt, 8); - found = 1; - json_append(json, "{"); - json_append_key_string(json, "id", id); - json_append(json, ",\"started_at\":"); - json_append_epoch(json, started_at); - json_appendf(json, ",\"local_date\":%d,\"topic\":\"%d\",\"activity\":%d,", - sqlite3_column_int(stmt, 2), sqlite3_column_int(stmt, 3), - sqlite3_column_int(stmt, 4)); - json_append_key_string(json, "source", (const char *)sqlite3_column_text(stmt, 5)); - json_append(json, ","); - json_append_key_string(json, "rounds_hash", (const char *)sqlite3_column_text(stmt, 6)); - json_appendf(json, ",\"deleted_at\":%lld,\"updated_at\":", sqlite3_column_int64(stmt, 7)); - json_append_epoch(json, updated_at > 0 ? updated_at : started_at); - json_append(json, ","); - storage_append_session_rounds_json(json, id); - json_append(json, "}"); - } - sqlite3_finalize(stmt); - return found; + return storage_append_id_payload_json( + json, + "SELECT " + "id,started_at,local_date,topic,activity,source," + "rounds_hash,deleted_at,updated_at " + "FROM sessions WHERE user_id=?1 AND id=?2", + session_id, storage_append_session_row_json); } static int @@ -1241,7 +1243,7 @@ storage_build_sync_payload_json(const char *user_id_hash, const char *public_key g_storage.pending_sync_outbox_seq = through_seq; json.ok = 1; json_append(&json, "{"); - json_append(&json, "\"protocol_version\":2,"); + json_appendf(&json, "\"protocol_version\":%d,", INBE_SYNC_PROTOCOL_VERSION); json_append_key_string(&json, "user_id_hash", user_id_hash); json_append(&json, ","); json_append_key_string(&json, "client_id", storage_sync_client_id()); @@ -1360,55 +1362,24 @@ storage_json_extract_text(const char *json, const char *path, char *out, size_t static long long storage_max_sync_outbox_seq(void) { - sqlite3_stmt *stmt = NULL; - long long seq = 0; - - if(g_storage.db == NULL) - return 0; - if(sqlite3_prepare_v2(g_storage.db, "SELECT COALESCE(MAX(seq),0) FROM sync_outbox", -1, &stmt, - NULL) != SQLITE_OK) - return 0; - if(sqlite3_step(stmt) == SQLITE_ROW) - seq = sqlite3_column_int64(stmt, 0); - sqlite3_finalize(stmt); - return seq; + return storage_select_int64("SELECT COALESCE(MAX(seq),0) FROM sync_outbox", 0); } static int storage_has_pending_sync_outbox(void) { - sqlite3_stmt *stmt = NULL; - int result = 0; - - if(g_storage.db == NULL) - return 0; - if(sqlite3_prepare_v2(g_storage.db, "SELECT EXISTS(SELECT 1 FROM sync_outbox LIMIT 1)", -1, - &stmt, NULL) != SQLITE_OK) - return 0; - if(sqlite3_step(stmt) == SQLITE_ROW) - result = sqlite3_column_int(stmt, 0) != 0; - sqlite3_finalize(stmt); - return result; + return storage_select_int64("SELECT EXISTS(SELECT 1 FROM sync_outbox LIMIT 1)", 0) != 0; } static int storage_has_orphan_habit_days(void) { - sqlite3_stmt *stmt = NULL; - int found = 0; - - if(g_storage.db == NULL) - return 0; - if(sqlite3_prepare_v2(g_storage.db, - "SELECT 1 FROM habit_days hd " - "WHERE hd.habit_id<>'' " - "AND NOT EXISTS (SELECT 1 FROM habits h WHERE h.id=hd.habit_id) " - "LIMIT 1", - -1, &stmt, NULL) != SQLITE_OK) - return 0; - found = sqlite3_step(stmt) == SQLITE_ROW; - sqlite3_finalize(stmt); - return found; + return storage_select_int64( + "SELECT EXISTS(SELECT 1 FROM habit_days hd " + "WHERE hd.habit_id<>'' " + "AND NOT EXISTS (SELECT 1 FROM habits h WHERE h.id=hd.habit_id) " + "LIMIT 1)", + 0) != 0; } int @@ -1469,6 +1440,11 @@ storage_sync_response_has_changes(const char *json) storage_json_array_has_items(json, "$.changes.habit_days") || storage_json_array_has_items(json, "$.changes.sessions") || storage_json_array_has_items(json, "$.changes.meditation_logs") || + storage_json_array_has_items(json, "$.data.habits") || + storage_json_array_has_items(json, "$.data.habit_days") || + storage_json_array_has_items(json, "$.data.sessions") || + storage_json_array_has_items(json, "$.data.meditation_logs") || + storage_json_array_has_items(json, "$.data.social") || storage_json_array_has_items(json, "$.changes.social_cache"); } @@ -1570,6 +1546,84 @@ storage_merge_habit_into(const char *keeper_id, const char *duplicate_id) return ok; } +static int +storage_reconcile_remote_habit_ids(const char *response_json) +{ + static const char *remote_map_sql = + "INSERT OR IGNORE INTO inbe_remote_habit_id_map(old_id,new_id) " + "SELECT h.id,COALESCE(json_extract(r.value,'$.id'),'') " + "FROM (SELECT value FROM json_each(?1,'$.changes.habits') " + " UNION ALL SELECT value FROM json_each(?1,'$.data.habits')) AS r " + "JOIN habits h ON h.name=COALESCE(json_extract(r.value,'$.name'),'') " + "WHERE h.deleted_at=0 " + " AND CAST(COALESCE(json_extract(r.value,'$.deleted_at'),0) AS INTEGER)=0 " + " AND COALESCE(json_extract(r.value,'$.id'),'')<>'' " + " AND h.id<>COALESCE(json_extract(r.value,'$.id'),'')"; + + if(response_json == NULL) + return 0; + if(!exec_sql("DROP TABLE IF EXISTS temp.inbe_remote_habit_id_map;" + "CREATE TEMP TABLE inbe_remote_habit_id_map(" + " old_id TEXT PRIMARY KEY," + " new_id TEXT NOT NULL" + ")")) + return 0; + if(!storage_exec_json_user_sql(remote_map_sql, response_json)) + return 0; + if(!exec_sql("UPDATE habit_days " + "SET completed=MAX(completed,COALESCE((SELECT d.completed FROM habit_days d " + " JOIN inbe_remote_habit_id_map m ON m.old_id=d.habit_id " + " WHERE m.new_id=habit_days.habit_id " + " AND d.local_date=habit_days.local_date),0))," + " count=MAX(count,COALESCE((SELECT d.count FROM habit_days d " + " JOIN inbe_remote_habit_id_map m ON m.old_id=d.habit_id " + " WHERE m.new_id=habit_days.habit_id " + " AND d.local_date=habit_days.local_date),0))," + " session_count=MAX(session_count,COALESCE((SELECT d.session_count FROM " + "habit_days d " + " JOIN inbe_remote_habit_id_map m ON m.old_id=d.habit_id " + " WHERE m.new_id=habit_days.habit_id " + " AND d.local_date=habit_days.local_date),0))," + " updated_at=MAX(updated_at,COALESCE((SELECT d.updated_at FROM habit_days d " + " JOIN inbe_remote_habit_id_map m ON m.old_id=d.habit_id " + " WHERE m.new_id=habit_days.habit_id " + " AND d.local_date=habit_days.local_date),0)) " + "WHERE EXISTS (SELECT 1 FROM inbe_remote_habit_id_map m " + " WHERE m.new_id=habit_days.habit_id)")) + return 0; + if(!exec_sql("INSERT INTO habit_days(habit_id,local_date,completed,count,session_count," + "updated_at) " + "SELECT m.new_id,d.local_date,d.completed,d.count,d.session_count,d.updated_at " + "FROM habit_days d JOIN inbe_remote_habit_id_map m ON m.old_id=d.habit_id " + "WHERE NOT EXISTS (SELECT 1 FROM habit_days k " + " WHERE k.habit_id=m.new_id AND k.local_date=d.local_date)")) + return 0; + if(!exec_sql("UPDATE OR IGNORE sync_outbox SET entity_id=(SELECT m.new_id FROM " + "inbe_remote_habit_id_map m WHERE m.old_id=sync_outbox.entity_id) " + "WHERE entity_type IN ('habit','habit_day') " + "AND EXISTS (SELECT 1 FROM inbe_remote_habit_id_map m " + " WHERE m.old_id=sync_outbox.entity_id);" + "DELETE FROM sync_outbox WHERE entity_type IN ('habit','habit_day') " + "AND EXISTS (SELECT 1 FROM inbe_remote_habit_id_map m " + " WHERE m.old_id=sync_outbox.entity_id);" + "UPDATE OR IGNORE sync_ops SET entity_id=(SELECT m.new_id FROM " + "inbe_remote_habit_id_map m WHERE m.old_id=sync_ops.entity_id) " + "WHERE entity_type IN ('habit','habit_day') " + "AND EXISTS (SELECT 1 FROM inbe_remote_habit_id_map m " + " WHERE m.old_id=sync_ops.entity_id);" + "UPDATE settings SET value=(SELECT m.new_id FROM inbe_remote_habit_id_map m " + " WHERE m.old_id=settings.value),updated_at=strftime('%s','now') " + "WHERE key='habits_selected_id' " + "AND EXISTS (SELECT 1 FROM inbe_remote_habit_id_map m " + " WHERE m.old_id=settings.value);" + "DELETE FROM habit_days WHERE EXISTS (SELECT 1 FROM inbe_remote_habit_id_map m " + " WHERE m.old_id=habit_days.habit_id);" + "DELETE FROM habits WHERE EXISTS (SELECT 1 FROM inbe_remote_habit_id_map m " + " WHERE m.old_id=habits.id);")) + return 0; + return exec_sql("DROP TABLE IF EXISTS temp.inbe_remote_habit_id_map"); +} + static int storage_habit_exists(const char *habit_id) { @@ -1671,6 +1725,81 @@ storage_migrate_default_habit_ids(void) return 1; } +int +storage_migrate_habit_ids_to_uuid(void) +{ + sqlite3_stmt *stmt = NULL; + struct { + char old_id[INBE_STORAGE_ID_SIZE]; + char new_id[37]; + } rows[INBE_HABIT_MAX]; + int count = 0; + int ok = 1; + + if(g_storage.db == NULL) + return 0; + if(get_meta_int64(STORAGE_HABIT_UUID_MIGRATION_KEY, 0)) + return 1; + if(sqlite3_prepare_v2(g_storage.db, + "SELECT id FROM habits WHERE id<>'' ORDER BY sort_order,id", + -1, &stmt, NULL) != SQLITE_OK) + return 0; + while(sqlite3_step(stmt) == SQLITE_ROW && count < INBE_HABIT_MAX) { + const char *id = (const char *)sqlite3_column_text(stmt, 0); + if(id != NULL && !storage_is_uuid(id)) { + snprintf(rows[count].old_id, sizeof(rows[count].old_id), "%s", id); + storage_make_uuid(rows[count].new_id); + count++; + } + } + sqlite3_finalize(stmt); + if(count <= 0) { + set_meta_int64(STORAGE_HABIT_UUID_MIGRATION_KEY, 1); + return 1; + } + if(!exec_sql("BEGIN IMMEDIATE")) + return 0; + for(int i = 0; i < count; i++) { + const char *sqls[] = { + "UPDATE habits SET id=?2,updated_at=?3 WHERE id=?1", + "UPDATE habit_days SET habit_id=?2 WHERE habit_id=?1", + "UPDATE OR IGNORE sync_outbox SET entity_id=?2 " + "WHERE entity_id=?1 AND entity_type IN ('habit','habit_day')", + "DELETE FROM sync_outbox WHERE entity_id=?1 " + "AND entity_type IN ('habit','habit_day')", + "UPDATE settings SET value=?2,updated_at=?3 " + "WHERE key='habits_selected_id' AND value=?1"}; + long long changed_at = storage_next_change_time(); + + for(size_t j = 0; j < sizeof(sqls) / sizeof(sqls[0]); j++) { + if(sqlite3_prepare_v2(g_storage.db, sqls[j], -1, &stmt, NULL) != SQLITE_OK) { + ok = 0; + break; + } + bind_text(stmt, 1, rows[i].old_id); + bind_text(stmt, 2, rows[i].new_id); + sqlite3_bind_int64(stmt, 3, changed_at); + ok = sqlite3_step(stmt) == SQLITE_DONE; + sqlite3_finalize(stmt); + stmt = NULL; + if(!ok) + break; + } + if(!ok) + break; + storage_enqueue_sync_habit(rows[i].new_id); + storage_enqueue_habit_days_for_sync(rows[i].new_id); + } + if(ok) { + set_meta_int64(STORAGE_HABIT_UUID_MIGRATION_KEY, 1); + ok = exec_sql("COMMIT"); + } else { + sqlite3_finalize(stmt); + exec_sql("ROLLBACK"); + } + return ok; +} + static int storage_merge_duplicate_habit_names(void) { @@ -1743,7 +1872,8 @@ storage_apply_sync_response_json(const char *response_json) " " "CAST(COALESCE(strftime('%s',json_extract(value,'$.updated_at')),'0') AS " "INTEGER) " - "FROM json_each(?1,'$.changes.habits') " + "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 " " user_id=excluded.user_id,name=excluded.name,color_r=excluded.color_r," @@ -1768,7 +1898,8 @@ storage_apply_sync_response_json(const char *response_json) " " "CAST(COALESCE(strftime('%s',json_extract(value,'$.updated_at')),'0') AS " "INTEGER) " - "FROM json_each(?1,'$.changes.habit_days') " + "FROM (SELECT value FROM json_each(?1,'$.changes.habit_days') " + " UNION ALL SELECT value FROM json_each(?1,'$.data.habit_days')) " "WHERE COALESCE(json_extract(value,'$.habit_id'),'')<>'' " " AND CAST(COALESCE(json_extract(value,'$.local_date'),0) AS INTEGER)>0 " "ON CONFLICT(habit_id,local_date) DO UPDATE SET " @@ -1800,7 +1931,8 @@ storage_apply_sync_response_json(const char *response_json) " " "CAST(COALESCE(strftime('%s',json_extract(value,'$.updated_at'))," "strftime('%s',json_extract(value,'$.started_at')),'0') AS INTEGER) " - "FROM json_each(?1,'$.changes.sessions') " + "FROM (SELECT value FROM json_each(?1,'$.changes.sessions') " + " UNION ALL SELECT value FROM json_each(?1,'$.data.sessions')) " "WHERE COALESCE(json_extract(value,'$.id'),'')<>'' " "ON CONFLICT(id) DO UPDATE SET " " user_id=excluded.user_id,started_at=excluded.started_at,local_date=" @@ -1817,7 +1949,8 @@ storage_apply_sync_response_json(const char *response_json) static const char *delete_rounds_sql = "DELETE FROM session_rounds WHERE session_id IN (" " SELECT COALESCE(json_extract(value,'$.id'),'') " - " FROM json_each(?1,'$.changes.sessions') " + " FROM (SELECT value FROM json_each(?1,'$.changes.sessions') " + " UNION ALL SELECT value FROM json_each(?1,'$.data.sessions')) " " WHERE COALESCE(json_extract(value,'$.id'),'')<>'' " " AND (" " NOT EXISTS (SELECT 1 FROM sessions WHERE " @@ -1844,7 +1977,8 @@ storage_apply_sync_response_json(const char *response_json) "INTEGER)," " CAST(COALESCE(json_extract(r.value,'$.hold_seconds'),0) AS " "INTEGER) " - "FROM json_each(?1,'$.changes.sessions') AS s, " + "FROM (SELECT value FROM json_each(?1,'$.changes.sessions') " + " UNION ALL SELECT value FROM json_each(?1,'$.data.sessions')) AS s, " "json_each(s.value,'$.rounds') AS r " "WHERE COALESCE(json_extract(s.value,'$.id'),'')<>'' " "AND " @@ -1861,7 +1995,7 @@ storage_apply_sync_response_json(const char *response_json) " WHERE entity_type='session' AND " "entity_id=COALESCE(json_extract(s.value,'$.id'),'') AND local_date=0)))"; static const char *social_cache_sql = - "INSERT INTO social_cache(user_id,kind,json,updated_at) " + "INSERT INTO social_snapshots(user_id,kind,json,updated_at) " "SELECT ?2," " COALESCE(json_extract(value,'$.kind'),'')," " json(COALESCE(json_extract(value,'$.json'),'{}'))," @@ -1870,9 +2004,20 @@ storage_apply_sync_response_json(const char *response_json) "WHERE COALESCE(json_extract(value,'$.kind'),'')<>'' " "ON CONFLICT(user_id,kind) DO UPDATE SET " " json=excluded.json,updated_at=excluded.updated_at"; + static const char *social_sql = + "INSERT INTO social_snapshots(user_id,kind,json,updated_at) " + "SELECT ?2," + " COALESCE(json_extract(value,'$.kind'),'')," + " json(COALESCE(json_extract(value,'$.json'),'{}'))," + " CAST(COALESCE(strftime('%s',json_extract(value,'$.updated_at')),'0') AS INTEGER) " + "FROM json_each(?1,'$.data.social') " + "WHERE COALESCE(json_extract(value,'$.kind'),'')<>'' " + "ON CONFLICT(user_id,kind) DO UPDATE SET " + " json=excluded.json,updated_at=excluded.updated_at"; long long server_version; long long server_clock; long long old_server_version; + long long latest_protocol; char server_hash[80]; char account_alias[40]; @@ -1886,6 +2031,9 @@ storage_apply_sync_response_json(const char *response_json) if(storage_json_extract_text(response_json, "$.account_alias", account_alias, sizeof(account_alias))) storage_set_setting_text(STORAGE_SYNC_ACCOUNT_ALIAS_KEY, account_alias); + latest_protocol = storage_json_extract_int64(response_json, "$.latest_protocol", 0); + if(latest_protocol > 0) + set_meta_int64(STORAGE_SYNC_LATEST_PROTOCOL_KEY, latest_protocol); if(storage_json_extract_int64(response_json, "$.full_snapshot_required", 0) != 0 && get_meta_int64(STORAGE_SYNC_APPLY_REVIEW_KEY, 0) == 0) { if(!storage_has_any()) @@ -1905,21 +2053,23 @@ storage_apply_sync_response_json(const char *response_json) } } old_server_version = get_meta_int64("sync_last_server_version", 0); - if(!exec_sql("BEGIN IMMEDIATE")) + if(!exec_sql("SAVEPOINT inbe_sync_apply")) return 0; storage_clear_uploaded_outbox(g_storage.pending_sync_outbox_seq); - if(!storage_exec_json_user_sql(habits_sql, response_json) || + if(!storage_reconcile_remote_habit_ids(response_json) || + !storage_exec_json_user_sql(habits_sql, response_json) || !storage_exec_json_user_sql(habit_days_sql, response_json) || !storage_merge_duplicate_habit_names() || !storage_exec_json_user_sql(delete_rounds_sql, response_json) || !storage_exec_json_user_sql(rounds_sql, response_json) || !storage_exec_json_user_sql(sessions_sql, response_json) || + !storage_exec_json_user_sql(social_sql, response_json) || !storage_exec_json_user_sql(social_cache_sql, response_json)) { - exec_sql("ROLLBACK"); + exec_sql("ROLLBACK TO inbe_sync_apply"); + exec_sql("RELEASE inbe_sync_apply"); return 0; } - if(!exec_sql("COMMIT")) { - exec_sql("ROLLBACK"); + if(!exec_sql("RELEASE inbe_sync_apply")) { return 0; } storage_materialize_session_habit_days(); @@ -1929,9 +2079,12 @@ storage_apply_sync_response_json(const char *response_json) "SYNC: response server_version=%lld old_server_version=%lld " "habits=%d habit_days=%d sessions=%d", server_version, old_server_version, - storage_json_array_count(response_json, "$.changes.habits"), - storage_json_array_count(response_json, "$.changes.habit_days"), - storage_json_array_count(response_json, "$.changes.sessions")); + storage_json_array_count(response_json, "$.changes.habits") + + storage_json_array_count(response_json, "$.data.habits"), + storage_json_array_count(response_json, "$.changes.habit_days") + + storage_json_array_count(response_json, "$.data.habit_days"), + storage_json_array_count(response_json, "$.changes.sessions") + + storage_json_array_count(response_json, "$.data.sessions")); if(server_version > old_server_version && storage_sync_response_has_changes(response_json)) g_storage.last_sync_changed = 1; if(server_version > 0) @@ -1981,7 +2134,7 @@ storage_clear_local_sync_data(void) { static const char *const sqls[] = {"DELETE FROM session_rounds", "DELETE FROM sessions", "DELETE FROM habit_days", "DELETE FROM habits", - "DELETE FROM social_cache", + "DELETE FROM social_snapshots", "DELETE FROM sync_outbox"}; if(g_storage.db == NULL) @@ -2010,8 +2163,6 @@ storage_last_sync_changed(void) int storage_sync_status(InbeStorageSyncStatus *status) { - sqlite3_stmt *stmt = NULL; - if(status == NULL) return 0; memset(status, 0, sizeof(*status)); @@ -2024,12 +2175,10 @@ storage_sync_status(InbeStorageSyncStatus *status) status->full_upload_done = get_meta_int64("sync_full_upload_done", 0) != 0; status->server_version = get_meta_int64("sync_last_server_version", 0); status->server_clock = get_meta_int64(STORAGE_SYNC_SERVER_CLOCK_KEY, 0); - if(sqlite3_prepare_v2(g_storage.db, "SELECT COUNT(*) FROM sync_outbox", -1, &stmt, NULL) == - SQLITE_OK) { - if(sqlite3_step(stmt) == SQLITE_ROW) - status->queued_changes = sqlite3_column_int64(stmt, 0); - } - sqlite3_finalize(stmt); + status->latest_protocol = (int)get_meta_int64(STORAGE_SYNC_LATEST_PROTOCOL_KEY, + INBE_SYNC_PROTOCOL_VERSION); + status->protocol_upgrade_available = status->latest_protocol > INBE_SYNC_PROTOCOL_VERSION; + status->queued_changes = storage_select_int64("SELECT COUNT(*) FROM sync_outbox", 0); return 1; } @@ -2178,17 +2327,7 @@ storage_habits_empty(void) int storage_habit_count(void) { - sqlite3_stmt *stmt = NULL; - int count = 0; - if(g_storage.db == NULL) - return 0; - if(sqlite3_prepare_v2(g_storage.db, "SELECT COUNT(*) FROM habits WHERE deleted_at=0", -1, &stmt, - NULL) != SQLITE_OK) - return 0; - if(sqlite3_step(stmt) == SQLITE_ROW) - count = sqlite3_column_int(stmt, 0); - sqlite3_finalize(stmt); - return count; + return (int)storage_select_int64("SELECT COUNT(*) FROM habits WHERE deleted_at=0", 0); } int @@ -2226,27 +2365,30 @@ storage_habits_load(void *habits_ptr) index++; } sqlite3_finalize(stmt); + stmt = NULL; habits->count = index; habits->loaded_count = index; - for(int i = 0; i < habits->count; i++) { - if(sqlite3_prepare_v2(g_storage.db, - "SELECT local_date,completed,count FROM habit_days " - "WHERE habit_id=?1 ORDER BY local_date", - -1, &stmt, NULL) != SQLITE_OK) - continue; - bind_text(stmt, 1, habits->items[i].id); - while(sqlite3_step(stmt) == SQLITE_ROW) { - int d = habits->items[i].day_count++; - if(!habit_reserve_days(&habits->items[i], habits->items[i].day_count)) { - habits->items[i].day_count--; - break; + if(sqlite3_prepare_v2(g_storage.db, + "SELECT local_date,completed,count FROM habit_days " + "WHERE habit_id=?1 ORDER BY local_date", + -1, &stmt, NULL) == SQLITE_OK) { + for(int i = 0; i < habits->count; i++) { + sqlite3_reset(stmt); + sqlite3_clear_bindings(stmt); + bind_text(stmt, 1, habits->items[i].id); + while(sqlite3_step(stmt) == SQLITE_ROW) { + int d = habits->items[i].day_count++; + if(!habit_reserve_days(&habits->items[i], habits->items[i].day_count)) { + habits->items[i].day_count--; + break; + } + habits->items[i].days[d].day_index = sqlite3_column_int(stmt, 0); + habits->items[i].days[d].completed = sqlite3_column_int(stmt, 1) != 0; + habits->items[i].days[d].count = sqlite3_column_int(stmt, 2); + if(habits->items[i].days[d].count <= 0 && habits->items[i].days[d].completed) + habits->items[i].days[d].count = 1; } - habits->items[i].days[d].day_index = sqlite3_column_int(stmt, 0); - habits->items[i].days[d].completed = sqlite3_column_int(stmt, 1) != 0; - habits->items[i].days[d].count = sqlite3_column_int(stmt, 2); - if(habits->items[i].days[d].count <= 0 && habits->items[i].days[d].completed) - habits->items[i].days[d].count = 1; } sqlite3_finalize(stmt); } @@ -2266,6 +2408,11 @@ storage_habits_save(const void *habits_ptr) { const InbeHabits *habits = habits_ptr; sqlite3_stmt *stmt = NULL; + sqlite3_stmt *loaded_stmt = NULL; + sqlite3_stmt *habit_stmt = NULL; + sqlite3_stmt *desc_stmt = NULL; + sqlite3_stmt *seen_stmt = NULL; + sqlite3_stmt *day_stmt = NULL; long long changed_at = storage_next_change_time(); if(habits == NULL || g_storage.db == NULL) return; @@ -2275,109 +2422,118 @@ storage_habits_save(const void *habits_ptr) "CREATE TEMP TABLE IF NOT EXISTS sync_loaded_habits(id TEXT PRIMARY KEY);" "DELETE FROM sync_seen_habits;" "DELETE FROM sync_loaded_habits;"); + sqlite3_prepare_v2(g_storage.db, "INSERT OR IGNORE INTO sync_loaded_habits(id) VALUES(?1)", + -1, &loaded_stmt, NULL); + sqlite3_prepare_v2(g_storage.db, + "INSERT INTO " + "habits(id,user_id,name,description,color_r,color_g,color_b,sync_mode,sync_" + "activity,counter_enabled,sort_order,deleted_at,updated_at) " + "VALUES(?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,0,?12) " + "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," + "sort_order=excluded.sort_order," + "deleted_at=0," + "updated_at=excluded.updated_at " + "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.sort_order<>excluded.sort_order OR " + "habits.deleted_at<>0", + -1, &habit_stmt, NULL); + sqlite3_prepare_v2(g_storage.db, + "UPDATE habits SET description=?2 " + "WHERE id=?1 AND description<>?2", + -1, &desc_stmt, NULL); + sqlite3_prepare_v2(g_storage.db, "INSERT OR IGNORE INTO sync_seen_habits(id) VALUES(?1)", + -1, &seen_stmt, NULL); + sqlite3_prepare_v2(g_storage.db, + "INSERT INTO " + "habit_days(habit_id,local_date,completed,count,updated_at) " + "VALUES(?1,?2,?3,?4,?5) " + "ON CONFLICT(habit_id,local_date) DO UPDATE SET " + "completed=excluded.completed," + "count=excluded.count," + "updated_at=CASE WHEN habit_days.completed<>excluded.completed " + "OR habit_days.count<>excluded.count " + "THEN excluded.updated_at ELSE habit_days.updated_at END", + -1, &day_stmt, NULL); for(int i = 0; i < habits->loaded_count && i < INBE_HABIT_MAX; i++) { if(habits->loaded_ids[i][0] == '\0') continue; - if(sqlite3_prepare_v2(g_storage.db, - "INSERT OR IGNORE INTO sync_loaded_habits(id) VALUES(?1)", -1, &stmt, - NULL) != SQLITE_OK) + if(loaded_stmt == NULL) continue; - bind_text(stmt, 1, habits->loaded_ids[i]); - sqlite3_step(stmt); - sqlite3_finalize(stmt); - stmt = NULL; + sqlite3_reset(loaded_stmt); + sqlite3_clear_bindings(loaded_stmt); + bind_text(loaded_stmt, 1, habits->loaded_ids[i]); + sqlite3_step(loaded_stmt); } for(int i = 0; i < habits->count; i++) { const InbeHabit *habit = &habits->items[i]; - if(sqlite3_prepare_v2(g_storage.db, - "INSERT INTO " - "habits(id,user_id,name,description,color_r,color_g,color_b,sync_mode,sync_" - "activity,counter_enabled,sort_order,deleted_at,updated_at) " - "VALUES(?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,0,?12) " - "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," - "sort_order=excluded.sort_order," - "deleted_at=0," - "updated_at=excluded.updated_at " - "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.sort_order<>excluded.sort_order OR " - "habits.deleted_at<>0", - -1, &stmt, NULL) != SQLITE_OK) + if(habit_stmt == NULL) continue; - bind_text(stmt, 1, habit->id); - bind_text(stmt, 2, g_storage.user_id); - bind_text(stmt, 3, habit->name); - bind_text(stmt, 4, habit->description); - sqlite3_bind_int(stmt, 5, habit->color.r); - sqlite3_bind_int(stmt, 6, habit->color.g); - sqlite3_bind_int(stmt, 7, habit->color.b); - sqlite3_bind_int(stmt, 8, habit->sync_mode); - sqlite3_bind_int(stmt, 9, habit->sync_activity); - sqlite3_bind_int(stmt, 10, habit->counter_enabled ? 1 : 0); - sqlite3_bind_int(stmt, 11, i); - sqlite3_bind_int64(stmt, 12, changed_at); - if(sqlite3_step(stmt) == SQLITE_DONE && sqlite3_changes(g_storage.db) > 0) + sqlite3_reset(habit_stmt); + sqlite3_clear_bindings(habit_stmt); + bind_text(habit_stmt, 1, habit->id); + bind_text(habit_stmt, 2, g_storage.user_id); + bind_text(habit_stmt, 3, habit->name); + bind_text(habit_stmt, 4, habit->description); + sqlite3_bind_int(habit_stmt, 5, habit->color.r); + sqlite3_bind_int(habit_stmt, 6, habit->color.g); + sqlite3_bind_int(habit_stmt, 7, habit->color.b); + sqlite3_bind_int(habit_stmt, 8, habit->sync_mode); + sqlite3_bind_int(habit_stmt, 9, habit->sync_activity); + sqlite3_bind_int(habit_stmt, 10, habit->counter_enabled ? 1 : 0); + sqlite3_bind_int(habit_stmt, 11, i); + sqlite3_bind_int64(habit_stmt, 12, changed_at); + if(sqlite3_step(habit_stmt) == SQLITE_DONE && sqlite3_changes(g_storage.db) > 0) storage_enqueue_sync_habit(habit->id); - sqlite3_finalize(stmt); - stmt = NULL; - if(sqlite3_prepare_v2(g_storage.db, - "UPDATE habits SET description=?2 " - "WHERE id=?1 AND description<>?2", - -1, &stmt, NULL) == SQLITE_OK) { - bind_text(stmt, 1, habit->id); - bind_text(stmt, 2, habit->description); - sqlite3_step(stmt); - sqlite3_finalize(stmt); - stmt = NULL; + if(desc_stmt != NULL) { + sqlite3_reset(desc_stmt); + sqlite3_clear_bindings(desc_stmt); + bind_text(desc_stmt, 1, habit->id); + bind_text(desc_stmt, 2, habit->description); + sqlite3_step(desc_stmt); } - if(sqlite3_prepare_v2(g_storage.db, "INSERT OR IGNORE INTO sync_seen_habits(id) VALUES(?1)", - -1, &stmt, NULL) == SQLITE_OK) { - bind_text(stmt, 1, habit->id); - sqlite3_step(stmt); - sqlite3_finalize(stmt); - stmt = NULL; + if(seen_stmt != NULL) { + sqlite3_reset(seen_stmt); + sqlite3_clear_bindings(seen_stmt); + bind_text(seen_stmt, 1, habit->id); + sqlite3_step(seen_stmt); } for(int d = 0; d < habit->day_count; d++) { - if(sqlite3_prepare_v2(g_storage.db, - "INSERT INTO " - "habit_days(habit_id,local_date,completed,count,updated_at) " - "VALUES(?1,?2,?3,?4,?5) " - "ON CONFLICT(habit_id,local_date) DO UPDATE SET " - "completed=excluded.completed," - "count=excluded.count," - "updated_at=CASE WHEN habit_days.completed<>excluded.completed " - "OR habit_days.count<>excluded.count " - "THEN excluded.updated_at ELSE habit_days.updated_at END", - -1, &stmt, NULL) != SQLITE_OK) + if(day_stmt == NULL) continue; - bind_text(stmt, 1, habit->id); - sqlite3_bind_int(stmt, 2, habit->days[d].day_index); - sqlite3_bind_int(stmt, 3, habit->days[d].count > 0 || habit->days[d].completed ? 1 : 0); - sqlite3_bind_int(stmt, 4, + sqlite3_reset(day_stmt); + sqlite3_clear_bindings(day_stmt); + bind_text(day_stmt, 1, habit->id); + sqlite3_bind_int(day_stmt, 2, habit->days[d].day_index); + sqlite3_bind_int(day_stmt, 3, habit->days[d].count > 0 || habit->days[d].completed ? 1 : 0); + sqlite3_bind_int(day_stmt, 4, habit->days[d].count > 0 ? habit->days[d].count : (habit->days[d].completed ? 1 : 0)); - sqlite3_bind_int64(stmt, 5, changed_at); - sqlite3_step(stmt); - sqlite3_finalize(stmt); - stmt = NULL; + sqlite3_bind_int64(day_stmt, 5, changed_at); + sqlite3_step(day_stmt); storage_enqueue_sync_habit_day(habit->id, habit->days[d].day_index); } } + sqlite3_finalize(loaded_stmt); + sqlite3_finalize(habit_stmt); + sqlite3_finalize(desc_stmt); + sqlite3_finalize(seen_stmt); + sqlite3_finalize(day_stmt); if(sqlite3_prepare_v2(g_storage.db, "SELECT id FROM habits WHERE user_id=?1 AND deleted_at=0 " "AND id IN (SELECT id FROM sync_loaded_habits) " diff --git a/src/storage/storage.h b/src/storage/storage.h index 8f94776ea..890d788f9 100644 --- a/src/storage/storage.h +++ b/src/storage/storage.h @@ -6,7 +6,8 @@ enum { INBE_STORAGE_PATH_SIZE = 512, - INBE_STORAGE_ID_SIZE = 64 + INBE_STORAGE_ID_SIZE = 64, + INBE_SYNC_PROTOCOL_VERSION = 3 }; typedef void (*InbeStorageSessionRecordCallback)(const char *id, @@ -35,6 +36,8 @@ typedef struct InbeStorageSyncStatus { int has_account; int review_pending; int repair_pending; + int protocol_upgrade_available; + int latest_protocol; int full_upload_done; long long server_version; long long server_clock; @@ -96,6 +99,7 @@ int storage_sync_review_apply_remote_if_local_empty(void); int storage_apply_pending_sync_review(int use_remote); void storage_purge_synced_deleted_data(void); const char *storage_sync_client_id(void); +void storage_make_uuid(char out[37]); void storage_reset_sync_state(void); int storage_habits_empty(void); diff --git a/src/storage/storage_sessions.c b/src/storage/storage_sessions.c index 6c2559ec9..8da0a64d4 100644 --- a/src/storage/storage_sessions.c +++ b/src/storage/storage_sessions.c @@ -42,6 +42,65 @@ parse_db_id(const char *path_or_id, char *out, size_t out_size) return out[0] != '\0'; } +static int +filter_positive_rounds(const int *round_times, int round_count, int *out, int out_max) +{ + int saved_count = 0; + + if(round_times == NULL || out == NULL || round_count < 0 || out_max <= 0) + return 0; + for(int i = 0; i < round_count && i < out_max; i++) { + if(round_times[i] > 0) + out[saved_count++] = round_times[i]; + } + return saved_count; +} + +static int +write_session_rounds(const char *session_id, const int *round_times, int round_count, + int replace) +{ + sqlite3_stmt *stmt = NULL; + + if(g_storage.db == NULL || session_id == NULL || round_times == NULL || round_count <= 0) + return 0; + if(sqlite3_prepare_v2(g_storage.db, + replace + ? "INSERT OR REPLACE INTO session_rounds(session_id,round_index,seconds) VALUES(?1,?2,?3)" + : "INSERT INTO session_rounds(session_id,round_index,seconds) VALUES(?1,?2,?3)", + -1, &stmt, NULL) != SQLITE_OK) + return 0; + for(int i = 0; i < round_count; i++) { + sqlite3_reset(stmt); + sqlite3_clear_bindings(stmt); + bind_text(stmt, 1, session_id); + sqlite3_bind_int(stmt, 2, i); + sqlite3_bind_int(stmt, 3, round_times[i]); + if(sqlite3_step(stmt) != SQLITE_DONE) { + sqlite3_finalize(stmt); + return 0; + } + } + sqlite3_finalize(stmt); + return 1; +} + +static int +storage_count_sql(const char *sql) +{ + sqlite3_stmt *stmt = NULL; + int count = 0; + + if(g_storage.db == NULL || sql == NULL) + return 0; + if(sqlite3_prepare_v2(g_storage.db, sql, -1, &stmt, NULL) != SQLITE_OK) + return 0; + if(sqlite3_step(stmt) == SQLITE_ROW) + count = sqlite3_column_int(stmt, 0); + sqlite3_finalize(stmt); + return count; +} + int insert_session_at_ex(long long started_at, int local_date, const int *round_times, int round_count, int topic, int activity, const char *source, char *out_id, size_t out_id_size) @@ -82,18 +141,8 @@ insert_session_at_ex(long long started_at, int local_date, const int *round_time inserted = sqlite3_changes(g_storage.db) > 0; if(inserted) { - for(int i = 0; i < round_count; i++) { - if(sqlite3_prepare_v2(g_storage.db, - "INSERT OR REPLACE INTO " - "session_rounds(session_id,round_index,seconds) VALUES(?1,?2,?3)", - -1, &stmt, NULL) != SQLITE_OK) - return 0; - bind_text(stmt, 1, id); - sqlite3_bind_int(stmt, 2, i); - sqlite3_bind_int(stmt, 3, round_times[i]); - sqlite3_step(stmt); - sqlite3_finalize(stmt); - } + if(!write_session_rounds(id, round_times, round_count, 1)) + return 0; storage_enqueue_sync_session(id); } @@ -112,15 +161,12 @@ storage_save_session_for_activity(const int *round_times, int round_count, int t time_t now = time(NULL); struct tm *tm = localtime(&now); int saved[MaxRounds]; - int saved_count = 0; + int saved_count; int local_date; if(tm == NULL) return 0; - for(int i = 0; i < round_count && i < MaxRounds; i++) { - if(round_times[i] > 0) - saved[saved_count++] = round_times[i]; - } + saved_count = filter_positive_rounds(round_times, round_count, saved, MaxRounds); if(saved_count <= 0) return 0; local_date = (tm->tm_year + 1900) * 10000 + (tm->tm_mon + 1) * 100 + tm->tm_mday; @@ -136,14 +182,11 @@ storage_save_session_at_for_activity(int local_date, int hour, int minute, int s struct tm tm; time_t started_at; int saved[MaxRounds]; - int saved_count = 0; + int saved_count; if(local_date <= 0) return 0; - for(int i = 0; i < round_count && i < MaxRounds; i++) { - if(round_times[i] > 0) - saved[saved_count++] = round_times[i]; - } + saved_count = filter_positive_rounds(round_times, round_count, saved, MaxRounds); if(saved_count <= 0) return 0; @@ -233,15 +276,12 @@ storage_replace_session(const char *path_or_id, const int *round_times, int roun sqlite3_stmt *stmt = NULL; char id[INBE_STORAGE_ID_SIZE]; int saved[MaxRounds]; - int saved_count = 0; + int saved_count; if(!parse_db_id(path_or_id, id, sizeof(id)) || round_times == NULL || round_count < 0 || round_count > MaxRounds) return 0; - for(int i = 0; i < round_count; i++) { - if(round_times[i] > 0) - saved[saved_count++] = round_times[i]; - } + saved_count = filter_positive_rounds(round_times, round_count, saved, MaxRounds); if(saved_count <= 0) return storage_delete_session(path_or_id); @@ -253,20 +293,8 @@ storage_replace_session(const char *path_or_id, const int *round_times, int roun sqlite3_step(stmt); sqlite3_finalize(stmt); stmt = NULL; - for(int i = 0; i < saved_count; i++) { - if(sqlite3_prepare_v2(g_storage.db, - "INSERT INTO session_rounds(session_id,round_index,seconds) " - "VALUES(?1,?2,?3)", - -1, &stmt, NULL) != SQLITE_OK) - goto fail; - bind_text(stmt, 1, id); - sqlite3_bind_int(stmt, 2, i); - sqlite3_bind_int(stmt, 3, saved[i]); - if(sqlite3_step(stmt) != SQLITE_DONE) - goto fail; - sqlite3_finalize(stmt); - stmt = NULL; - } + if(!write_session_rounds(id, saved, saved_count, 0)) + goto fail; if(sqlite3_prepare_v2(g_storage.db, "UPDATE sessions SET rounds_hash=?2,updated_at=?3 WHERE id=?1", -1, &stmt, NULL) != SQLITE_OK) @@ -436,7 +464,6 @@ storage_list_session_records(InbeStorageSessionRecordCallback callback, void *us int storage_has_any(void) { - sqlite3_stmt *stmt = NULL; int count = storage_session_count(); if(count > 0) @@ -446,30 +473,13 @@ storage_has_any(void) count = storage_habit_count(); if(count > 0) return 1; - if(sqlite3_prepare_v2(g_storage.db, - "SELECT COUNT(*) FROM habit_days WHERE completed!=0 OR count>0", -1, - &stmt, NULL) != SQLITE_OK) - return 0; - if(sqlite3_step(stmt) == SQLITE_ROW) - count = sqlite3_column_int(stmt, 0); - sqlite3_finalize(stmt); - return count > 0; + return storage_count_sql("SELECT COUNT(*) FROM habit_days WHERE completed!=0 OR count>0") > 0; } int storage_session_count(void) { - sqlite3_stmt *stmt = NULL; - int count = 0; - if(g_storage.db == NULL) - return 0; - if(sqlite3_prepare_v2(g_storage.db, "SELECT COUNT(*) FROM sessions WHERE deleted_at=0", -1, - &stmt, NULL) != SQLITE_OK) - return 0; - if(sqlite3_step(stmt) == SQLITE_ROW) - count = sqlite3_column_int(stmt, 0); - sqlite3_finalize(stmt); - return count; + return storage_count_sql("SELECT COUNT(*) FROM sessions WHERE deleted_at=0"); } long long @@ -496,13 +506,8 @@ storage_delete_all_sessions(void) if(g_storage.db == NULL) return 0; - if(sqlite3_prepare_v2(g_storage.db, - "SELECT COUNT(*) FROM habit_days WHERE completed!=0 OR count>0", -1, - &stmt, NULL) == SQLITE_OK) { - if(sqlite3_step(stmt) == SQLITE_ROW) - habit_day_count = sqlite3_column_int(stmt, 0); - sqlite3_finalize(stmt); - } + habit_day_count = storage_count_sql( + "SELECT COUNT(*) FROM habit_days WHERE completed!=0 OR count>0"); if(count <= 0 && habit_day_count <= 0 && habit_count <= 0) return 0; diff --git a/src/storage/sync_review.c b/src/storage/sync_review.c index c45ee3089..627d768ae 100644 --- a/src/storage/sync_review.c +++ b/src/storage/sync_review.c @@ -31,6 +31,24 @@ static int review_has_unknown_activity(const char *json); static int review_small_session_only_change(const char *diff); static int review_visible_change_count(const char *diff); +static int +review_sql_bool(const char *sql, const char *text_arg, int fallback) +{ + sqlite3_stmt *stmt = NULL; + int result = fallback; + + if(g_storage.db == NULL || sql == NULL) + return fallback; + if(sqlite3_prepare_v2(g_storage.db, sql, -1, &stmt, NULL) != SQLITE_OK) + return fallback; + if(text_arg != NULL) + bind_text(stmt, 1, text_arg); + if(sqlite3_step(stmt) == SQLITE_ROW) + result = sqlite3_column_int(stmt, 0) != 0; + sqlite3_finalize(stmt); + return result; +} + static int review_reserve(ReviewText *text, size_t extra) { @@ -245,6 +263,41 @@ review_append_activity_heading(ReviewText *out, int activity) review_append(out, "\n"); } +static void +review_append_date(ReviewText *out, int local_date) +{ + review_appendf(out, "%04d-%02d-%02d", + local_date / 10000, (local_date / 100) % 100, + local_date % 100); +} + +static void +review_append_date_time(ReviewText *out, int local_date, const char *time_text) +{ + review_append_date(out, local_date); + review_appendf(out, " %s\n", time_text != NULL ? time_text : "--:--"); +} + +static void +review_append_habit_day(ReviewText *out, char *last_name, size_t last_name_size, + int *rows, const char *name, int local_date, int count) +{ + const char *safe_name = name != NULL && name[0] != '\0' ? name : "(unnamed)"; + + if(strcmp(last_name, safe_name) != 0) { + if(*rows > 0) + review_append(out, "\n"); + review_append(out, safe_name); + review_append(out, "\n"); + snprintf(last_name, last_name_size, "%s", safe_name); + } + review_append_date(out, local_date); + if(count > 0) + review_appendf(out, " count %d", count); + review_append(out, "\n"); + (*rows)++; +} + static void review_append_local_rounds(ReviewText *out, const char *session_id) { @@ -315,9 +368,7 @@ review_append_local(ReviewText *out) review_append_activity_heading(out, activity); last_activity = activity; } - review_appendf(out, "%04d-%02d-%02d %s\n", - local_date / 10000, (local_date / 100) % 100, - local_date % 100, time_text != NULL ? time_text : "--:--"); + review_append_date_time(out, local_date, time_text); if(activity == 2) { review_append(out, "session 1"); } else if(review_activity_uses_duration(activity)) { @@ -350,21 +401,8 @@ review_append_local(ReviewText *out) while(sqlite3_step(stmt) == SQLITE_ROW) { int local_date = sqlite3_column_int(stmt, 1); const char *name = (const char *)sqlite3_column_text(stmt, 0); - const char *safe_name = name != NULL && name[0] != '\0' ? name : "(unnamed)"; - if(strcmp(last_name, safe_name) != 0) { - if(rows > 0) - review_append(out, "\n"); - review_append(out, safe_name); - review_append(out, "\n"); - snprintf(last_name, sizeof(last_name), "%s", safe_name); - } - review_appendf(out, "%04d-%02d-%02d", - local_date / 10000, (local_date / 100) % 100, - local_date % 100); - if(sqlite3_column_int(stmt, 2) > 0) - review_appendf(out, " count %d", sqlite3_column_int(stmt, 2)); - review_append(out, "\n"); - rows++; + review_append_habit_day(out, last_name, sizeof(last_name), &rows, + name, local_date, sqlite3_column_int(stmt, 2)); } sqlite3_finalize(stmt); } @@ -407,9 +445,7 @@ review_append_remote(ReviewText *out, const char *json) review_append_activity_heading(out, activity); last_activity = activity; } - review_appendf(out, "%04d-%02d-%02d %s\n", - local_date / 10000, (local_date / 100) % 100, - local_date % 100, time_text != NULL ? time_text : "--:--"); + review_append_date_time(out, local_date, time_text); if(activity == 2) review_append(out, "session 1"); else if(review_activity_uses_duration(activity)) @@ -444,23 +480,10 @@ review_append_remote(ReviewText *out, const char *json) while(sqlite3_step(stmt) == SQLITE_ROW) { int local_date = sqlite3_column_int(stmt, 1); const char *name = (const char *)sqlite3_column_text(stmt, 0); - const char *safe_name = name != NULL ? name : ""; - if(safe_name[0] == '\0') + if(name == NULL || name[0] == '\0') continue; - if(strcmp(last_name, safe_name) != 0) { - if(rows > 0) - review_append(out, "\n"); - review_append(out, safe_name); - review_append(out, "\n"); - snprintf(last_name, sizeof(last_name), "%s", safe_name); - } - review_appendf(out, "%04d-%02d-%02d", - local_date / 10000, (local_date / 100) % 100, - local_date % 100); - if(sqlite3_column_int(stmt, 2) > 0) - review_appendf(out, " count %d", sqlite3_column_int(stmt, 2)); - review_append(out, "\n"); - rows++; + review_append_habit_day(out, last_name, sizeof(last_name), &rows, + name, local_date, sqlite3_column_int(stmt, 2)); } sqlite3_finalize(stmt); } @@ -642,100 +665,49 @@ storage_sync_review_json_should_auto_apply_remote(const char *json) static int review_has_local_activity(void) { - sqlite3_stmt *stmt = NULL; - int result = 0; - - if(g_storage.db == NULL) - return 0; - if(sqlite3_prepare_v2(g_storage.db, - "SELECT EXISTS(" - " SELECT 1 FROM sessions WHERE deleted_at=0" - " UNION ALL" - " SELECT 1 FROM habit_days " - " WHERE completed!=0 OR count>0 OR session_count>0" - " LIMIT 1" - ")", - -1, &stmt, NULL) != SQLITE_OK) - return 1; - if(sqlite3_step(stmt) == SQLITE_ROW) - result = sqlite3_column_int(stmt, 0) != 0; - sqlite3_finalize(stmt); - return result; + return review_sql_bool("SELECT EXISTS(" + " SELECT 1 FROM sessions WHERE deleted_at=0" + " UNION ALL" + " SELECT 1 FROM habit_days " + " WHERE completed!=0 OR count>0 OR session_count>0" + " LIMIT 1" + ")", + NULL, 1); } static int review_has_pending_outbox(void) { - sqlite3_stmt *stmt = NULL; - int result = 0; - - if(g_storage.db == NULL) - return 1; - if(sqlite3_prepare_v2(g_storage.db, - "SELECT EXISTS(SELECT 1 FROM sync_outbox LIMIT 1)", - -1, &stmt, NULL) != SQLITE_OK) - return 1; - if(sqlite3_step(stmt) == SQLITE_ROW) - result = sqlite3_column_int(stmt, 0) != 0; - sqlite3_finalize(stmt); - return result; + return review_sql_bool("SELECT EXISTS(SELECT 1 FROM sync_outbox LIMIT 1)", + NULL, 1); } static int review_pending_outbox_sessions_only(void) { - sqlite3_stmt *stmt = NULL; - int result = 0; - - if(g_storage.db == NULL) - return 0; - if(sqlite3_prepare_v2(g_storage.db, - "SELECT EXISTS(SELECT 1 FROM sync_outbox LIMIT 1) " - "AND NOT EXISTS(SELECT 1 FROM sync_outbox WHERE entity_type<>'session')", - -1, &stmt, NULL) != SQLITE_OK) - return 0; - if(sqlite3_step(stmt) == SQLITE_ROW) - result = sqlite3_column_int(stmt, 0) != 0; - sqlite3_finalize(stmt); - return result; + return review_sql_bool( + "SELECT EXISTS(SELECT 1 FROM sync_outbox LIMIT 1) " + "AND NOT EXISTS(SELECT 1 FROM sync_outbox WHERE entity_type<>'session')", + NULL, 0); } static int review_has_unknown_activity(const char *json) { - sqlite3_stmt *stmt = NULL; - int result = 0; - - if(g_storage.db == NULL) - return 1; - if(sqlite3_prepare_v2(g_storage.db, - "SELECT EXISTS(SELECT 1 FROM sessions " - "WHERE deleted_at=0 AND activity NOT IN (0,1,2))", - -1, &stmt, NULL) != SQLITE_OK) - return 1; - if(sqlite3_step(stmt) == SQLITE_ROW) - result = sqlite3_column_int(stmt, 0) != 0; - sqlite3_finalize(stmt); - if(result) + if(review_sql_bool("SELECT EXISTS(SELECT 1 FROM sessions " + "WHERE deleted_at=0 AND activity NOT IN (0,1,2))", + NULL, 1)) return 1; if(json == NULL) return 0; - if(sqlite3_prepare_v2(g_storage.db, - "SELECT EXISTS(" - " SELECT 1 FROM json_each(?1,'$.changes.sessions') AS s " - " WHERE CAST(COALESCE(json_extract(s.value,'$.deleted_at'),0) AS INTEGER)=0 " - " AND CAST(COALESCE(json_extract(s.value,'$.activity'),0) AS INTEGER) NOT IN (0,1,2)" - ")", - -1, &stmt, NULL) != SQLITE_OK) - return 1; - bind_text(stmt, 1, json); - if(sqlite3_step(stmt) == SQLITE_ROW) - result = sqlite3_column_int(stmt, 0) != 0; - sqlite3_finalize(stmt); - if(result) - return 1; - return 0; + return review_sql_bool( + "SELECT EXISTS(" + " SELECT 1 FROM json_each(?1,'$.changes.sessions') AS s " + " WHERE CAST(COALESCE(json_extract(s.value,'$.deleted_at'),0) AS INTEGER)=0 " + " AND CAST(COALESCE(json_extract(s.value,'$.activity'),0) AS INTEGER) NOT IN (0,1,2)" + ")", + json, 1); } static int diff --git a/src/web_shell.html b/src/web_shell.html index 7a01b5d5d..5e0cf23e3 100644 --- a/src/web_shell.html +++ b/src/web_shell.html @@ -22,10 +22,15 @@