From 5d9bff6b769903044ab06570bc6cbc3ef72142f2 Mon Sep 17 00:00:00 2001 From: Ken Van Hoeylandt Date: Fri, 13 Nov 2026 23:28:47 +0100 Subject: [PATCH 01/12] Implement app icons --- Buildscripts/TactilitySDK/Tools/app.py | 7 + Buildscripts/generate-assets.py | 2 +- CMakeLists.txt | 2 + Data/system/app_icon/default.svg | 1 + Data/system/app_icon/default_mono.svg | 1 + Data/system/app_icon/tactility.appearance.svg | 1 + .../app_icon/tactility.appearance_mono.svg | 1 + Data/system/app_icon/tactility.apphub.svg | 1 + .../system/app_icon/tactility.apphub_mono.svg | 1 + .../app_icon/tactility.audiosettings.svg | 1 + .../app_icon/tactility.audiosettings_mono.svg | 1 + Data/system/app_icon/tactility.btmanage.svg | 1 + .../app_icon/tactility.btmanage_mono.svg | 1 + Data/system/app_icon/tactility.camera.svg | 1 + .../system/app_icon/tactility.camera_mono.svg | 1 + Data/system/app_icon/tactility.chat.svg | 1 + Data/system/app_icon/tactility.chat_mono.svg | 1 + .../system/app_icon/tactility.development.svg | 1 + .../app_icon/tactility.development_mono.svg | 1 + Data/system/app_icon/tactility.display.svg | 1 + .../app_icon/tactility.display_mono.svg | 1 + Data/system/app_icon/tactility.files.svg | 1 + Data/system/app_icon/tactility.files_mono.svg | 1 + .../app_icon/tactility.grovesettings.svg | 1 + .../app_icon/tactility.grovesettings_mono.svg | 1 + Data/system/app_icon/tactility.i2cscanner.svg | 1 + .../app_icon/tactility.i2cscanner_mono.svg | 1 + .../app_icon/tactility.keyboardsettings.svg | 1 + .../tactility.keyboardsettings_mono.svg | 1 + .../app_icon/tactility.ledstripsettings.svg | 1 + .../tactility.ledstripsettings_mono.svg | 1 + .../app_icon/tactility.locationsettings.svg | 1 + .../tactility.locationsettings_mono.svg | 1 + Data/system/app_icon/tactility.maps.svg | 1 + Data/system/app_icon/tactility.maps_mono.svg | 1 + .../app_icon/tactility.meshchannels.svg | 1 + .../app_icon/tactility.meshchannels_mono.svg | 1 + .../app_icon/tactility.meshcontacts.svg | 1 + .../app_icon/tactility.meshcontacts_mono.svg | 1 + .../app_icon/tactility.meshsettings.svg | 1 + .../app_icon/tactility.meshsettings_mono.svg | 1 + Data/system/app_icon/tactility.notes.svg | 1 + Data/system/app_icon/tactility.notes_mono.svg | 1 + Data/system/app_icon/tactility.power.svg | 1 + Data/system/app_icon/tactility.power_mono.svg | 1 + Data/system/app_icon/tactility.systeminfo.svg | 1 + .../app_icon/tactility.systeminfo_mono.svg | 1 + Data/system/app_icon/tactility.terminal.svg | 1 + .../app_icon/tactility.terminal_mono.svg | 1 + .../app_icon/tactility.timedatesettings.svg | 1 + .../tactility.timedatesettings_mono.svg | 1 + .../app_icon/tactility.touchcalibration.svg | 1 + .../tactility.touchcalibration_mono.svg | 1 + .../app_icon/tactility.trackballsettings.svg | 1 + .../tactility.trackballsettings_mono.svg | 1 + .../system/app_icon/tactility.usbsettings.svg | 1 + .../app_icon/tactility.usbsettings_mono.svg | 1 + .../app_icon/tactility.vibrationsettings.svg | 1 + .../tactility.vibrationsettings_mono.svg | 1 + Data/system/app_icon/tactility.wifimanage.svg | 1 + .../app_icon/tactility.wifimanage_mono.svg | 1 + Data/system/file_icon/app.svg | 1 + Data/system/file_icon/app_mono.svg | 1 + Data/system/file_icon/executable.svg | 1 + Data/system/file_icon/executable_mono.svg | 1 + Data/system/file_icon/file.svg | 1 + Data/system/file_icon/file_mono.svg | 1 + Data/system/file_icon/folder.svg | 1 + Data/system/file_icon/folder_mono.svg | 1 + Data/system/file_icon/image.svg | 1 + Data/system/file_icon/image_mono.svg | 1 + Data/system/file_icon/link.svg | 1 + Data/system/file_icon/link_mono.svg | 1 + Data/system/file_icon/sd_card.svg | 1 + Data/system/file_icon/sd_card_mono.svg | 1 + Data/system/file_icon/text.svg | 1 + Data/system/file_icon/text_mono.svg | 1 + Data/system/file_icon/usb.svg | 1 + Data/system/file_icon/usb_mono.svg | 1 + Libraries/nanosvg/CMakeLists.txt | 10 + Libraries/nanosvg/LICENSE.txt | 18 + Libraries/nanosvg/src/nanosvg.h | 3278 +++++++++++++++++ Libraries/nanosvg/src/nanosvgrast.h | 1472 ++++++++ Modules/app-module/include/app/manager.h | 16 + .../app-module/private/app/private/ledger.h | 7 + Modules/app-module/source/manager.cpp | 35 + Modules/app-module/source/module.cpp | 2 + .../app-module/tests/source/manager_test.cpp | 24 + Modules/lvgl-module/CMakeLists.txt | 1 + Modules/lvgl-module/include/lvgl/svg.h | 59 + Modules/lvgl-module/source/svg.c | 125 + Modules/lvgl-module/source/symbols.c | 1 + Modules/lvgl-module/tests/CMakeLists.txt | 4 + Modules/lvgl-module/tests/source/svg_test.cpp | 172 + Tactility/Private/Tactility/app/TileGrid.h | 8 +- Tactility/Private/Tactility/app/files/View.h | 10 +- .../Tactility/app/launcher/LauncherMode.h | 21 + Tactility/Source/app/TileGrid.cpp | 40 +- Tactility/Source/app/files/FilesApp.cpp | 1 + Tactility/Source/app/files/View.cpp | 80 +- Tactility/Source/app/launcher/AppsMode.cpp | 269 +- Tactility/Source/app/launcher/Launcher.cpp | 82 +- .../Source/app/launcher/SettingsMode.cpp | 155 +- 103 files changed, 5900 insertions(+), 77 deletions(-) create mode 100644 Data/system/app_icon/default.svg create mode 100644 Data/system/app_icon/default_mono.svg create mode 100644 Data/system/app_icon/tactility.appearance.svg create mode 100644 Data/system/app_icon/tactility.appearance_mono.svg create mode 100644 Data/system/app_icon/tactility.apphub.svg create mode 100644 Data/system/app_icon/tactility.apphub_mono.svg create mode 100644 Data/system/app_icon/tactility.audiosettings.svg create mode 100644 Data/system/app_icon/tactility.audiosettings_mono.svg create mode 100644 Data/system/app_icon/tactility.btmanage.svg create mode 100644 Data/system/app_icon/tactility.btmanage_mono.svg create mode 100644 Data/system/app_icon/tactility.camera.svg create mode 100644 Data/system/app_icon/tactility.camera_mono.svg create mode 100644 Data/system/app_icon/tactility.chat.svg create mode 100644 Data/system/app_icon/tactility.chat_mono.svg create mode 100644 Data/system/app_icon/tactility.development.svg create mode 100644 Data/system/app_icon/tactility.development_mono.svg create mode 100644 Data/system/app_icon/tactility.display.svg create mode 100644 Data/system/app_icon/tactility.display_mono.svg create mode 100644 Data/system/app_icon/tactility.files.svg create mode 100644 Data/system/app_icon/tactility.files_mono.svg create mode 100644 Data/system/app_icon/tactility.grovesettings.svg create mode 100644 Data/system/app_icon/tactility.grovesettings_mono.svg create mode 100644 Data/system/app_icon/tactility.i2cscanner.svg create mode 100644 Data/system/app_icon/tactility.i2cscanner_mono.svg create mode 100644 Data/system/app_icon/tactility.keyboardsettings.svg create mode 100644 Data/system/app_icon/tactility.keyboardsettings_mono.svg create mode 100644 Data/system/app_icon/tactility.ledstripsettings.svg create mode 100644 Data/system/app_icon/tactility.ledstripsettings_mono.svg create mode 100644 Data/system/app_icon/tactility.locationsettings.svg create mode 100644 Data/system/app_icon/tactility.locationsettings_mono.svg create mode 100644 Data/system/app_icon/tactility.maps.svg create mode 100644 Data/system/app_icon/tactility.maps_mono.svg create mode 100644 Data/system/app_icon/tactility.meshchannels.svg create mode 100644 Data/system/app_icon/tactility.meshchannels_mono.svg create mode 100644 Data/system/app_icon/tactility.meshcontacts.svg create mode 100644 Data/system/app_icon/tactility.meshcontacts_mono.svg create mode 100644 Data/system/app_icon/tactility.meshsettings.svg create mode 100644 Data/system/app_icon/tactility.meshsettings_mono.svg create mode 100644 Data/system/app_icon/tactility.notes.svg create mode 100644 Data/system/app_icon/tactility.notes_mono.svg create mode 100644 Data/system/app_icon/tactility.power.svg create mode 100644 Data/system/app_icon/tactility.power_mono.svg create mode 100644 Data/system/app_icon/tactility.systeminfo.svg create mode 100644 Data/system/app_icon/tactility.systeminfo_mono.svg create mode 100644 Data/system/app_icon/tactility.terminal.svg create mode 100644 Data/system/app_icon/tactility.terminal_mono.svg create mode 100644 Data/system/app_icon/tactility.timedatesettings.svg create mode 100644 Data/system/app_icon/tactility.timedatesettings_mono.svg create mode 100644 Data/system/app_icon/tactility.touchcalibration.svg create mode 100644 Data/system/app_icon/tactility.touchcalibration_mono.svg create mode 100644 Data/system/app_icon/tactility.trackballsettings.svg create mode 100644 Data/system/app_icon/tactility.trackballsettings_mono.svg create mode 100644 Data/system/app_icon/tactility.usbsettings.svg create mode 100644 Data/system/app_icon/tactility.usbsettings_mono.svg create mode 100644 Data/system/app_icon/tactility.vibrationsettings.svg create mode 100644 Data/system/app_icon/tactility.vibrationsettings_mono.svg create mode 100644 Data/system/app_icon/tactility.wifimanage.svg create mode 100644 Data/system/app_icon/tactility.wifimanage_mono.svg create mode 100644 Data/system/file_icon/app.svg create mode 100644 Data/system/file_icon/app_mono.svg create mode 100644 Data/system/file_icon/executable.svg create mode 100644 Data/system/file_icon/executable_mono.svg create mode 100644 Data/system/file_icon/file.svg create mode 100644 Data/system/file_icon/file_mono.svg create mode 100644 Data/system/file_icon/folder.svg create mode 100644 Data/system/file_icon/folder_mono.svg create mode 100644 Data/system/file_icon/image.svg create mode 100644 Data/system/file_icon/image_mono.svg create mode 100644 Data/system/file_icon/link.svg create mode 100644 Data/system/file_icon/link_mono.svg create mode 100644 Data/system/file_icon/sd_card.svg create mode 100644 Data/system/file_icon/sd_card_mono.svg create mode 100644 Data/system/file_icon/text.svg create mode 100644 Data/system/file_icon/text_mono.svg create mode 100644 Data/system/file_icon/usb.svg create mode 100644 Data/system/file_icon/usb_mono.svg create mode 100644 Libraries/nanosvg/CMakeLists.txt create mode 100644 Libraries/nanosvg/LICENSE.txt create mode 100644 Libraries/nanosvg/src/nanosvg.h create mode 100644 Libraries/nanosvg/src/nanosvgrast.h create mode 100644 Modules/lvgl-module/include/lvgl/svg.h create mode 100644 Modules/lvgl-module/source/svg.c create mode 100644 Modules/lvgl-module/tests/source/svg_test.cpp diff --git a/Buildscripts/TactilitySDK/Tools/app.py b/Buildscripts/TactilitySDK/Tools/app.py index 72c23db88..f0e6396d3 100755 --- a/Buildscripts/TactilitySDK/Tools/app.py +++ b/Buildscripts/TactilitySDK/Tools/app.py @@ -642,6 +642,12 @@ def package_intermediate_assets(target_path): if os.path.isdir("assets"): shutil.copytree("assets", os.path.join(target_path, "assets"), dirs_exist_ok=True) +def package_intermediate_icon(target_path): + # icon.svg is the colour icon, icon_mono.svg the single colour one for mono displays. Either can be omitted. + for icon in ("icon.svg", "icon_mono.svg"): + if os.path.isfile(icon): + shutil.copy(icon, os.path.join(target_path, icon)) + def package_intermediate(platforms, manifest): target_path = os.path.abspath(os.path.join("build", "package-intermediate")) if os.path.isdir(target_path): @@ -652,6 +658,7 @@ def package_intermediate(platforms, manifest): if not package_intermediate_binaries(target_path, platforms, manifest): return False package_intermediate_assets(target_path) + package_intermediate_icon(target_path) return True def package_name(manifest): diff --git a/Buildscripts/generate-assets.py b/Buildscripts/generate-assets.py index 8e5ba92c1..baf72e098 100644 --- a/Buildscripts/generate-assets.py +++ b/Buildscripts/generate-assets.py @@ -16,7 +16,7 @@ import re import sys -TEXT_EXTENSIONS = {".pem", ".csv", ".html", ".json", ".codepoints", ".i18n", ".txt"} +TEXT_EXTENSIONS = {".pem", ".csv", ".html", ".json", ".codepoints", ".i18n", ".txt", ".svg"} def symbol_name(relative_path: str) -> str: diff --git a/CMakeLists.txt b/CMakeLists.txt index 363e707a3..731905f2b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -51,6 +51,7 @@ if (DEFINED ENV{ESP_IDF_VERSION}) "Libraries/minitar" "Libraries/ed25519" "Libraries/minmea" + "Libraries/nanosvg" "Libraries/QRCode" "Libraries/esp32-audio-codec" ) @@ -165,6 +166,7 @@ if (NOT DEFINED ENV{ESP_IDF_VERSION}) add_subdirectory(Libraries/minitar) add_subdirectory(Libraries/ed25519) add_subdirectory(Libraries/minmea) + add_subdirectory(Libraries/nanosvg) add_subdirectory(Modules/lvgl-module) add_subdirectory(Modules/audio-decoder-module) add_subdirectory(Modules/binfont-module) diff --git a/Data/system/app_icon/default.svg b/Data/system/app_icon/default.svg new file mode 100644 index 000000000..8aa3538a3 --- /dev/null +++ b/Data/system/app_icon/default.svg @@ -0,0 +1 @@ + diff --git a/Data/system/app_icon/default_mono.svg b/Data/system/app_icon/default_mono.svg new file mode 100644 index 000000000..893b2f5ff --- /dev/null +++ b/Data/system/app_icon/default_mono.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Data/system/app_icon/tactility.appearance.svg b/Data/system/app_icon/tactility.appearance.svg new file mode 100644 index 000000000..7e27acc98 --- /dev/null +++ b/Data/system/app_icon/tactility.appearance.svg @@ -0,0 +1 @@ + diff --git a/Data/system/app_icon/tactility.appearance_mono.svg b/Data/system/app_icon/tactility.appearance_mono.svg new file mode 100644 index 000000000..315fc5c58 --- /dev/null +++ b/Data/system/app_icon/tactility.appearance_mono.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Data/system/app_icon/tactility.apphub.svg b/Data/system/app_icon/tactility.apphub.svg new file mode 100644 index 000000000..b3e1912e5 --- /dev/null +++ b/Data/system/app_icon/tactility.apphub.svg @@ -0,0 +1 @@ + diff --git a/Data/system/app_icon/tactility.apphub_mono.svg b/Data/system/app_icon/tactility.apphub_mono.svg new file mode 100644 index 000000000..d440715ec --- /dev/null +++ b/Data/system/app_icon/tactility.apphub_mono.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Data/system/app_icon/tactility.audiosettings.svg b/Data/system/app_icon/tactility.audiosettings.svg new file mode 100644 index 000000000..bd44fff75 --- /dev/null +++ b/Data/system/app_icon/tactility.audiosettings.svg @@ -0,0 +1 @@ + diff --git a/Data/system/app_icon/tactility.audiosettings_mono.svg b/Data/system/app_icon/tactility.audiosettings_mono.svg new file mode 100644 index 000000000..1e54fdf51 --- /dev/null +++ b/Data/system/app_icon/tactility.audiosettings_mono.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Data/system/app_icon/tactility.btmanage.svg b/Data/system/app_icon/tactility.btmanage.svg new file mode 100644 index 000000000..99a51de51 --- /dev/null +++ b/Data/system/app_icon/tactility.btmanage.svg @@ -0,0 +1 @@ + diff --git a/Data/system/app_icon/tactility.btmanage_mono.svg b/Data/system/app_icon/tactility.btmanage_mono.svg new file mode 100644 index 000000000..62c33356c --- /dev/null +++ b/Data/system/app_icon/tactility.btmanage_mono.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Data/system/app_icon/tactility.camera.svg b/Data/system/app_icon/tactility.camera.svg new file mode 100644 index 000000000..0cf101bd8 --- /dev/null +++ b/Data/system/app_icon/tactility.camera.svg @@ -0,0 +1 @@ + diff --git a/Data/system/app_icon/tactility.camera_mono.svg b/Data/system/app_icon/tactility.camera_mono.svg new file mode 100644 index 000000000..9ac20f1dd --- /dev/null +++ b/Data/system/app_icon/tactility.camera_mono.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Data/system/app_icon/tactility.chat.svg b/Data/system/app_icon/tactility.chat.svg new file mode 100644 index 000000000..efe07371c --- /dev/null +++ b/Data/system/app_icon/tactility.chat.svg @@ -0,0 +1 @@ + diff --git a/Data/system/app_icon/tactility.chat_mono.svg b/Data/system/app_icon/tactility.chat_mono.svg new file mode 100644 index 000000000..1d469dca6 --- /dev/null +++ b/Data/system/app_icon/tactility.chat_mono.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Data/system/app_icon/tactility.development.svg b/Data/system/app_icon/tactility.development.svg new file mode 100644 index 000000000..959cf8599 --- /dev/null +++ b/Data/system/app_icon/tactility.development.svg @@ -0,0 +1 @@ + diff --git a/Data/system/app_icon/tactility.development_mono.svg b/Data/system/app_icon/tactility.development_mono.svg new file mode 100644 index 000000000..9f6a097d7 --- /dev/null +++ b/Data/system/app_icon/tactility.development_mono.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Data/system/app_icon/tactility.display.svg b/Data/system/app_icon/tactility.display.svg new file mode 100644 index 000000000..4bc6c41b5 --- /dev/null +++ b/Data/system/app_icon/tactility.display.svg @@ -0,0 +1 @@ + diff --git a/Data/system/app_icon/tactility.display_mono.svg b/Data/system/app_icon/tactility.display_mono.svg new file mode 100644 index 000000000..0612fa40e --- /dev/null +++ b/Data/system/app_icon/tactility.display_mono.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Data/system/app_icon/tactility.files.svg b/Data/system/app_icon/tactility.files.svg new file mode 100644 index 000000000..d66244542 --- /dev/null +++ b/Data/system/app_icon/tactility.files.svg @@ -0,0 +1 @@ + diff --git a/Data/system/app_icon/tactility.files_mono.svg b/Data/system/app_icon/tactility.files_mono.svg new file mode 100644 index 000000000..e25b30152 --- /dev/null +++ b/Data/system/app_icon/tactility.files_mono.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Data/system/app_icon/tactility.grovesettings.svg b/Data/system/app_icon/tactility.grovesettings.svg new file mode 100644 index 000000000..b1cc8c629 --- /dev/null +++ b/Data/system/app_icon/tactility.grovesettings.svg @@ -0,0 +1 @@ + diff --git a/Data/system/app_icon/tactility.grovesettings_mono.svg b/Data/system/app_icon/tactility.grovesettings_mono.svg new file mode 100644 index 000000000..107e4a13f --- /dev/null +++ b/Data/system/app_icon/tactility.grovesettings_mono.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Data/system/app_icon/tactility.i2cscanner.svg b/Data/system/app_icon/tactility.i2cscanner.svg new file mode 100644 index 000000000..6ebffc915 --- /dev/null +++ b/Data/system/app_icon/tactility.i2cscanner.svg @@ -0,0 +1 @@ + diff --git a/Data/system/app_icon/tactility.i2cscanner_mono.svg b/Data/system/app_icon/tactility.i2cscanner_mono.svg new file mode 100644 index 000000000..107e4a13f --- /dev/null +++ b/Data/system/app_icon/tactility.i2cscanner_mono.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Data/system/app_icon/tactility.keyboardsettings.svg b/Data/system/app_icon/tactility.keyboardsettings.svg new file mode 100644 index 000000000..5685bc685 --- /dev/null +++ b/Data/system/app_icon/tactility.keyboardsettings.svg @@ -0,0 +1 @@ + diff --git a/Data/system/app_icon/tactility.keyboardsettings_mono.svg b/Data/system/app_icon/tactility.keyboardsettings_mono.svg new file mode 100644 index 000000000..eacd7a79b --- /dev/null +++ b/Data/system/app_icon/tactility.keyboardsettings_mono.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Data/system/app_icon/tactility.ledstripsettings.svg b/Data/system/app_icon/tactility.ledstripsettings.svg new file mode 100644 index 000000000..73be715a7 --- /dev/null +++ b/Data/system/app_icon/tactility.ledstripsettings.svg @@ -0,0 +1 @@ + diff --git a/Data/system/app_icon/tactility.ledstripsettings_mono.svg b/Data/system/app_icon/tactility.ledstripsettings_mono.svg new file mode 100644 index 000000000..acdab4b4a --- /dev/null +++ b/Data/system/app_icon/tactility.ledstripsettings_mono.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Data/system/app_icon/tactility.locationsettings.svg b/Data/system/app_icon/tactility.locationsettings.svg new file mode 100644 index 000000000..df27a934e --- /dev/null +++ b/Data/system/app_icon/tactility.locationsettings.svg @@ -0,0 +1 @@ + diff --git a/Data/system/app_icon/tactility.locationsettings_mono.svg b/Data/system/app_icon/tactility.locationsettings_mono.svg new file mode 100644 index 000000000..229959a62 --- /dev/null +++ b/Data/system/app_icon/tactility.locationsettings_mono.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Data/system/app_icon/tactility.maps.svg b/Data/system/app_icon/tactility.maps.svg new file mode 100644 index 000000000..8517674c8 --- /dev/null +++ b/Data/system/app_icon/tactility.maps.svg @@ -0,0 +1 @@ + diff --git a/Data/system/app_icon/tactility.maps_mono.svg b/Data/system/app_icon/tactility.maps_mono.svg new file mode 100644 index 000000000..f57e88b1d --- /dev/null +++ b/Data/system/app_icon/tactility.maps_mono.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Data/system/app_icon/tactility.meshchannels.svg b/Data/system/app_icon/tactility.meshchannels.svg new file mode 100644 index 000000000..762133368 --- /dev/null +++ b/Data/system/app_icon/tactility.meshchannels.svg @@ -0,0 +1 @@ + diff --git a/Data/system/app_icon/tactility.meshchannels_mono.svg b/Data/system/app_icon/tactility.meshchannels_mono.svg new file mode 100644 index 000000000..1d469dca6 --- /dev/null +++ b/Data/system/app_icon/tactility.meshchannels_mono.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Data/system/app_icon/tactility.meshcontacts.svg b/Data/system/app_icon/tactility.meshcontacts.svg new file mode 100644 index 000000000..7afbfcf97 --- /dev/null +++ b/Data/system/app_icon/tactility.meshcontacts.svg @@ -0,0 +1 @@ + diff --git a/Data/system/app_icon/tactility.meshcontacts_mono.svg b/Data/system/app_icon/tactility.meshcontacts_mono.svg new file mode 100644 index 000000000..1d469dca6 --- /dev/null +++ b/Data/system/app_icon/tactility.meshcontacts_mono.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Data/system/app_icon/tactility.meshsettings.svg b/Data/system/app_icon/tactility.meshsettings.svg new file mode 100644 index 000000000..1ab624ea3 --- /dev/null +++ b/Data/system/app_icon/tactility.meshsettings.svg @@ -0,0 +1 @@ + diff --git a/Data/system/app_icon/tactility.meshsettings_mono.svg b/Data/system/app_icon/tactility.meshsettings_mono.svg new file mode 100644 index 000000000..9d3d0d9ee --- /dev/null +++ b/Data/system/app_icon/tactility.meshsettings_mono.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Data/system/app_icon/tactility.notes.svg b/Data/system/app_icon/tactility.notes.svg new file mode 100644 index 000000000..d92292569 --- /dev/null +++ b/Data/system/app_icon/tactility.notes.svg @@ -0,0 +1 @@ + diff --git a/Data/system/app_icon/tactility.notes_mono.svg b/Data/system/app_icon/tactility.notes_mono.svg new file mode 100644 index 000000000..17fee4ef1 --- /dev/null +++ b/Data/system/app_icon/tactility.notes_mono.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Data/system/app_icon/tactility.power.svg b/Data/system/app_icon/tactility.power.svg new file mode 100644 index 000000000..6e67c5cf3 --- /dev/null +++ b/Data/system/app_icon/tactility.power.svg @@ -0,0 +1 @@ + diff --git a/Data/system/app_icon/tactility.power_mono.svg b/Data/system/app_icon/tactility.power_mono.svg new file mode 100644 index 000000000..ad0214864 --- /dev/null +++ b/Data/system/app_icon/tactility.power_mono.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Data/system/app_icon/tactility.systeminfo.svg b/Data/system/app_icon/tactility.systeminfo.svg new file mode 100644 index 000000000..f3f01d7b9 --- /dev/null +++ b/Data/system/app_icon/tactility.systeminfo.svg @@ -0,0 +1 @@ + diff --git a/Data/system/app_icon/tactility.systeminfo_mono.svg b/Data/system/app_icon/tactility.systeminfo_mono.svg new file mode 100644 index 000000000..967be3326 --- /dev/null +++ b/Data/system/app_icon/tactility.systeminfo_mono.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Data/system/app_icon/tactility.terminal.svg b/Data/system/app_icon/tactility.terminal.svg new file mode 100644 index 000000000..274461e03 --- /dev/null +++ b/Data/system/app_icon/tactility.terminal.svg @@ -0,0 +1 @@ + diff --git a/Data/system/app_icon/tactility.terminal_mono.svg b/Data/system/app_icon/tactility.terminal_mono.svg new file mode 100644 index 000000000..bbd2b7d38 --- /dev/null +++ b/Data/system/app_icon/tactility.terminal_mono.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Data/system/app_icon/tactility.timedatesettings.svg b/Data/system/app_icon/tactility.timedatesettings.svg new file mode 100644 index 000000000..9e8142253 --- /dev/null +++ b/Data/system/app_icon/tactility.timedatesettings.svg @@ -0,0 +1 @@ + diff --git a/Data/system/app_icon/tactility.timedatesettings_mono.svg b/Data/system/app_icon/tactility.timedatesettings_mono.svg new file mode 100644 index 000000000..796c97aa9 --- /dev/null +++ b/Data/system/app_icon/tactility.timedatesettings_mono.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Data/system/app_icon/tactility.touchcalibration.svg b/Data/system/app_icon/tactility.touchcalibration.svg new file mode 100644 index 000000000..247c2709c --- /dev/null +++ b/Data/system/app_icon/tactility.touchcalibration.svg @@ -0,0 +1 @@ + diff --git a/Data/system/app_icon/tactility.touchcalibration_mono.svg b/Data/system/app_icon/tactility.touchcalibration_mono.svg new file mode 100644 index 000000000..49e9e73e8 --- /dev/null +++ b/Data/system/app_icon/tactility.touchcalibration_mono.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Data/system/app_icon/tactility.trackballsettings.svg b/Data/system/app_icon/tactility.trackballsettings.svg new file mode 100644 index 000000000..5363eeca3 --- /dev/null +++ b/Data/system/app_icon/tactility.trackballsettings.svg @@ -0,0 +1 @@ + diff --git a/Data/system/app_icon/tactility.trackballsettings_mono.svg b/Data/system/app_icon/tactility.trackballsettings_mono.svg new file mode 100644 index 000000000..d53d23b7b --- /dev/null +++ b/Data/system/app_icon/tactility.trackballsettings_mono.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Data/system/app_icon/tactility.usbsettings.svg b/Data/system/app_icon/tactility.usbsettings.svg new file mode 100644 index 000000000..6e7763e6f --- /dev/null +++ b/Data/system/app_icon/tactility.usbsettings.svg @@ -0,0 +1 @@ + diff --git a/Data/system/app_icon/tactility.usbsettings_mono.svg b/Data/system/app_icon/tactility.usbsettings_mono.svg new file mode 100644 index 000000000..b69cd3fb2 --- /dev/null +++ b/Data/system/app_icon/tactility.usbsettings_mono.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Data/system/app_icon/tactility.vibrationsettings.svg b/Data/system/app_icon/tactility.vibrationsettings.svg new file mode 100644 index 000000000..bfb0dcb03 --- /dev/null +++ b/Data/system/app_icon/tactility.vibrationsettings.svg @@ -0,0 +1 @@ + diff --git a/Data/system/app_icon/tactility.vibrationsettings_mono.svg b/Data/system/app_icon/tactility.vibrationsettings_mono.svg new file mode 100644 index 000000000..ebdcd0835 --- /dev/null +++ b/Data/system/app_icon/tactility.vibrationsettings_mono.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Data/system/app_icon/tactility.wifimanage.svg b/Data/system/app_icon/tactility.wifimanage.svg new file mode 100644 index 000000000..158146dcf --- /dev/null +++ b/Data/system/app_icon/tactility.wifimanage.svg @@ -0,0 +1 @@ + diff --git a/Data/system/app_icon/tactility.wifimanage_mono.svg b/Data/system/app_icon/tactility.wifimanage_mono.svg new file mode 100644 index 000000000..a0cace8cb --- /dev/null +++ b/Data/system/app_icon/tactility.wifimanage_mono.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Data/system/file_icon/app.svg b/Data/system/file_icon/app.svg new file mode 100644 index 000000000..5d48e2e1f --- /dev/null +++ b/Data/system/file_icon/app.svg @@ -0,0 +1 @@ + diff --git a/Data/system/file_icon/app_mono.svg b/Data/system/file_icon/app_mono.svg new file mode 100644 index 000000000..893b2f5ff --- /dev/null +++ b/Data/system/file_icon/app_mono.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Data/system/file_icon/executable.svg b/Data/system/file_icon/executable.svg new file mode 100644 index 000000000..95b79dd5a --- /dev/null +++ b/Data/system/file_icon/executable.svg @@ -0,0 +1 @@ + diff --git a/Data/system/file_icon/executable_mono.svg b/Data/system/file_icon/executable_mono.svg new file mode 100644 index 000000000..6584201da --- /dev/null +++ b/Data/system/file_icon/executable_mono.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Data/system/file_icon/file.svg b/Data/system/file_icon/file.svg new file mode 100644 index 000000000..05f1783b3 --- /dev/null +++ b/Data/system/file_icon/file.svg @@ -0,0 +1 @@ + diff --git a/Data/system/file_icon/file_mono.svg b/Data/system/file_icon/file_mono.svg new file mode 100644 index 000000000..215afa567 --- /dev/null +++ b/Data/system/file_icon/file_mono.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Data/system/file_icon/folder.svg b/Data/system/file_icon/folder.svg new file mode 100644 index 000000000..a947284df --- /dev/null +++ b/Data/system/file_icon/folder.svg @@ -0,0 +1 @@ + diff --git a/Data/system/file_icon/folder_mono.svg b/Data/system/file_icon/folder_mono.svg new file mode 100644 index 000000000..e25b30152 --- /dev/null +++ b/Data/system/file_icon/folder_mono.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Data/system/file_icon/image.svg b/Data/system/file_icon/image.svg new file mode 100644 index 000000000..153bd29d8 --- /dev/null +++ b/Data/system/file_icon/image.svg @@ -0,0 +1 @@ + diff --git a/Data/system/file_icon/image_mono.svg b/Data/system/file_icon/image_mono.svg new file mode 100644 index 000000000..9fafc7b3d --- /dev/null +++ b/Data/system/file_icon/image_mono.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Data/system/file_icon/link.svg b/Data/system/file_icon/link.svg new file mode 100644 index 000000000..0009b6897 --- /dev/null +++ b/Data/system/file_icon/link.svg @@ -0,0 +1 @@ + diff --git a/Data/system/file_icon/link_mono.svg b/Data/system/file_icon/link_mono.svg new file mode 100644 index 000000000..680c0944f --- /dev/null +++ b/Data/system/file_icon/link_mono.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Data/system/file_icon/sd_card.svg b/Data/system/file_icon/sd_card.svg new file mode 100644 index 000000000..c65cde433 --- /dev/null +++ b/Data/system/file_icon/sd_card.svg @@ -0,0 +1 @@ + diff --git a/Data/system/file_icon/sd_card_mono.svg b/Data/system/file_icon/sd_card_mono.svg new file mode 100644 index 000000000..f5afbd64e --- /dev/null +++ b/Data/system/file_icon/sd_card_mono.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Data/system/file_icon/text.svg b/Data/system/file_icon/text.svg new file mode 100644 index 000000000..ab01142d4 --- /dev/null +++ b/Data/system/file_icon/text.svg @@ -0,0 +1 @@ + diff --git a/Data/system/file_icon/text_mono.svg b/Data/system/file_icon/text_mono.svg new file mode 100644 index 000000000..58c0960b8 --- /dev/null +++ b/Data/system/file_icon/text_mono.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Data/system/file_icon/usb.svg b/Data/system/file_icon/usb.svg new file mode 100644 index 000000000..3202f4ed5 --- /dev/null +++ b/Data/system/file_icon/usb.svg @@ -0,0 +1 @@ + diff --git a/Data/system/file_icon/usb_mono.svg b/Data/system/file_icon/usb_mono.svg new file mode 100644 index 000000000..b69cd3fb2 --- /dev/null +++ b/Data/system/file_icon/usb_mono.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Libraries/nanosvg/CMakeLists.txt b/Libraries/nanosvg/CMakeLists.txt new file mode 100644 index 000000000..d1ddf7074 --- /dev/null +++ b/Libraries/nanosvg/CMakeLists.txt @@ -0,0 +1,10 @@ +cmake_minimum_required(VERSION 3.20) + +if (DEFINED ENV{ESP_IDF_VERSION}) + idf_component_register( + INCLUDE_DIRS "src/" + ) +else() + add_library(nanosvg INTERFACE) + target_include_directories(nanosvg INTERFACE "src/") +endif() diff --git a/Libraries/nanosvg/LICENSE.txt b/Libraries/nanosvg/LICENSE.txt new file mode 100644 index 000000000..6fde401cb --- /dev/null +++ b/Libraries/nanosvg/LICENSE.txt @@ -0,0 +1,18 @@ +Copyright (c) 2013-14 Mikko Mononen memon@inside.org + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not +claim that you wrote the original software. If you use this software +in a product, an acknowledgment in the product documentation would be +appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be +misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution. + diff --git a/Libraries/nanosvg/src/nanosvg.h b/Libraries/nanosvg/src/nanosvg.h new file mode 100644 index 000000000..291ecbf8a --- /dev/null +++ b/Libraries/nanosvg/src/nanosvg.h @@ -0,0 +1,3278 @@ +/* + * Copyright (c) 2013-14 Mikko Mononen memon@inside.org + * + * This software is provided 'as-is', without any express or implied + * warranty. In no event will the authors be held liable for any damages + * arising from the use of this software. + * + * Permission is granted to anyone to use this software for any purpose, + * including commercial applications, and to alter it and redistribute it + * freely, subject to the following restrictions: + * + * 1. The origin of this software must not be misrepresented; you must not + * claim that you wrote the original software. If you use this software + * in a product, an acknowledgment in the product documentation would be + * appreciated but is not required. + * 2. Altered source versions must be plainly marked as such, and must not be + * misrepresented as being the original software. + * 3. This notice may not be removed or altered from any source distribution. + * + * The SVG parser is based on Anti-Grain Geometry 2.4 SVG example + * Copyright (C) 2002-2004 Maxim Shemanarev (McSeem) (http://www.antigrain.com/) + * + * Arc calculation code based on canvg (https://code.google.com/p/canvg/) + * + * Bounding box calculation based on http://blog.hackers-cafe.net/2009/06/how-to-calculate-bezier-curves-bounding.html + * + */ + +#ifndef NANOSVG_H +#define NANOSVG_H + +#ifndef NANOSVG_CPLUSPLUS +#ifdef __cplusplus +extern "C" { +#endif +#endif + +// NanoSVG is a simple stupid single-header-file SVG parse. The output of the parser is a list of cubic bezier shapes. +// +// The library suits well for anything from rendering scalable icons in your editor application to prototyping a game. +// +// NanoSVG supports a wide range of SVG features, but something may be missing, feel free to create a pull request! +// +// The shapes in the SVG images are transformed by the viewBox and converted to specified units. +// That is, you should get the same looking data as your designed in your favorite app. +// +// NanoSVG can return the paths in few different units. For example if you want to render an image, you may choose +// to get the paths in pixels, or if you are feeding the data into a CNC-cutter, you may want to use millimeters. +// +// The units passed to NanoSVG should be one of: 'px', 'pt', 'pc' 'mm', 'cm', or 'in'. +// DPI (dots-per-inch) controls how the unit conversion is done. +// +// If you don't know or care about the units stuff, "px" and 96 should get you going. + + +/* Example Usage: + // Load SVG + NSVGimage* image; + image = nsvgParseFromFile("test.svg", "px", 96); + printf("size: %f x %f\n", image->width, image->height); + // Use... + for (NSVGshape *shape = image->shapes; shape != NULL; shape = shape->next) { + for (NSVGpath *path = shape->paths; path != NULL; path = path->next) { + for (int i = 0; i < path->npts-1; i += 3) { + float* p = &path->pts[i*2]; + drawCubicBez(p[0],p[1], p[2],p[3], p[4],p[5], p[6],p[7]); + } + } + } + // Delete + nsvgDelete(image); +*/ + +enum NSVGpaintType { + NSVG_PAINT_UNDEF = -1, + NSVG_PAINT_NONE = 0, + NSVG_PAINT_COLOR = 1, + NSVG_PAINT_LINEAR_GRADIENT = 2, + NSVG_PAINT_RADIAL_GRADIENT = 3 +}; + +enum NSVGspreadType { + NSVG_SPREAD_PAD = 0, + NSVG_SPREAD_REFLECT = 1, + NSVG_SPREAD_REPEAT = 2 +}; + +enum NSVGlineJoin { + NSVG_JOIN_MITER = 0, + NSVG_JOIN_ROUND = 1, + NSVG_JOIN_BEVEL = 2 +}; + +enum NSVGlineCap { + NSVG_CAP_BUTT = 0, + NSVG_CAP_ROUND = 1, + NSVG_CAP_SQUARE = 2 +}; + +enum NSVGfillRule { + NSVG_FILLRULE_NONZERO = 0, + NSVG_FILLRULE_EVENODD = 1 +}; + +enum NSVGflags { + NSVG_FLAGS_VISIBLE = 0x01 +}; + +enum NSVGpaintOrder { + NSVG_PAINT_FILL = 0x00, + NSVG_PAINT_MARKERS = 0x01, + NSVG_PAINT_STROKE = 0x02, +}; + +typedef struct NSVGgradientStop { + unsigned int color; + float offset; +} NSVGgradientStop; + +typedef struct NSVGgradient { + float xform[6]; + char spread; + float fx, fy; + int nstops; + NSVGgradientStop stops[1]; +} NSVGgradient; + +typedef struct NSVGpaint { + signed char type; + union { + unsigned int color; + NSVGgradient* gradient; + }; +} NSVGpaint; + +typedef struct NSVGpath +{ + float* pts; // Cubic bezier points: x0,y0, [cpx1,cpx1,cpx2,cpy2,x1,y1], ... + int npts; // Total number of bezier points. + char closed; // Flag indicating if shapes should be treated as closed. + float bounds[4]; // Tight bounding box of the shape [minx,miny,maxx,maxy]. + struct NSVGpath* next; // Pointer to next path, or NULL if last element. +} NSVGpath; + +typedef struct NSVGshape +{ + char id[64]; // Optional 'id' attr of the shape or its group + NSVGpaint fill; // Fill paint + NSVGpaint stroke; // Stroke paint + float opacity; // Opacity of the shape. + float strokeWidth; // Stroke width (scaled). + float strokeDashOffset; // Stroke dash offset (scaled). + float strokeDashArray[8]; // Stroke dash array (scaled). + char strokeDashCount; // Number of dash values in dash array. + char strokeLineJoin; // Stroke join type. + char strokeLineCap; // Stroke cap type. + float miterLimit; // Miter limit + char fillRule; // Fill rule, see NSVGfillRule. + unsigned char paintOrder; // Encoded paint order (3×2-bit fields) see NSVGpaintOrder + unsigned char flags; // Logical or of NSVG_FLAGS_* flags + float bounds[4]; // Tight bounding box of the shape [minx,miny,maxx,maxy]. + char fillGradient[64]; // Optional 'id' of fill gradient + char strokeGradient[64]; // Optional 'id' of stroke gradient + float xform[6]; // Root transformation for fill/stroke gradient + NSVGpath* paths; // Linked list of paths in the image. + struct NSVGshape* next; // Pointer to next shape, or NULL if last element. +} NSVGshape; + +typedef struct NSVGimage +{ + float width; // Width of the image. + float height; // Height of the image. + NSVGshape* shapes; // Linked list of shapes in the image. +} NSVGimage; + +// Parses SVG file from a file, returns SVG image as paths. +NSVGimage* nsvgParseFromFile(const char* filename, const char* units, float dpi); + +// Parses SVG file from a null terminated string, returns SVG image as paths. +// Important note: changes the string. +NSVGimage* nsvgParse(char* input, const char* units, float dpi); + +// Duplicates a path. +NSVGpath* nsvgDuplicatePath(NSVGpath* p); + +// Deletes an image. +void nsvgDelete(NSVGimage* image); + +#ifndef NANOSVG_CPLUSPLUS +#ifdef __cplusplus +} +#endif +#endif + +#ifdef NANOSVG_IMPLEMENTATION + +#include +#include +#include +#include + +#define NSVG_PI (3.14159265358979323846264338327f) +#define NSVG_KAPPA90 (0.5522847493f) // Length proportional to radius of a cubic bezier handle for 90deg arcs. + +#define NSVG_ALIGN_MIN 0 +#define NSVG_ALIGN_MID 1 +#define NSVG_ALIGN_MAX 2 +#define NSVG_ALIGN_NONE 0 +#define NSVG_ALIGN_MEET 1 +#define NSVG_ALIGN_SLICE 2 + +#define NSVG_NOTUSED(v) do { (void)(1 ? (void)0 : ( (void)(v) ) ); } while(0) +#define NSVG_RGB(r, g, b) (((unsigned int)r) | ((unsigned int)g << 8) | ((unsigned int)b << 16)) + +#ifdef _MSC_VER + #pragma warning (disable: 4996) // Switch off security warnings + #pragma warning (disable: 4100) // Switch off unreferenced formal parameter warnings + #ifdef __cplusplus + #define NSVG_INLINE inline + #else + #define NSVG_INLINE + #endif +#else + #define NSVG_INLINE inline +#endif + + +static int nsvg__isspace(char c) +{ + return strchr(" \t\n\v\f\r", c) != 0; +} + +static int nsvg__isdigit(char c) +{ + return c >= '0' && c <= '9'; +} + +static NSVG_INLINE float nsvg__minf(float a, float b) { return a < b ? a : b; } +static NSVG_INLINE float nsvg__maxf(float a, float b) { return a > b ? a : b; } + + +// Simple XML parser + +#define NSVG_XML_TAG 1 +#define NSVG_XML_CONTENT 2 +#define NSVG_XML_MAX_ATTRIBS 256 + +static void nsvg__parseContent(char* s, + void (*contentCb)(void* ud, const char* s), + void* ud) +{ + // Trim start white spaces + while (*s && nsvg__isspace(*s)) s++; + if (!*s) return; + + if (contentCb) + (*contentCb)(ud, s); +} + +static void nsvg__parseElement(char* s, + void (*startelCb)(void* ud, const char* el, const char** attr), + void (*endelCb)(void* ud, const char* el), + void* ud) +{ + const char* attr[NSVG_XML_MAX_ATTRIBS]; + int nattr = 0; + char* name; + int start = 0; + int end = 0; + char quote; + + // Skip white space after the '<' + while (*s && nsvg__isspace(*s)) s++; + + // Check if the tag is end tag + if (*s == '/') { + s++; + end = 1; + } else { + start = 1; + } + + // Skip comments, data and preprocessor stuff. + if (!*s || *s == '?' || *s == '!') + return; + + // Get tag name + name = s; + while (*s && !nsvg__isspace(*s)) s++; + if (*s) { *s++ = '\0'; } + + // Get attribs + while (!end && *s && nattr < NSVG_XML_MAX_ATTRIBS-3) { + char* name = NULL; + char* value = NULL; + + // Skip white space before the attrib name + while (*s && nsvg__isspace(*s)) s++; + if (!*s) break; + if (*s == '/') { + end = 1; + break; + } + name = s; + // Find end of the attrib name. + while (*s && !nsvg__isspace(*s) && *s != '=') s++; + if (*s) { *s++ = '\0'; } + // Skip until the beginning of the value. + while (*s && *s != '\"' && *s != '\'') s++; + if (!*s) break; + quote = *s; + s++; + // Store value and find the end of it. + value = s; + while (*s && *s != quote) s++; + if (*s) { *s++ = '\0'; } + + // Store only well formed attributes + if (name && value) { + attr[nattr++] = name; + attr[nattr++] = value; + } + } + + // List terminator + attr[nattr++] = 0; + attr[nattr++] = 0; + + // Call callbacks. + if (start && startelCb) + (*startelCb)(ud, name, attr); + if (end && endelCb) + (*endelCb)(ud, name); +} + +int nsvg__parseXML(char* input, + void (*startelCb)(void* ud, const char* el, const char** attr), + void (*endelCb)(void* ud, const char* el), + void (*contentCb)(void* ud, const char* s), + void* ud) +{ + char* s = input; + char* mark = s; + int state = NSVG_XML_CONTENT; + while (*s) { + if (*s == '<' && state == NSVG_XML_CONTENT) { + // Start of a tag + *s++ = '\0'; + nsvg__parseContent(mark, contentCb, ud); + mark = s; + state = NSVG_XML_TAG; + } else if (*s == '>' && state == NSVG_XML_TAG) { + // Start of a content or new tag. + *s++ = '\0'; + nsvg__parseElement(mark, startelCb, endelCb, ud); + mark = s; + state = NSVG_XML_CONTENT; + } else { + s++; + } + } + + return 1; +} + + +/* Simple SVG parser. */ + +#define NSVG_MAX_ATTR 128 + +enum NSVGgradientUnits { + NSVG_USER_SPACE = 0, + NSVG_OBJECT_SPACE = 1 +}; + +#define NSVG_MAX_DASHES 8 +#define NSVG_MAX_CLASSES 32 + +enum NSVGunits { + NSVG_UNITS_USER, + NSVG_UNITS_PX, + NSVG_UNITS_PT, + NSVG_UNITS_PC, + NSVG_UNITS_MM, + NSVG_UNITS_CM, + NSVG_UNITS_IN, + NSVG_UNITS_PERCENT, + NSVG_UNITS_EM, + NSVG_UNITS_EX +}; + +typedef struct NSVGcoordinate { + float value; + int units; +} NSVGcoordinate; + +typedef struct NSVGlinearData { + NSVGcoordinate x1, y1, x2, y2; +} NSVGlinearData; + +typedef struct NSVGradialData { + NSVGcoordinate cx, cy, r, fx, fy; +} NSVGradialData; + +typedef struct NSVGgradientData +{ + char id[64]; + char ref[64]; + signed char type; + union { + NSVGlinearData linear; + NSVGradialData radial; + }; + char spread; + char units; + float xform[6]; + int nstops; + NSVGgradientStop* stops; + struct NSVGgradientData* next; +} NSVGgradientData; + +typedef struct NSVGattrib +{ + char id[64]; + float xform[6]; + unsigned int fillColor; + unsigned int strokeColor; + float opacity; + float fillOpacity; + float strokeOpacity; + char fillGradient[64]; + char strokeGradient[64]; + float strokeWidth; + float strokeDashOffset; + float strokeDashArray[NSVG_MAX_DASHES]; + int strokeDashCount; + char strokeLineJoin; + char strokeLineCap; + float miterLimit; + char fillRule; + float fontSize; + unsigned int stopColor; + float stopOpacity; + float stopOffset; + char hasFill; + char hasStroke; + char visible; + unsigned char paintOrder; +} NSVGattrib; + +typedef struct NSVGstyleDeclaration +{ + char* className; + char* propertiesText; + struct NSVGstyleDeclaration* next; +} NSVGstyleDeclaration; + +typedef struct NSVGparser +{ + NSVGattrib attr[NSVG_MAX_ATTR]; + int attrHead; + float* pts; + int npts; + int cpts; + NSVGpath* plist; + NSVGimage* image; + NSVGstyleDeclaration* styles; + NSVGgradientData* gradients; + NSVGshape* shapesTail; + float viewMinx, viewMiny, viewWidth, viewHeight; + int alignX, alignY, alignType; + float dpi; + char pathFlag; + char defsFlag; + char styleFlag; +} NSVGparser; + +static void nsvg__xformIdentity(float* t) +{ + t[0] = 1.0f; t[1] = 0.0f; + t[2] = 0.0f; t[3] = 1.0f; + t[4] = 0.0f; t[5] = 0.0f; +} + +static void nsvg__xformSetTranslation(float* t, float tx, float ty) +{ + t[0] = 1.0f; t[1] = 0.0f; + t[2] = 0.0f; t[3] = 1.0f; + t[4] = tx; t[5] = ty; +} + +static void nsvg__xformSetScale(float* t, float sx, float sy) +{ + t[0] = sx; t[1] = 0.0f; + t[2] = 0.0f; t[3] = sy; + t[4] = 0.0f; t[5] = 0.0f; +} + +static void nsvg__xformSetSkewX(float* t, float a) +{ + t[0] = 1.0f; t[1] = 0.0f; + t[2] = tanf(a); t[3] = 1.0f; + t[4] = 0.0f; t[5] = 0.0f; +} + +static void nsvg__xformSetSkewY(float* t, float a) +{ + t[0] = 1.0f; t[1] = tanf(a); + t[2] = 0.0f; t[3] = 1.0f; + t[4] = 0.0f; t[5] = 0.0f; +} + +static void nsvg__xformSetRotation(float* t, float a) +{ + float cs = cosf(a), sn = sinf(a); + t[0] = cs; t[1] = sn; + t[2] = -sn; t[3] = cs; + t[4] = 0.0f; t[5] = 0.0f; +} + +static void nsvg__xformMultiply(float* t, float* s) +{ + float t0 = t[0] * s[0] + t[1] * s[2]; + float t2 = t[2] * s[0] + t[3] * s[2]; + float t4 = t[4] * s[0] + t[5] * s[2] + s[4]; + t[1] = t[0] * s[1] + t[1] * s[3]; + t[3] = t[2] * s[1] + t[3] * s[3]; + t[5] = t[4] * s[1] + t[5] * s[3] + s[5]; + t[0] = t0; + t[2] = t2; + t[4] = t4; +} + +static void nsvg__xformInverse(float* inv, float* t) +{ + double invdet, det = (double)t[0] * t[3] - (double)t[2] * t[1]; + if (det > -1e-6 && det < 1e-6) { + nsvg__xformIdentity(t); + return; + } + invdet = 1.0 / det; + inv[0] = (float)(t[3] * invdet); + inv[2] = (float)(-t[2] * invdet); + inv[4] = (float)(((double)t[2] * t[5] - (double)t[3] * t[4]) * invdet); + inv[1] = (float)(-t[1] * invdet); + inv[3] = (float)(t[0] * invdet); + inv[5] = (float)(((double)t[1] * t[4] - (double)t[0] * t[5]) * invdet); +} + +static void nsvg__xformPremultiply(float* t, float* s) +{ + float s2[6]; + memcpy(s2, s, sizeof(float)*6); + nsvg__xformMultiply(s2, t); + memcpy(t, s2, sizeof(float)*6); +} + +static void nsvg__xformPoint(float* dx, float* dy, float x, float y, float* t) +{ + *dx = x*t[0] + y*t[2] + t[4]; + *dy = x*t[1] + y*t[3] + t[5]; +} + +static void nsvg__xformVec(float* dx, float* dy, float x, float y, float* t) +{ + *dx = x*t[0] + y*t[2]; + *dy = x*t[1] + y*t[3]; +} + +#define NSVG_EPSILON (1e-12) + +static int nsvg__ptInBounds(float* pt, float* bounds) +{ + return pt[0] >= bounds[0] && pt[0] <= bounds[2] && pt[1] >= bounds[1] && pt[1] <= bounds[3]; +} + + +static double nsvg__evalBezier(double t, double p0, double p1, double p2, double p3) +{ + double it = 1.0-t; + return it*it*it*p0 + 3.0*it*it*t*p1 + 3.0*it*t*t*p2 + t*t*t*p3; +} + +static void nsvg__curveBounds(float* bounds, float* curve) +{ + int i, j, count; + double roots[2], a, b, c, b2ac, t, v; + float* v0 = &curve[0]; + float* v1 = &curve[2]; + float* v2 = &curve[4]; + float* v3 = &curve[6]; + + // Start the bounding box by end points + bounds[0] = nsvg__minf(v0[0], v3[0]); + bounds[1] = nsvg__minf(v0[1], v3[1]); + bounds[2] = nsvg__maxf(v0[0], v3[0]); + bounds[3] = nsvg__maxf(v0[1], v3[1]); + + // Bezier curve fits inside the convex hull of it's control points. + // If control points are inside the bounds, we're done. + if (nsvg__ptInBounds(v1, bounds) && nsvg__ptInBounds(v2, bounds)) + return; + + // Add bezier curve inflection points in X and Y. + for (i = 0; i < 2; i++) { + a = -3.0 * v0[i] + 9.0 * v1[i] - 9.0 * v2[i] + 3.0 * v3[i]; + b = 6.0 * v0[i] - 12.0 * v1[i] + 6.0 * v2[i]; + c = 3.0 * v1[i] - 3.0 * v0[i]; + count = 0; + if (fabs(a) < NSVG_EPSILON) { + if (fabs(b) > NSVG_EPSILON) { + t = -c / b; + if (t > NSVG_EPSILON && t < 1.0-NSVG_EPSILON) + roots[count++] = t; + } + } else { + b2ac = b*b - 4.0*c*a; + if (b2ac > NSVG_EPSILON) { + t = (-b + sqrt(b2ac)) / (2.0 * a); + if (t > NSVG_EPSILON && t < 1.0-NSVG_EPSILON) + roots[count++] = t; + t = (-b - sqrt(b2ac)) / (2.0 * a); + if (t > NSVG_EPSILON && t < 1.0-NSVG_EPSILON) + roots[count++] = t; + } + } + for (j = 0; j < count; j++) { + v = nsvg__evalBezier(roots[j], v0[i], v1[i], v2[i], v3[i]); + bounds[0+i] = nsvg__minf(bounds[0+i], (float)v); + bounds[2+i] = nsvg__maxf(bounds[2+i], (float)v); + } + } +} + +static unsigned char nsvg__encodePaintOrder(enum NSVGpaintOrder a, enum NSVGpaintOrder b, enum NSVGpaintOrder c) { + return (a & 0x03) | ((b & 0x03) << 2) | ((c & 0x03) << 4); +} + +static NSVGparser* nsvg__createParser(void) +{ + NSVGparser* p; + p = (NSVGparser*)malloc(sizeof(NSVGparser)); + if (p == NULL) goto error; + memset(p, 0, sizeof(NSVGparser)); + + p->image = (NSVGimage*)malloc(sizeof(NSVGimage)); + if (p->image == NULL) goto error; + memset(p->image, 0, sizeof(NSVGimage)); + + // Init style + nsvg__xformIdentity(p->attr[0].xform); + memset(p->attr[0].id, 0, sizeof p->attr[0].id); + p->attr[0].fillColor = NSVG_RGB(0,0,0); + p->attr[0].strokeColor = NSVG_RGB(0,0,0); + p->attr[0].opacity = 1; + p->attr[0].fillOpacity = 1; + p->attr[0].strokeOpacity = 1; + p->attr[0].stopOpacity = 1; + p->attr[0].strokeWidth = 1; + p->attr[0].strokeLineJoin = NSVG_JOIN_MITER; + p->attr[0].strokeLineCap = NSVG_CAP_BUTT; + p->attr[0].miterLimit = 4; + p->attr[0].fillRule = NSVG_FILLRULE_NONZERO; + p->attr[0].hasFill = 1; + p->attr[0].visible = 1; + p->attr[0].paintOrder = nsvg__encodePaintOrder(NSVG_PAINT_FILL, NSVG_PAINT_STROKE, NSVG_PAINT_MARKERS); + + return p; + +error: + if (p) { + if (p->image) free(p->image); + free(p); + } + return NULL; +} +static void nsvg__deleteStyles(NSVGstyleDeclaration* style) { + while (style) { + NSVGstyleDeclaration* next = style->next; + free(style->className); + free(style->propertiesText); + free(style); + style = next; + } +} + +static void nsvg__deletePaths(NSVGpath* path) +{ + while (path) { + NSVGpath *next = path->next; + if (path->pts != NULL) + free(path->pts); + free(path); + path = next; + } +} + +static void nsvg__deletePaint(NSVGpaint* paint) +{ + if (paint->type == NSVG_PAINT_LINEAR_GRADIENT || paint->type == NSVG_PAINT_RADIAL_GRADIENT) + free(paint->gradient); +} + +static void nsvg__deleteGradientData(NSVGgradientData* grad) +{ + NSVGgradientData* next; + while (grad != NULL) { + next = grad->next; + free(grad->stops); + free(grad); + grad = next; + } +} + +static void nsvg__deleteParser(NSVGparser* p) +{ + if (p != NULL) { + nsvg__deleteStyles(p->styles); + nsvg__deletePaths(p->plist); + nsvg__deleteGradientData(p->gradients); + nsvgDelete(p->image); + free(p->pts); + free(p); + } +} + +static void nsvg__resetPath(NSVGparser* p) +{ + p->npts = 0; +} + +static void nsvg__addPoint(NSVGparser* p, float x, float y) +{ + if (p->npts+1 > p->cpts) { + p->cpts = p->cpts ? p->cpts*2 : 8; + p->pts = (float*)realloc(p->pts, p->cpts*2*sizeof(float)); + if (!p->pts) return; + } + p->pts[p->npts*2+0] = x; + p->pts[p->npts*2+1] = y; + p->npts++; +} + +static void nsvg__moveTo(NSVGparser* p, float x, float y) +{ + if (p->npts > 0) { + p->pts[(p->npts-1)*2+0] = x; + p->pts[(p->npts-1)*2+1] = y; + } else { + nsvg__addPoint(p, x, y); + } +} + +static void nsvg__lineTo(NSVGparser* p, float x, float y) +{ + float px,py, dx,dy; + if (p->npts > 0) { + px = p->pts[(p->npts-1)*2+0]; + py = p->pts[(p->npts-1)*2+1]; + dx = x - px; + dy = y - py; + nsvg__addPoint(p, px + dx/3.0f, py + dy/3.0f); + nsvg__addPoint(p, x - dx/3.0f, y - dy/3.0f); + nsvg__addPoint(p, x, y); + } +} + +static void nsvg__cubicBezTo(NSVGparser* p, float cpx1, float cpy1, float cpx2, float cpy2, float x, float y) +{ + if (p->npts > 0) { + nsvg__addPoint(p, cpx1, cpy1); + nsvg__addPoint(p, cpx2, cpy2); + nsvg__addPoint(p, x, y); + } +} + +static NSVGattrib* nsvg__getAttr(NSVGparser* p) +{ + return &p->attr[p->attrHead]; +} + +static void nsvg__pushAttr(NSVGparser* p) +{ + if (p->attrHead < NSVG_MAX_ATTR-1) { + p->attrHead++; + memcpy(&p->attr[p->attrHead], &p->attr[p->attrHead-1], sizeof(NSVGattrib)); + } +} + +static void nsvg__popAttr(NSVGparser* p) +{ + if (p->attrHead > 0) + p->attrHead--; +} + +static float nsvg__actualOrigX(NSVGparser* p) +{ + return p->viewMinx; +} + +static float nsvg__actualOrigY(NSVGparser* p) +{ + return p->viewMiny; +} + +static float nsvg__actualWidth(NSVGparser* p) +{ + return p->viewWidth; +} + +static float nsvg__actualHeight(NSVGparser* p) +{ + return p->viewHeight; +} + +static float nsvg__actualLength(NSVGparser* p) +{ + float w = nsvg__actualWidth(p), h = nsvg__actualHeight(p); + return sqrtf(w*w + h*h) / sqrtf(2.0f); +} + +static float nsvg__convertToPixels(NSVGparser* p, NSVGcoordinate c, float orig, float length) +{ + NSVGattrib* attr = nsvg__getAttr(p); + switch (c.units) { + case NSVG_UNITS_USER: return c.value; + case NSVG_UNITS_PX: return c.value; + case NSVG_UNITS_PT: return c.value / 72.0f * p->dpi; + case NSVG_UNITS_PC: return c.value / 6.0f * p->dpi; + case NSVG_UNITS_MM: return c.value / 25.4f * p->dpi; + case NSVG_UNITS_CM: return c.value / 2.54f * p->dpi; + case NSVG_UNITS_IN: return c.value * p->dpi; + case NSVG_UNITS_EM: return c.value * attr->fontSize; + case NSVG_UNITS_EX: return c.value * attr->fontSize * 0.52f; // x-height of Helvetica. + case NSVG_UNITS_PERCENT: return orig + c.value / 100.0f * length; + default: return c.value; + } + return c.value; +} + +static NSVGgradientData* nsvg__findGradientData(NSVGparser* p, const char* id) +{ + NSVGgradientData* grad = p->gradients; + if (id == NULL || *id == '\0') + return NULL; + while (grad != NULL) { + if (strcmp(grad->id, id) == 0) + return grad; + grad = grad->next; + } + return NULL; +} + +static NSVGgradient* nsvg__createGradient(NSVGparser* p, const char* id, const float* localBounds, float *xform, signed char* paintType) +{ + NSVGgradientData* data = NULL; + NSVGgradientData* ref = NULL; + NSVGgradientStop* stops = NULL; + NSVGgradient* grad; + float ox, oy, sw, sh, sl; + int nstops = 0; + int refIter; + + data = nsvg__findGradientData(p, id); + if (data == NULL) return NULL; + + // TODO: use ref to fill in all unset values too. + ref = data; + refIter = 0; + while (ref != NULL) { + NSVGgradientData* nextRef = NULL; + if (stops == NULL && ref->stops != NULL) { + stops = ref->stops; + nstops = ref->nstops; + break; + } + nextRef = nsvg__findGradientData(p, ref->ref); + if (nextRef == ref) break; // prevent infite loops on malformed data + ref = nextRef; + refIter++; + if (refIter > 32) break; // prevent infite loops on malformed data + } + if (stops == NULL) return NULL; + + grad = (NSVGgradient*)malloc(sizeof(NSVGgradient) + sizeof(NSVGgradientStop)*(nstops-1)); + if (grad == NULL) return NULL; + + // The shape width and height. + if (data->units == NSVG_OBJECT_SPACE) { + ox = localBounds[0]; + oy = localBounds[1]; + sw = localBounds[2] - localBounds[0]; + sh = localBounds[3] - localBounds[1]; + } else { + ox = nsvg__actualOrigX(p); + oy = nsvg__actualOrigY(p); + sw = nsvg__actualWidth(p); + sh = nsvg__actualHeight(p); + } + sl = sqrtf(sw*sw + sh*sh) / sqrtf(2.0f); + + if (data->type == NSVG_PAINT_LINEAR_GRADIENT) { + float x1, y1, x2, y2, dx, dy; + x1 = nsvg__convertToPixels(p, data->linear.x1, ox, sw); + y1 = nsvg__convertToPixels(p, data->linear.y1, oy, sh); + x2 = nsvg__convertToPixels(p, data->linear.x2, ox, sw); + y2 = nsvg__convertToPixels(p, data->linear.y2, oy, sh); + // Calculate transform aligned to the line + dx = x2 - x1; + dy = y2 - y1; + grad->xform[0] = dy; grad->xform[1] = -dx; + grad->xform[2] = dx; grad->xform[3] = dy; + grad->xform[4] = x1; grad->xform[5] = y1; + } else { + float cx, cy, fx, fy, r; + cx = nsvg__convertToPixels(p, data->radial.cx, ox, sw); + cy = nsvg__convertToPixels(p, data->radial.cy, oy, sh); + fx = nsvg__convertToPixels(p, data->radial.fx, ox, sw); + fy = nsvg__convertToPixels(p, data->radial.fy, oy, sh); + r = nsvg__convertToPixels(p, data->radial.r, 0, sl); + // Calculate transform aligned to the circle + grad->xform[0] = r; grad->xform[1] = 0; + grad->xform[2] = 0; grad->xform[3] = r; + grad->xform[4] = cx; grad->xform[5] = cy; + grad->fx = fx / r; + grad->fy = fy / r; + } + + nsvg__xformMultiply(grad->xform, data->xform); + nsvg__xformMultiply(grad->xform, xform); + + grad->spread = data->spread; + memcpy(grad->stops, stops, nstops*sizeof(NSVGgradientStop)); + grad->nstops = nstops; + + *paintType = data->type; + + return grad; +} + +static float nsvg__getAverageScale(float* t) +{ + float sx = sqrtf(t[0]*t[0] + t[2]*t[2]); + float sy = sqrtf(t[1]*t[1] + t[3]*t[3]); + return (sx + sy) * 0.5f; +} + +static void nsvg__getLocalBounds(float* bounds, NSVGshape *shape, float* xform) +{ + NSVGpath* path; + float curve[4*2], curveBounds[4]; + int i, first = 1; + for (path = shape->paths; path != NULL; path = path->next) { + nsvg__xformPoint(&curve[0], &curve[1], path->pts[0], path->pts[1], xform); + for (i = 0; i < path->npts-1; i += 3) { + nsvg__xformPoint(&curve[2], &curve[3], path->pts[(i+1)*2], path->pts[(i+1)*2+1], xform); + nsvg__xformPoint(&curve[4], &curve[5], path->pts[(i+2)*2], path->pts[(i+2)*2+1], xform); + nsvg__xformPoint(&curve[6], &curve[7], path->pts[(i+3)*2], path->pts[(i+3)*2+1], xform); + nsvg__curveBounds(curveBounds, curve); + if (first) { + bounds[0] = curveBounds[0]; + bounds[1] = curveBounds[1]; + bounds[2] = curveBounds[2]; + bounds[3] = curveBounds[3]; + first = 0; + } else { + bounds[0] = nsvg__minf(bounds[0], curveBounds[0]); + bounds[1] = nsvg__minf(bounds[1], curveBounds[1]); + bounds[2] = nsvg__maxf(bounds[2], curveBounds[2]); + bounds[3] = nsvg__maxf(bounds[3], curveBounds[3]); + } + curve[0] = curve[6]; + curve[1] = curve[7]; + } + } +} + +static void nsvg__addShape(NSVGparser* p) +{ + NSVGattrib* attr = nsvg__getAttr(p); + float scale = 1.0f; + NSVGshape* shape; + NSVGpath* path; + int i; + + if (p->plist == NULL) + return; + + shape = (NSVGshape*)malloc(sizeof(NSVGshape)); + if (shape == NULL) goto error; + memset(shape, 0, sizeof(NSVGshape)); + + memcpy(shape->id, attr->id, sizeof shape->id); + memcpy(shape->fillGradient, attr->fillGradient, sizeof shape->fillGradient); + memcpy(shape->strokeGradient, attr->strokeGradient, sizeof shape->strokeGradient); + memcpy(shape->xform, attr->xform, sizeof shape->xform); + scale = nsvg__getAverageScale(attr->xform); + shape->strokeWidth = attr->strokeWidth * scale; + shape->strokeDashOffset = attr->strokeDashOffset * scale; + shape->strokeDashCount = (char)attr->strokeDashCount; + for (i = 0; i < attr->strokeDashCount; i++) + shape->strokeDashArray[i] = attr->strokeDashArray[i] * scale; + shape->strokeLineJoin = attr->strokeLineJoin; + shape->strokeLineCap = attr->strokeLineCap; + shape->miterLimit = attr->miterLimit; + shape->fillRule = attr->fillRule; + shape->opacity = attr->opacity; + shape->paintOrder = attr->paintOrder; + + shape->paths = p->plist; + p->plist = NULL; + + // Calculate shape bounds + shape->bounds[0] = shape->paths->bounds[0]; + shape->bounds[1] = shape->paths->bounds[1]; + shape->bounds[2] = shape->paths->bounds[2]; + shape->bounds[3] = shape->paths->bounds[3]; + for (path = shape->paths->next; path != NULL; path = path->next) { + shape->bounds[0] = nsvg__minf(shape->bounds[0], path->bounds[0]); + shape->bounds[1] = nsvg__minf(shape->bounds[1], path->bounds[1]); + shape->bounds[2] = nsvg__maxf(shape->bounds[2], path->bounds[2]); + shape->bounds[3] = nsvg__maxf(shape->bounds[3], path->bounds[3]); + } + + // Set fill + if (attr->hasFill == 0) { + shape->fill.type = NSVG_PAINT_NONE; + } else if (attr->hasFill == 1) { + shape->fill.type = NSVG_PAINT_COLOR; + shape->fill.color = attr->fillColor; + shape->fill.color |= (unsigned int)(attr->fillOpacity*255) << 24; + } else if (attr->hasFill == 2) { + shape->fill.type = NSVG_PAINT_UNDEF; + } + + // Set stroke + if (attr->hasStroke == 0) { + shape->stroke.type = NSVG_PAINT_NONE; + } else if (attr->hasStroke == 1) { + shape->stroke.type = NSVG_PAINT_COLOR; + shape->stroke.color = attr->strokeColor; + shape->stroke.color |= (unsigned int)(attr->strokeOpacity*255) << 24; + } else if (attr->hasStroke == 2) { + shape->stroke.type = NSVG_PAINT_UNDEF; + } + + // Set flags + shape->flags = (attr->visible ? NSVG_FLAGS_VISIBLE : 0x00); + + // Add to tail + if (p->image->shapes == NULL) + p->image->shapes = shape; + else + p->shapesTail->next = shape; + p->shapesTail = shape; + + return; + +error: + if (shape) free(shape); +} + +static void nsvg__addPath(NSVGparser* p, char closed) +{ + NSVGattrib* attr = nsvg__getAttr(p); + NSVGpath* path = NULL; + float bounds[4]; + float* curve; + int i; + + if (p->npts < 4) + return; + + if (closed) + nsvg__lineTo(p, p->pts[0], p->pts[1]); + + // Expect 1 + N*3 points (N = number of cubic bezier segments). + if ((p->npts % 3) != 1) + return; + + path = (NSVGpath*)malloc(sizeof(NSVGpath)); + if (path == NULL) goto error; + memset(path, 0, sizeof(NSVGpath)); + + path->pts = (float*)malloc(p->npts*2*sizeof(float)); + if (path->pts == NULL) goto error; + path->closed = closed; + path->npts = p->npts; + + // Transform path. + for (i = 0; i < p->npts; ++i) + nsvg__xformPoint(&path->pts[i*2], &path->pts[i*2+1], p->pts[i*2], p->pts[i*2+1], attr->xform); + + // Find bounds + for (i = 0; i < path->npts-1; i += 3) { + curve = &path->pts[i*2]; + nsvg__curveBounds(bounds, curve); + if (i == 0) { + path->bounds[0] = bounds[0]; + path->bounds[1] = bounds[1]; + path->bounds[2] = bounds[2]; + path->bounds[3] = bounds[3]; + } else { + path->bounds[0] = nsvg__minf(path->bounds[0], bounds[0]); + path->bounds[1] = nsvg__minf(path->bounds[1], bounds[1]); + path->bounds[2] = nsvg__maxf(path->bounds[2], bounds[2]); + path->bounds[3] = nsvg__maxf(path->bounds[3], bounds[3]); + } + } + + path->next = p->plist; + p->plist = path; + + return; + +error: + if (path != NULL) { + if (path->pts != NULL) free(path->pts); + free(path); + } +} + +// We roll our own string to float because the std library one uses locale and messes things up. +static double nsvg__atof(const char* s) +{ + char* cur = (char*)s; + char* end = NULL; + double res = 0.0, sign = 1.0; + long long intPart = 0, fracPart = 0; + char hasIntPart = 0, hasFracPart = 0; + + // Parse optional sign + if (*cur == '+') { + cur++; + } else if (*cur == '-') { + sign = -1; + cur++; + } + + // Parse integer part + if (nsvg__isdigit(*cur)) { + // Parse digit sequence + intPart = strtoll(cur, &end, 10); + if (cur != end) { + res = (double)intPart; + hasIntPart = 1; + cur = end; + } + } + + // Parse fractional part. + if (*cur == '.') { + cur++; // Skip '.' + if (nsvg__isdigit(*cur)) { + // Parse digit sequence + fracPart = strtoll(cur, &end, 10); + if (cur != end) { + res += (double)fracPart / pow(10.0, (double)(end - cur)); + hasFracPart = 1; + cur = end; + } + } + } + + // A valid number should have integer or fractional part. + if (!hasIntPart && !hasFracPart) + return 0.0; + + // Parse optional exponent + if (*cur == 'e' || *cur == 'E') { + long expPart = 0; + cur++; // skip 'E' + expPart = strtol(cur, &end, 10); // Parse digit sequence with sign + if (cur != end) { + res *= pow(10.0, (double)expPart); + } + } + + return res * sign; +} + + +static const char* nsvg__parseNumber(const char* s, char* it, const int size) +{ + const int last = size-1; + int i = 0; + + // sign + if (*s == '-' || *s == '+') { + if (i < last) it[i++] = *s; + s++; + } + // integer part + while (*s && nsvg__isdigit(*s)) { + if (i < last) it[i++] = *s; + s++; + } + if (*s == '.') { + // decimal point + if (i < last) it[i++] = *s; + s++; + // fraction part + while (*s && nsvg__isdigit(*s)) { + if (i < last) it[i++] = *s; + s++; + } + } + // exponent + if ((*s == 'e' || *s == 'E') && (s[1] != 'm' && s[1] != 'x')) { + if (i < last) it[i++] = *s; + s++; + if (*s == '-' || *s == '+') { + if (i < last) it[i++] = *s; + s++; + } + while (*s && nsvg__isdigit(*s)) { + if (i < last) it[i++] = *s; + s++; + } + } + it[i] = '\0'; + + return s; +} + +static const char* nsvg__getNextPathItemWhenArcFlag(const char* s, char* it) +{ + it[0] = '\0'; + while (*s && (nsvg__isspace(*s) || *s == ',')) s++; + if (!*s) return s; + if (*s == '0' || *s == '1') { + it[0] = *s++; + it[1] = '\0'; + return s; + } + return s; +} + +static const char* nsvg__getNextPathItem(const char* s, char* it) +{ + it[0] = '\0'; + // Skip white spaces and commas + while (*s && (nsvg__isspace(*s) || *s == ',')) s++; + if (!*s) return s; + if (*s == '-' || *s == '+' || *s == '.' || nsvg__isdigit(*s)) { + s = nsvg__parseNumber(s, it, 64); + } else { + // Parse command + it[0] = *s++; + it[1] = '\0'; + return s; + } + + return s; +} + +static unsigned int nsvg__parseColorHex(const char* str) +{ + unsigned int r=0, g=0, b=0; + if (sscanf(str, "#%2x%2x%2x", &r, &g, &b) == 3 ) // 2 digit hex + return NSVG_RGB(r, g, b); + if (sscanf(str, "#%1x%1x%1x", &r, &g, &b) == 3 ) // 1 digit hex, e.g. #abc -> 0xccbbaa + return NSVG_RGB(r*17, g*17, b*17); // same effect as (r<<4|r), (g<<4|g), .. + return NSVG_RGB(128, 128, 128); +} + +// Parse rgb color. The pointer 'str' must point at "rgb(" (4+ characters). +// This function returns gray (rgb(128, 128, 128) == '#808080') on parse errors +// for backwards compatibility. Note: other image viewers return black instead. + +static unsigned int nsvg__parseColorRGB(const char* str) +{ + int i; + unsigned int rgbi[3]; + float rgbf[3]; + // try decimal integers first + if (sscanf(str, "rgb(%u, %u, %u)", &rgbi[0], &rgbi[1], &rgbi[2]) != 3) { + // integers failed, try percent values (float, locale independent) + const char delimiter[3] = {',', ',', ')'}; + str += 4; // skip "rgb(" + for (i = 0; i < 3; i++) { + while (*str && (nsvg__isspace(*str))) str++; // skip leading spaces + if (*str == '+') str++; // skip '+' (don't allow '-') + if (!*str) break; + rgbf[i] = nsvg__atof(str); + + // Note 1: it would be great if nsvg__atof() returned how many + // bytes it consumed but it doesn't. We need to skip the number, + // the '%' character, spaces, and the delimiter ',' or ')'. + + // Note 2: The following code does not allow values like "33.%", + // i.e. a decimal point w/o fractional part, but this is consistent + // with other image viewers, e.g. firefox, chrome, eog, gimp. + + while (*str && nsvg__isdigit(*str)) str++; // skip integer part + if (*str == '.') { + str++; + if (!nsvg__isdigit(*str)) break; // error: no digit after '.' + while (*str && nsvg__isdigit(*str)) str++; // skip fractional part + } + if (*str == '%') str++; else break; + while (*str && nsvg__isspace(*str)) str++; + if (*str == delimiter[i]) str++; + else break; + } + if (i == 3) { + rgbi[0] = roundf(rgbf[0] * 2.55f); + rgbi[1] = roundf(rgbf[1] * 2.55f); + rgbi[2] = roundf(rgbf[2] * 2.55f); + } else { + rgbi[0] = rgbi[1] = rgbi[2] = 128; + } + } + // clip values as the CSS spec requires + for (i = 0; i < 3; i++) { + if (rgbi[i] > 255) rgbi[i] = 255; + } + return NSVG_RGB(rgbi[0], rgbi[1], rgbi[2]); +} + +typedef struct NSVGNamedColor { + const char* name; + unsigned int color; +} NSVGNamedColor; + +NSVGNamedColor nsvg__colors[] = { + + { "red", NSVG_RGB(255, 0, 0) }, + { "green", NSVG_RGB( 0, 128, 0) }, + { "blue", NSVG_RGB( 0, 0, 255) }, + { "yellow", NSVG_RGB(255, 255, 0) }, + { "cyan", NSVG_RGB( 0, 255, 255) }, + { "magenta", NSVG_RGB(255, 0, 255) }, + { "black", NSVG_RGB( 0, 0, 0) }, + { "grey", NSVG_RGB(128, 128, 128) }, + { "gray", NSVG_RGB(128, 128, 128) }, + { "white", NSVG_RGB(255, 255, 255) }, + +#ifdef NANOSVG_ALL_COLOR_KEYWORDS + { "aliceblue", NSVG_RGB(240, 248, 255) }, + { "antiquewhite", NSVG_RGB(250, 235, 215) }, + { "aqua", NSVG_RGB( 0, 255, 255) }, + { "aquamarine", NSVG_RGB(127, 255, 212) }, + { "azure", NSVG_RGB(240, 255, 255) }, + { "beige", NSVG_RGB(245, 245, 220) }, + { "bisque", NSVG_RGB(255, 228, 196) }, + { "blanchedalmond", NSVG_RGB(255, 235, 205) }, + { "blueviolet", NSVG_RGB(138, 43, 226) }, + { "brown", NSVG_RGB(165, 42, 42) }, + { "burlywood", NSVG_RGB(222, 184, 135) }, + { "cadetblue", NSVG_RGB( 95, 158, 160) }, + { "chartreuse", NSVG_RGB(127, 255, 0) }, + { "chocolate", NSVG_RGB(210, 105, 30) }, + { "coral", NSVG_RGB(255, 127, 80) }, + { "cornflowerblue", NSVG_RGB(100, 149, 237) }, + { "cornsilk", NSVG_RGB(255, 248, 220) }, + { "crimson", NSVG_RGB(220, 20, 60) }, + { "darkblue", NSVG_RGB( 0, 0, 139) }, + { "darkcyan", NSVG_RGB( 0, 139, 139) }, + { "darkgoldenrod", NSVG_RGB(184, 134, 11) }, + { "darkgray", NSVG_RGB(169, 169, 169) }, + { "darkgreen", NSVG_RGB( 0, 100, 0) }, + { "darkgrey", NSVG_RGB(169, 169, 169) }, + { "darkkhaki", NSVG_RGB(189, 183, 107) }, + { "darkmagenta", NSVG_RGB(139, 0, 139) }, + { "darkolivegreen", NSVG_RGB( 85, 107, 47) }, + { "darkorange", NSVG_RGB(255, 140, 0) }, + { "darkorchid", NSVG_RGB(153, 50, 204) }, + { "darkred", NSVG_RGB(139, 0, 0) }, + { "darksalmon", NSVG_RGB(233, 150, 122) }, + { "darkseagreen", NSVG_RGB(143, 188, 143) }, + { "darkslateblue", NSVG_RGB( 72, 61, 139) }, + { "darkslategray", NSVG_RGB( 47, 79, 79) }, + { "darkslategrey", NSVG_RGB( 47, 79, 79) }, + { "darkturquoise", NSVG_RGB( 0, 206, 209) }, + { "darkviolet", NSVG_RGB(148, 0, 211) }, + { "deeppink", NSVG_RGB(255, 20, 147) }, + { "deepskyblue", NSVG_RGB( 0, 191, 255) }, + { "dimgray", NSVG_RGB(105, 105, 105) }, + { "dimgrey", NSVG_RGB(105, 105, 105) }, + { "dodgerblue", NSVG_RGB( 30, 144, 255) }, + { "firebrick", NSVG_RGB(178, 34, 34) }, + { "floralwhite", NSVG_RGB(255, 250, 240) }, + { "forestgreen", NSVG_RGB( 34, 139, 34) }, + { "fuchsia", NSVG_RGB(255, 0, 255) }, + { "gainsboro", NSVG_RGB(220, 220, 220) }, + { "ghostwhite", NSVG_RGB(248, 248, 255) }, + { "gold", NSVG_RGB(255, 215, 0) }, + { "goldenrod", NSVG_RGB(218, 165, 32) }, + { "greenyellow", NSVG_RGB(173, 255, 47) }, + { "honeydew", NSVG_RGB(240, 255, 240) }, + { "hotpink", NSVG_RGB(255, 105, 180) }, + { "indianred", NSVG_RGB(205, 92, 92) }, + { "indigo", NSVG_RGB( 75, 0, 130) }, + { "ivory", NSVG_RGB(255, 255, 240) }, + { "khaki", NSVG_RGB(240, 230, 140) }, + { "lavender", NSVG_RGB(230, 230, 250) }, + { "lavenderblush", NSVG_RGB(255, 240, 245) }, + { "lawngreen", NSVG_RGB(124, 252, 0) }, + { "lemonchiffon", NSVG_RGB(255, 250, 205) }, + { "lightblue", NSVG_RGB(173, 216, 230) }, + { "lightcoral", NSVG_RGB(240, 128, 128) }, + { "lightcyan", NSVG_RGB(224, 255, 255) }, + { "lightgoldenrodyellow", NSVG_RGB(250, 250, 210) }, + { "lightgray", NSVG_RGB(211, 211, 211) }, + { "lightgreen", NSVG_RGB(144, 238, 144) }, + { "lightgrey", NSVG_RGB(211, 211, 211) }, + { "lightpink", NSVG_RGB(255, 182, 193) }, + { "lightsalmon", NSVG_RGB(255, 160, 122) }, + { "lightseagreen", NSVG_RGB( 32, 178, 170) }, + { "lightskyblue", NSVG_RGB(135, 206, 250) }, + { "lightslategray", NSVG_RGB(119, 136, 153) }, + { "lightslategrey", NSVG_RGB(119, 136, 153) }, + { "lightsteelblue", NSVG_RGB(176, 196, 222) }, + { "lightyellow", NSVG_RGB(255, 255, 224) }, + { "lime", NSVG_RGB( 0, 255, 0) }, + { "limegreen", NSVG_RGB( 50, 205, 50) }, + { "linen", NSVG_RGB(250, 240, 230) }, + { "maroon", NSVG_RGB(128, 0, 0) }, + { "mediumaquamarine", NSVG_RGB(102, 205, 170) }, + { "mediumblue", NSVG_RGB( 0, 0, 205) }, + { "mediumorchid", NSVG_RGB(186, 85, 211) }, + { "mediumpurple", NSVG_RGB(147, 112, 219) }, + { "mediumseagreen", NSVG_RGB( 60, 179, 113) }, + { "mediumslateblue", NSVG_RGB(123, 104, 238) }, + { "mediumspringgreen", NSVG_RGB( 0, 250, 154) }, + { "mediumturquoise", NSVG_RGB( 72, 209, 204) }, + { "mediumvioletred", NSVG_RGB(199, 21, 133) }, + { "midnightblue", NSVG_RGB( 25, 25, 112) }, + { "mintcream", NSVG_RGB(245, 255, 250) }, + { "mistyrose", NSVG_RGB(255, 228, 225) }, + { "moccasin", NSVG_RGB(255, 228, 181) }, + { "navajowhite", NSVG_RGB(255, 222, 173) }, + { "navy", NSVG_RGB( 0, 0, 128) }, + { "oldlace", NSVG_RGB(253, 245, 230) }, + { "olive", NSVG_RGB(128, 128, 0) }, + { "olivedrab", NSVG_RGB(107, 142, 35) }, + { "orange", NSVG_RGB(255, 165, 0) }, + { "orangered", NSVG_RGB(255, 69, 0) }, + { "orchid", NSVG_RGB(218, 112, 214) }, + { "palegoldenrod", NSVG_RGB(238, 232, 170) }, + { "palegreen", NSVG_RGB(152, 251, 152) }, + { "paleturquoise", NSVG_RGB(175, 238, 238) }, + { "palevioletred", NSVG_RGB(219, 112, 147) }, + { "papayawhip", NSVG_RGB(255, 239, 213) }, + { "peachpuff", NSVG_RGB(255, 218, 185) }, + { "peru", NSVG_RGB(205, 133, 63) }, + { "pink", NSVG_RGB(255, 192, 203) }, + { "plum", NSVG_RGB(221, 160, 221) }, + { "powderblue", NSVG_RGB(176, 224, 230) }, + { "purple", NSVG_RGB(128, 0, 128) }, + { "rosybrown", NSVG_RGB(188, 143, 143) }, + { "royalblue", NSVG_RGB( 65, 105, 225) }, + { "saddlebrown", NSVG_RGB(139, 69, 19) }, + { "salmon", NSVG_RGB(250, 128, 114) }, + { "sandybrown", NSVG_RGB(244, 164, 96) }, + { "seagreen", NSVG_RGB( 46, 139, 87) }, + { "seashell", NSVG_RGB(255, 245, 238) }, + { "sienna", NSVG_RGB(160, 82, 45) }, + { "silver", NSVG_RGB(192, 192, 192) }, + { "skyblue", NSVG_RGB(135, 206, 235) }, + { "slateblue", NSVG_RGB(106, 90, 205) }, + { "slategray", NSVG_RGB(112, 128, 144) }, + { "slategrey", NSVG_RGB(112, 128, 144) }, + { "snow", NSVG_RGB(255, 250, 250) }, + { "springgreen", NSVG_RGB( 0, 255, 127) }, + { "steelblue", NSVG_RGB( 70, 130, 180) }, + { "tan", NSVG_RGB(210, 180, 140) }, + { "teal", NSVG_RGB( 0, 128, 128) }, + { "thistle", NSVG_RGB(216, 191, 216) }, + { "tomato", NSVG_RGB(255, 99, 71) }, + { "turquoise", NSVG_RGB( 64, 224, 208) }, + { "violet", NSVG_RGB(238, 130, 238) }, + { "wheat", NSVG_RGB(245, 222, 179) }, + { "whitesmoke", NSVG_RGB(245, 245, 245) }, + { "yellowgreen", NSVG_RGB(154, 205, 50) }, +#endif +}; + +static unsigned int nsvg__parseColorName(const char* str) +{ + int i, ncolors = sizeof(nsvg__colors) / sizeof(NSVGNamedColor); + + for (i = 0; i < ncolors; i++) { + if (strcmp(nsvg__colors[i].name, str) == 0) { + return nsvg__colors[i].color; + } + } + + return NSVG_RGB(128, 128, 128); +} + +static unsigned int nsvg__parseColor(const char* str) +{ + size_t len = 0; + while(*str == ' ') ++str; + len = strlen(str); + if (len >= 1 && *str == '#') + return nsvg__parseColorHex(str); + else if (len >= 4 && str[0] == 'r' && str[1] == 'g' && str[2] == 'b' && str[3] == '(') + return nsvg__parseColorRGB(str); + return nsvg__parseColorName(str); +} + +static float nsvg__parseOpacity(const char* str) +{ + float val = nsvg__atof(str); + if (val < 0.0f) val = 0.0f; + if (val > 1.0f) val = 1.0f; + return val; +} + +static float nsvg__parseMiterLimit(const char* str) +{ + float val = nsvg__atof(str); + if (val < 0.0f) val = 0.0f; + return val; +} + +static int nsvg__parseUnits(const char* units) +{ + if (units[0] == 'p' && units[1] == 'x') + return NSVG_UNITS_PX; + else if (units[0] == 'p' && units[1] == 't') + return NSVG_UNITS_PT; + else if (units[0] == 'p' && units[1] == 'c') + return NSVG_UNITS_PC; + else if (units[0] == 'm' && units[1] == 'm') + return NSVG_UNITS_MM; + else if (units[0] == 'c' && units[1] == 'm') + return NSVG_UNITS_CM; + else if (units[0] == 'i' && units[1] == 'n') + return NSVG_UNITS_IN; + else if (units[0] == '%') + return NSVG_UNITS_PERCENT; + else if (units[0] == 'e' && units[1] == 'm') + return NSVG_UNITS_EM; + else if (units[0] == 'e' && units[1] == 'x') + return NSVG_UNITS_EX; + return NSVG_UNITS_USER; +} + +static int nsvg__isCoordinate(const char* s) +{ + // optional sign + if (*s == '-' || *s == '+') + s++; + // must have at least one digit, or start by a dot + return (nsvg__isdigit(*s) || *s == '.'); +} + +static NSVGcoordinate nsvg__parseCoordinateRaw(const char* str) +{ + NSVGcoordinate coord = {0, NSVG_UNITS_USER}; + char buf[64]; + coord.units = nsvg__parseUnits(nsvg__parseNumber(str, buf, 64)); + coord.value = nsvg__atof(buf); + return coord; +} + +static NSVGcoordinate nsvg__coord(float v, int units) +{ + NSVGcoordinate coord = {v, units}; + return coord; +} + +static float nsvg__parseCoordinate(NSVGparser* p, const char* str, float orig, float length) +{ + NSVGcoordinate coord = nsvg__parseCoordinateRaw(str); + return nsvg__convertToPixels(p, coord, orig, length); +} + +static int nsvg__parseTransformArgs(const char* str, float* args, int maxNa, int* na) +{ + const char* end; + const char* ptr; + char it[64]; + + *na = 0; + ptr = str; + while (*ptr && *ptr != '(') ++ptr; + if (*ptr == 0) + return 1; + end = ptr; + while (*end && *end != ')') ++end; + if (*end == 0) + return 1; + + while (ptr < end) { + if (*ptr == '-' || *ptr == '+' || *ptr == '.' || nsvg__isdigit(*ptr)) { + if (*na >= maxNa) return 0; + ptr = nsvg__parseNumber(ptr, it, 64); + args[(*na)++] = (float)nsvg__atof(it); + } else { + ++ptr; + } + } + return (int)(end - str); +} + + +static int nsvg__parseMatrix(float* xform, const char* str) +{ + float t[6]; + int na = 0; + int len = nsvg__parseTransformArgs(str, t, 6, &na); + if (na != 6) return len; + memcpy(xform, t, sizeof(float)*6); + return len; +} + +static int nsvg__parseTranslate(float* xform, const char* str) +{ + float args[2]; + float t[6]; + int na = 0; + int len = nsvg__parseTransformArgs(str, args, 2, &na); + if (na == 1) args[1] = 0.0; + + nsvg__xformSetTranslation(t, args[0], args[1]); + memcpy(xform, t, sizeof(float)*6); + return len; +} + +static int nsvg__parseScale(float* xform, const char* str) +{ + float args[2]; + int na = 0; + float t[6]; + int len = nsvg__parseTransformArgs(str, args, 2, &na); + if (na == 1) args[1] = args[0]; + nsvg__xformSetScale(t, args[0], args[1]); + memcpy(xform, t, sizeof(float)*6); + return len; +} + +static int nsvg__parseSkewX(float* xform, const char* str) +{ + float args[1]; + int na = 0; + float t[6]; + int len = nsvg__parseTransformArgs(str, args, 1, &na); + nsvg__xformSetSkewX(t, args[0]/180.0f*NSVG_PI); + memcpy(xform, t, sizeof(float)*6); + return len; +} + +static int nsvg__parseSkewY(float* xform, const char* str) +{ + float args[1]; + int na = 0; + float t[6]; + int len = nsvg__parseTransformArgs(str, args, 1, &na); + nsvg__xformSetSkewY(t, args[0]/180.0f*NSVG_PI); + memcpy(xform, t, sizeof(float)*6); + return len; +} + +static int nsvg__parseRotate(float* xform, const char* str) +{ + float args[3]; + int na = 0; + float m[6]; + float t[6]; + int len = nsvg__parseTransformArgs(str, args, 3, &na); + if (na == 1) + args[1] = args[2] = 0.0f; + nsvg__xformIdentity(m); + + if (na > 1) { + nsvg__xformSetTranslation(t, -args[1], -args[2]); + nsvg__xformMultiply(m, t); + } + + nsvg__xformSetRotation(t, args[0]/180.0f*NSVG_PI); + nsvg__xformMultiply(m, t); + + if (na > 1) { + nsvg__xformSetTranslation(t, args[1], args[2]); + nsvg__xformMultiply(m, t); + } + + memcpy(xform, m, sizeof(float)*6); + + return len; +} + +static void nsvg__parseTransform(float* xform, const char* str) +{ + float t[6]; + int len; + nsvg__xformIdentity(xform); + while (*str) + { + if (strncmp(str, "matrix", 6) == 0) + len = nsvg__parseMatrix(t, str); + else if (strncmp(str, "translate", 9) == 0) + len = nsvg__parseTranslate(t, str); + else if (strncmp(str, "scale", 5) == 0) + len = nsvg__parseScale(t, str); + else if (strncmp(str, "rotate", 6) == 0) + len = nsvg__parseRotate(t, str); + else if (strncmp(str, "skewX", 5) == 0) + len = nsvg__parseSkewX(t, str); + else if (strncmp(str, "skewY", 5) == 0) + len = nsvg__parseSkewY(t, str); + else{ + ++str; + continue; + } + if (len != 0) { + str += len; + } else { + ++str; + continue; + } + + nsvg__xformPremultiply(xform, t); + } +} + +static void nsvg__parseUrl(char* id, const char* str) +{ + int i = 0; + str += 4; // "url("; + if (*str && *str == '#') + str++; + while (i < 63 && *str && *str != ')') { + id[i] = *str++; + i++; + } + id[i] = '\0'; +} + +static char nsvg__parseLineCap(const char* str) +{ + if (strcmp(str, "butt") == 0) + return NSVG_CAP_BUTT; + else if (strcmp(str, "round") == 0) + return NSVG_CAP_ROUND; + else if (strcmp(str, "square") == 0) + return NSVG_CAP_SQUARE; + // TODO: handle inherit. + return NSVG_CAP_BUTT; +} + +static char nsvg__parseLineJoin(const char* str) +{ + if (strcmp(str, "miter") == 0) + return NSVG_JOIN_MITER; + else if (strcmp(str, "round") == 0) + return NSVG_JOIN_ROUND; + else if (strcmp(str, "bevel") == 0) + return NSVG_JOIN_BEVEL; + // TODO: handle inherit. + return NSVG_JOIN_MITER; +} + +static char nsvg__parseFillRule(const char* str) +{ + if (strcmp(str, "nonzero") == 0) + return NSVG_FILLRULE_NONZERO; + else if (strcmp(str, "evenodd") == 0) + return NSVG_FILLRULE_EVENODD; + // TODO: handle inherit. + return NSVG_FILLRULE_NONZERO; +} + +static unsigned char nsvg__parsePaintOrder(const char* str) +{ + if (strcmp(str, "normal") == 0 || strcmp(str, "fill stroke markers") == 0) + return nsvg__encodePaintOrder(NSVG_PAINT_FILL, NSVG_PAINT_STROKE, NSVG_PAINT_MARKERS); + else if (strcmp(str, "fill markers stroke") == 0) + return nsvg__encodePaintOrder(NSVG_PAINT_FILL, NSVG_PAINT_MARKERS, NSVG_PAINT_STROKE); + else if (strcmp(str, "markers fill stroke") == 0) + return nsvg__encodePaintOrder(NSVG_PAINT_MARKERS, NSVG_PAINT_FILL, NSVG_PAINT_STROKE); + else if (strcmp(str, "markers stroke fill") == 0) + return nsvg__encodePaintOrder(NSVG_PAINT_MARKERS, NSVG_PAINT_STROKE, NSVG_PAINT_FILL); + else if (strcmp(str, "stroke fill markers") == 0) + return nsvg__encodePaintOrder(NSVG_PAINT_STROKE, NSVG_PAINT_FILL, NSVG_PAINT_MARKERS); + else if (strcmp(str, "stroke markers fill") == 0) + return nsvg__encodePaintOrder(NSVG_PAINT_STROKE, NSVG_PAINT_MARKERS, NSVG_PAINT_FILL); + // TODO: handle inherit. + return nsvg__encodePaintOrder(NSVG_PAINT_FILL, NSVG_PAINT_STROKE, NSVG_PAINT_MARKERS); +} + +static const char* nsvg__getNextDashItem(const char* s, char* it) +{ + int n = 0; + it[0] = '\0'; + // Skip white spaces and commas + while (*s && (nsvg__isspace(*s) || *s == ',')) s++; + // Advance until whitespace, comma or end. + while (*s && (!nsvg__isspace(*s) && *s != ',')) { + if (n < 63) + it[n++] = *s; + s++; + } + it[n++] = '\0'; + return s; +} + +static int nsvg__parseStrokeDashArray(NSVGparser* p, const char* str, float* strokeDashArray) +{ + char item[64]; + int count = 0, i; + float sum = 0.0f; + + // Handle "none" + if (str[0] == 'n') + return 0; + + // Parse dashes + while (*str) { + str = nsvg__getNextDashItem(str, item); + if (!*item) break; + if (count < NSVG_MAX_DASHES) + strokeDashArray[count++] = fabsf(nsvg__parseCoordinate(p, item, 0.0f, nsvg__actualLength(p))); + } + + for (i = 0; i < count; i++) + sum += strokeDashArray[i]; + if (sum <= 1e-6f) + count = 0; + + return count; +} + +static void nsvg__parseStyle(NSVGparser* p, const char* str); + +// Apply any matching class styles for a "class" attribute value. We support only simple class +// selectors. The class attribute may contain multiple space-separated class names. +static void nsvg__applyClassStyles(NSVGparser* p, const char* value) +{ + const char* cur = value; + while (*cur) { + const char* classStart; + size_t classLen; + NSVGstyleDeclaration* style; + + while (*cur && nsvg__isspace(*cur)) + cur++; + if (!*cur) + break; + + classStart = cur; + while (*cur && !nsvg__isspace(*cur)) + cur++; + classLen = (size_t)(cur - classStart); + + for (style = p->styles; style != NULL; style = style->next) { + if (strncmp(style->className, classStart, classLen) == 0 && style->className[classLen] == '\0') { + nsvg__parseStyle(p, style->propertiesText); + } + } + } +} + +static int nsvg__parseAttr(NSVGparser* p, const char* name, const char* value) +{ + float xform[6]; + NSVGattrib* attr = nsvg__getAttr(p); + if (!attr) return 0; + + if (strcmp(name, "style") == 0) { + nsvg__parseStyle(p, value); + } else if (strcmp(name, "display") == 0) { + if (strcmp(value, "none") == 0) + attr->visible = 0; + // Don't reset ->visible on display:inline, one display:none hides the whole subtree + + } else if (strcmp(name, "fill") == 0) { + if (strcmp(value, "none") == 0) { + attr->hasFill = 0; + } else if (strncmp(value, "url(", 4) == 0) { + attr->hasFill = 2; + nsvg__parseUrl(attr->fillGradient, value); + } else { + attr->hasFill = 1; + attr->fillColor = nsvg__parseColor(value); + } + } else if (strcmp(name, "opacity") == 0) { + attr->opacity = nsvg__parseOpacity(value); + } else if (strcmp(name, "fill-opacity") == 0) { + attr->fillOpacity = nsvg__parseOpacity(value); + } else if (strcmp(name, "stroke") == 0) { + if (strcmp(value, "none") == 0) { + attr->hasStroke = 0; + } else if (strncmp(value, "url(", 4) == 0) { + attr->hasStroke = 2; + nsvg__parseUrl(attr->strokeGradient, value); + } else { + attr->hasStroke = 1; + attr->strokeColor = nsvg__parseColor(value); + } + } else if (strcmp(name, "stroke-width") == 0) { + attr->strokeWidth = nsvg__parseCoordinate(p, value, 0.0f, nsvg__actualLength(p)); + } else if (strcmp(name, "stroke-dasharray") == 0) { + attr->strokeDashCount = nsvg__parseStrokeDashArray(p, value, attr->strokeDashArray); + } else if (strcmp(name, "stroke-dashoffset") == 0) { + attr->strokeDashOffset = nsvg__parseCoordinate(p, value, 0.0f, nsvg__actualLength(p)); + } else if (strcmp(name, "stroke-opacity") == 0) { + attr->strokeOpacity = nsvg__parseOpacity(value); + } else if (strcmp(name, "stroke-linecap") == 0) { + attr->strokeLineCap = nsvg__parseLineCap(value); + } else if (strcmp(name, "stroke-linejoin") == 0) { + attr->strokeLineJoin = nsvg__parseLineJoin(value); + } else if (strcmp(name, "stroke-miterlimit") == 0) { + attr->miterLimit = nsvg__parseMiterLimit(value); + } else if (strcmp(name, "fill-rule") == 0) { + attr->fillRule = nsvg__parseFillRule(value); + } else if (strcmp(name, "font-size") == 0) { + attr->fontSize = nsvg__parseCoordinate(p, value, 0.0f, nsvg__actualLength(p)); + } else if (strcmp(name, "transform") == 0) { + nsvg__parseTransform(xform, value); + nsvg__xformPremultiply(attr->xform, xform); + } else if (strcmp(name, "stop-color") == 0) { + attr->stopColor = nsvg__parseColor(value); + } else if (strcmp(name, "stop-opacity") == 0) { + attr->stopOpacity = nsvg__parseOpacity(value); + } else if (strcmp(name, "offset") == 0) { + attr->stopOffset = nsvg__parseCoordinate(p, value, 0.0f, 1.0f); + } else if (strcmp(name, "paint-order") == 0) { + attr->paintOrder = nsvg__parsePaintOrder(value); + } else if (strcmp(name, "id") == 0) { + strncpy(attr->id, value, 63); + attr->id[63] = '\0'; + } else if (strcmp(name, "class") == 0) { + nsvg__applyClassStyles(p, value); + } + else { + return 0; + } + return 1; +} + +static int nsvg__parseNameValue(NSVGparser* p, const char* start, const char* end) +{ + const char* str; + const char* val; + char name[512]; + char value[512]; + int n; + + str = start; + while (str < end && *str != ':') ++str; + + val = str; + + // Right Trim + while (str > start && (*str == ':' || nsvg__isspace(*str))) --str; + ++str; + + n = (int)(str - start); + if (n > 511) n = 511; + if (n) memcpy(name, start, n); + name[n] = 0; + + while (val < end && (*val == ':' || nsvg__isspace(*val))) ++val; + + n = (int)(end - val); + if (n > 511) n = 511; + if (n) memcpy(value, val, n); + value[n] = 0; + + return nsvg__parseAttr(p, name, value); +} + +static void nsvg__parseStyle(NSVGparser* p, const char* str) +{ + const char* start; + const char* end; + + while (*str) { + // Left Trim + while(*str && nsvg__isspace(*str)) ++str; + start = str; + while(*str && *str != ';') ++str; + end = str; + + // Right Trim + while (end > start && (*end == ';' || nsvg__isspace(*end))) --end; + ++end; + + nsvg__parseNameValue(p, start, end); + if (*str) ++str; + } +} + +static void nsvg__parseAttribs(NSVGparser* p, const char** attr) +{ + int i; + for (i = 0; attr[i]; i += 2) + { + if (strcmp(attr[i], "style") == 0) + nsvg__parseStyle(p, attr[i + 1]); + else + nsvg__parseAttr(p, attr[i], attr[i + 1]); + } +} + +static int nsvg__getArgsPerElement(char cmd) +{ + switch (cmd) { + case 'v': + case 'V': + case 'h': + case 'H': + return 1; + case 'm': + case 'M': + case 'l': + case 'L': + case 't': + case 'T': + return 2; + case 'q': + case 'Q': + case 's': + case 'S': + return 4; + case 'c': + case 'C': + return 6; + case 'a': + case 'A': + return 7; + case 'z': + case 'Z': + return 0; + } + return -1; +} + +static void nsvg__pathMoveTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel) +{ + if (rel) { + *cpx += args[0]; + *cpy += args[1]; + } else { + *cpx = args[0]; + *cpy = args[1]; + } + nsvg__moveTo(p, *cpx, *cpy); +} + +static void nsvg__pathLineTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel) +{ + if (rel) { + *cpx += args[0]; + *cpy += args[1]; + } else { + *cpx = args[0]; + *cpy = args[1]; + } + nsvg__lineTo(p, *cpx, *cpy); +} + +static void nsvg__pathHLineTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel) +{ + if (rel) + *cpx += args[0]; + else + *cpx = args[0]; + nsvg__lineTo(p, *cpx, *cpy); +} + +static void nsvg__pathVLineTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel) +{ + if (rel) + *cpy += args[0]; + else + *cpy = args[0]; + nsvg__lineTo(p, *cpx, *cpy); +} + +static void nsvg__pathCubicBezTo(NSVGparser* p, float* cpx, float* cpy, + float* cpx2, float* cpy2, float* args, int rel) +{ + float x2, y2, cx1, cy1, cx2, cy2; + + if (rel) { + cx1 = *cpx + args[0]; + cy1 = *cpy + args[1]; + cx2 = *cpx + args[2]; + cy2 = *cpy + args[3]; + x2 = *cpx + args[4]; + y2 = *cpy + args[5]; + } else { + cx1 = args[0]; + cy1 = args[1]; + cx2 = args[2]; + cy2 = args[3]; + x2 = args[4]; + y2 = args[5]; + } + + nsvg__cubicBezTo(p, cx1,cy1, cx2,cy2, x2,y2); + + *cpx2 = cx2; + *cpy2 = cy2; + *cpx = x2; + *cpy = y2; +} + +static void nsvg__pathCubicBezShortTo(NSVGparser* p, float* cpx, float* cpy, + float* cpx2, float* cpy2, float* args, int rel) +{ + float x1, y1, x2, y2, cx1, cy1, cx2, cy2; + + x1 = *cpx; + y1 = *cpy; + if (rel) { + cx2 = *cpx + args[0]; + cy2 = *cpy + args[1]; + x2 = *cpx + args[2]; + y2 = *cpy + args[3]; + } else { + cx2 = args[0]; + cy2 = args[1]; + x2 = args[2]; + y2 = args[3]; + } + + cx1 = 2*x1 - *cpx2; + cy1 = 2*y1 - *cpy2; + + nsvg__cubicBezTo(p, cx1,cy1, cx2,cy2, x2,y2); + + *cpx2 = cx2; + *cpy2 = cy2; + *cpx = x2; + *cpy = y2; +} + +static void nsvg__pathQuadBezTo(NSVGparser* p, float* cpx, float* cpy, + float* cpx2, float* cpy2, float* args, int rel) +{ + float x1, y1, x2, y2, cx, cy; + float cx1, cy1, cx2, cy2; + + x1 = *cpx; + y1 = *cpy; + if (rel) { + cx = *cpx + args[0]; + cy = *cpy + args[1]; + x2 = *cpx + args[2]; + y2 = *cpy + args[3]; + } else { + cx = args[0]; + cy = args[1]; + x2 = args[2]; + y2 = args[3]; + } + + // Convert to cubic bezier + cx1 = x1 + 2.0f/3.0f*(cx - x1); + cy1 = y1 + 2.0f/3.0f*(cy - y1); + cx2 = x2 + 2.0f/3.0f*(cx - x2); + cy2 = y2 + 2.0f/3.0f*(cy - y2); + + nsvg__cubicBezTo(p, cx1,cy1, cx2,cy2, x2,y2); + + *cpx2 = cx; + *cpy2 = cy; + *cpx = x2; + *cpy = y2; +} + +static void nsvg__pathQuadBezShortTo(NSVGparser* p, float* cpx, float* cpy, + float* cpx2, float* cpy2, float* args, int rel) +{ + float x1, y1, x2, y2, cx, cy; + float cx1, cy1, cx2, cy2; + + x1 = *cpx; + y1 = *cpy; + if (rel) { + x2 = *cpx + args[0]; + y2 = *cpy + args[1]; + } else { + x2 = args[0]; + y2 = args[1]; + } + + cx = 2*x1 - *cpx2; + cy = 2*y1 - *cpy2; + + // Convert to cubix bezier + cx1 = x1 + 2.0f/3.0f*(cx - x1); + cy1 = y1 + 2.0f/3.0f*(cy - y1); + cx2 = x2 + 2.0f/3.0f*(cx - x2); + cy2 = y2 + 2.0f/3.0f*(cy - y2); + + nsvg__cubicBezTo(p, cx1,cy1, cx2,cy2, x2,y2); + + *cpx2 = cx; + *cpy2 = cy; + *cpx = x2; + *cpy = y2; +} + +static float nsvg__sqr(float x) { return x*x; } +static float nsvg__vmag(float x, float y) { return sqrtf(x*x + y*y); } + +static float nsvg__vecrat(float ux, float uy, float vx, float vy) +{ + return (ux*vx + uy*vy) / (nsvg__vmag(ux,uy) * nsvg__vmag(vx,vy)); +} + +static float nsvg__vecang(float ux, float uy, float vx, float vy) +{ + float r = nsvg__vecrat(ux,uy, vx,vy); + if (r < -1.0f) r = -1.0f; + if (r > 1.0f) r = 1.0f; + return ((ux*vy < uy*vx) ? -1.0f : 1.0f) * acosf(r); +} + +static void nsvg__pathArcTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel) +{ + // Ported from canvg (https://code.google.com/p/canvg/) + float rx, ry, rotx; + float x1, y1, x2, y2, cx, cy, dx, dy, d; + float x1p, y1p, cxp, cyp, s, sa, sb; + float ux, uy, vx, vy, a1, da; + float x, y, tanx, tany, a, px = 0, py = 0, ptanx = 0, ptany = 0, t[6]; + float sinrx, cosrx; + int fa, fs; + int i, ndivs; + float hda, kappa; + + rx = fabsf(args[0]); // y radius + ry = fabsf(args[1]); // x radius + rotx = args[2] / 180.0f * NSVG_PI; // x rotation angle + fa = fabsf(args[3]) > 1e-6 ? 1 : 0; // Large arc + fs = fabsf(args[4]) > 1e-6 ? 1 : 0; // Sweep direction + x1 = *cpx; // start point + y1 = *cpy; + if (rel) { // end point + x2 = *cpx + args[5]; + y2 = *cpy + args[6]; + } else { + x2 = args[5]; + y2 = args[6]; + } + + dx = x1 - x2; + dy = y1 - y2; + d = sqrtf(dx*dx + dy*dy); + if (d < 1e-6f || rx < 1e-6f || ry < 1e-6f) { + // The arc degenerates to a line + nsvg__lineTo(p, x2, y2); + *cpx = x2; + *cpy = y2; + return; + } + + sinrx = sinf(rotx); + cosrx = cosf(rotx); + + // Convert to center point parameterization. + // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes + // 1) Compute x1', y1' + x1p = cosrx * dx / 2.0f + sinrx * dy / 2.0f; + y1p = -sinrx * dx / 2.0f + cosrx * dy / 2.0f; + d = nsvg__sqr(x1p)/nsvg__sqr(rx) + nsvg__sqr(y1p)/nsvg__sqr(ry); + if (d > 1) { + d = sqrtf(d); + rx *= d; + ry *= d; + } + // 2) Compute cx', cy' + s = 0.0f; + sa = nsvg__sqr(rx)*nsvg__sqr(ry) - nsvg__sqr(rx)*nsvg__sqr(y1p) - nsvg__sqr(ry)*nsvg__sqr(x1p); + sb = nsvg__sqr(rx)*nsvg__sqr(y1p) + nsvg__sqr(ry)*nsvg__sqr(x1p); + if (sa < 0.0f) sa = 0.0f; + if (sb > 0.0f) + s = sqrtf(sa / sb); + if (fa == fs) + s = -s; + cxp = s * rx * y1p / ry; + cyp = s * -ry * x1p / rx; + + // 3) Compute cx,cy from cx',cy' + cx = (x1 + x2)/2.0f + cosrx*cxp - sinrx*cyp; + cy = (y1 + y2)/2.0f + sinrx*cxp + cosrx*cyp; + + // 4) Calculate theta1, and delta theta. + ux = (x1p - cxp) / rx; + uy = (y1p - cyp) / ry; + vx = (-x1p - cxp) / rx; + vy = (-y1p - cyp) / ry; + a1 = nsvg__vecang(1.0f,0.0f, ux,uy); // Initial angle + da = nsvg__vecang(ux,uy, vx,vy); // Delta angle + +// if (vecrat(ux,uy,vx,vy) <= -1.0f) da = NSVG_PI; +// if (vecrat(ux,uy,vx,vy) >= 1.0f) da = 0; + + if (fs == 0 && da > 0) + da -= 2 * NSVG_PI; + else if (fs == 1 && da < 0) + da += 2 * NSVG_PI; + + // Approximate the arc using cubic spline segments. + t[0] = cosrx; t[1] = sinrx; + t[2] = -sinrx; t[3] = cosrx; + t[4] = cx; t[5] = cy; + + // Split arc into max 90 degree segments. + // The loop assumes an iteration per end point (including start and end), this +1. + ndivs = (int)(fabsf(da) / (NSVG_PI*0.5f) + 1.0f); + hda = (da / (float)ndivs) / 2.0f; + // Fix for ticket #179: division by 0: avoid cotangens around 0 (infinite) + if ((hda < 1e-3f) && (hda > -1e-3f)) + hda *= 0.5f; + else + hda = (1.0f - cosf(hda)) / sinf(hda); + kappa = fabsf(4.0f / 3.0f * hda); + if (da < 0.0f) + kappa = -kappa; + + for (i = 0; i <= ndivs; i++) { + a = a1 + da * ((float)i/(float)ndivs); + dx = cosf(a); + dy = sinf(a); + nsvg__xformPoint(&x, &y, dx*rx, dy*ry, t); // position + nsvg__xformVec(&tanx, &tany, -dy*rx * kappa, dx*ry * kappa, t); // tangent + if (i > 0) + nsvg__cubicBezTo(p, px+ptanx,py+ptany, x-tanx, y-tany, x, y); + px = x; + py = y; + ptanx = tanx; + ptany = tany; + } + + *cpx = x2; + *cpy = y2; +} + +static void nsvg__parsePath(NSVGparser* p, const char** attr) +{ + const char* s = NULL; + char cmd = '\0'; + float args[10]; + int nargs; + int rargs = 0; + char initPoint; + float cpx, cpy, cpx2, cpy2; + const char* tmp[4]; + char closedFlag; + int i; + char item[64]; + + for (i = 0; attr[i]; i += 2) { + if (strcmp(attr[i], "d") == 0) { + s = attr[i + 1]; + } else { + tmp[0] = attr[i]; + tmp[1] = attr[i + 1]; + tmp[2] = 0; + tmp[3] = 0; + nsvg__parseAttribs(p, tmp); + } + } + + if (s) { + nsvg__resetPath(p); + cpx = 0; cpy = 0; + cpx2 = 0; cpy2 = 0; + initPoint = 0; + closedFlag = 0; + nargs = 0; + + while (*s) { + item[0] = '\0'; + if ((cmd == 'A' || cmd == 'a') && (nargs == 3 || nargs == 4)) + s = nsvg__getNextPathItemWhenArcFlag(s, item); + if (!*item) + s = nsvg__getNextPathItem(s, item); + if (!*item) break; + if (cmd != '\0' && nsvg__isCoordinate(item)) { + if (nargs < 10) + args[nargs++] = (float)nsvg__atof(item); + if (nargs >= rargs) { + switch (cmd) { + case 'm': + case 'M': + nsvg__pathMoveTo(p, &cpx, &cpy, args, cmd == 'm' ? 1 : 0); + // Moveto can be followed by multiple coordinate pairs, + // which should be treated as linetos. + cmd = (cmd == 'm') ? 'l' : 'L'; + rargs = nsvg__getArgsPerElement(cmd); + cpx2 = cpx; cpy2 = cpy; + initPoint = 1; + break; + case 'l': + case 'L': + nsvg__pathLineTo(p, &cpx, &cpy, args, cmd == 'l' ? 1 : 0); + cpx2 = cpx; cpy2 = cpy; + break; + case 'H': + case 'h': + nsvg__pathHLineTo(p, &cpx, &cpy, args, cmd == 'h' ? 1 : 0); + cpx2 = cpx; cpy2 = cpy; + break; + case 'V': + case 'v': + nsvg__pathVLineTo(p, &cpx, &cpy, args, cmd == 'v' ? 1 : 0); + cpx2 = cpx; cpy2 = cpy; + break; + case 'C': + case 'c': + nsvg__pathCubicBezTo(p, &cpx, &cpy, &cpx2, &cpy2, args, cmd == 'c' ? 1 : 0); + break; + case 'S': + case 's': + nsvg__pathCubicBezShortTo(p, &cpx, &cpy, &cpx2, &cpy2, args, cmd == 's' ? 1 : 0); + break; + case 'Q': + case 'q': + nsvg__pathQuadBezTo(p, &cpx, &cpy, &cpx2, &cpy2, args, cmd == 'q' ? 1 : 0); + break; + case 'T': + case 't': + nsvg__pathQuadBezShortTo(p, &cpx, &cpy, &cpx2, &cpy2, args, cmd == 't' ? 1 : 0); + break; + case 'A': + case 'a': + nsvg__pathArcTo(p, &cpx, &cpy, args, cmd == 'a' ? 1 : 0); + cpx2 = cpx; cpy2 = cpy; + break; + default: + if (nargs >= 2) { + cpx = args[nargs-2]; + cpy = args[nargs-1]; + cpx2 = cpx; cpy2 = cpy; + } + break; + } + nargs = 0; + } + } else { + cmd = item[0]; + if (cmd == 'M' || cmd == 'm') { + // Commit path. + if (p->npts > 0) + nsvg__addPath(p, closedFlag); + // Start new subpath. + nsvg__resetPath(p); + closedFlag = 0; + nargs = 0; + } else if (initPoint == 0) { + // Do not allow other commands until initial point has been set (moveTo called once). + cmd = '\0'; + } + if (cmd == 'Z' || cmd == 'z') { + closedFlag = 1; + // Commit path. + if (p->npts > 0) { + // Move current point to first point + cpx = p->pts[0]; + cpy = p->pts[1]; + cpx2 = cpx; cpy2 = cpy; + nsvg__addPath(p, closedFlag); + } + // Start new subpath. + nsvg__resetPath(p); + nsvg__moveTo(p, cpx, cpy); + closedFlag = 0; + nargs = 0; + } + rargs = nsvg__getArgsPerElement(cmd); + if (rargs == -1) { + // Command not recognized + cmd = '\0'; + rargs = 0; + } + } + } + // Commit path. + if (p->npts) + nsvg__addPath(p, closedFlag); + } + + nsvg__addShape(p); +} + +static void nsvg__parseRect(NSVGparser* p, const char** attr) +{ + float x = 0.0f; + float y = 0.0f; + float w = 0.0f; + float h = 0.0f; + float rx = -1.0f; // marks not set + float ry = -1.0f; + int i; + + for (i = 0; attr[i]; i += 2) { + if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) { + if (strcmp(attr[i], "x") == 0) x = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigX(p), nsvg__actualWidth(p)); + if (strcmp(attr[i], "y") == 0) y = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigY(p), nsvg__actualHeight(p)); + if (strcmp(attr[i], "width") == 0) w = nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualWidth(p)); + if (strcmp(attr[i], "height") == 0) h = nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualHeight(p)); + if (strcmp(attr[i], "rx") == 0) rx = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualWidth(p))); + if (strcmp(attr[i], "ry") == 0) ry = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualHeight(p))); + } + } + + if (rx < 0.0f && ry > 0.0f) rx = ry; + if (ry < 0.0f && rx > 0.0f) ry = rx; + if (rx < 0.0f) rx = 0.0f; + if (ry < 0.0f) ry = 0.0f; + if (rx > w/2.0f) rx = w/2.0f; + if (ry > h/2.0f) ry = h/2.0f; + + if (w != 0.0f && h != 0.0f) { + nsvg__resetPath(p); + + if (rx < 0.00001f || ry < 0.0001f) { + nsvg__moveTo(p, x, y); + nsvg__lineTo(p, x+w, y); + nsvg__lineTo(p, x+w, y+h); + nsvg__lineTo(p, x, y+h); + } else { + // Rounded rectangle + nsvg__moveTo(p, x+rx, y); + nsvg__lineTo(p, x+w-rx, y); + nsvg__cubicBezTo(p, x+w-rx*(1-NSVG_KAPPA90), y, x+w, y+ry*(1-NSVG_KAPPA90), x+w, y+ry); + nsvg__lineTo(p, x+w, y+h-ry); + nsvg__cubicBezTo(p, x+w, y+h-ry*(1-NSVG_KAPPA90), x+w-rx*(1-NSVG_KAPPA90), y+h, x+w-rx, y+h); + nsvg__lineTo(p, x+rx, y+h); + nsvg__cubicBezTo(p, x+rx*(1-NSVG_KAPPA90), y+h, x, y+h-ry*(1-NSVG_KAPPA90), x, y+h-ry); + nsvg__lineTo(p, x, y+ry); + nsvg__cubicBezTo(p, x, y+ry*(1-NSVG_KAPPA90), x+rx*(1-NSVG_KAPPA90), y, x+rx, y); + } + + nsvg__addPath(p, 1); + + nsvg__addShape(p); + } +} + +static void nsvg__parseCircle(NSVGparser* p, const char** attr) +{ + float cx = 0.0f; + float cy = 0.0f; + float r = 0.0f; + int i; + + for (i = 0; attr[i]; i += 2) { + if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) { + if (strcmp(attr[i], "cx") == 0) cx = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigX(p), nsvg__actualWidth(p)); + if (strcmp(attr[i], "cy") == 0) cy = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigY(p), nsvg__actualHeight(p)); + if (strcmp(attr[i], "r") == 0) r = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualLength(p))); + } + } + + if (r > 0.0f) { + nsvg__resetPath(p); + + nsvg__moveTo(p, cx+r, cy); + nsvg__cubicBezTo(p, cx+r, cy+r*NSVG_KAPPA90, cx+r*NSVG_KAPPA90, cy+r, cx, cy+r); + nsvg__cubicBezTo(p, cx-r*NSVG_KAPPA90, cy+r, cx-r, cy+r*NSVG_KAPPA90, cx-r, cy); + nsvg__cubicBezTo(p, cx-r, cy-r*NSVG_KAPPA90, cx-r*NSVG_KAPPA90, cy-r, cx, cy-r); + nsvg__cubicBezTo(p, cx+r*NSVG_KAPPA90, cy-r, cx+r, cy-r*NSVG_KAPPA90, cx+r, cy); + + nsvg__addPath(p, 1); + + nsvg__addShape(p); + } +} + +static void nsvg__parseEllipse(NSVGparser* p, const char** attr) +{ + float cx = 0.0f; + float cy = 0.0f; + float rx = 0.0f; + float ry = 0.0f; + int i; + + for (i = 0; attr[i]; i += 2) { + if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) { + if (strcmp(attr[i], "cx") == 0) cx = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigX(p), nsvg__actualWidth(p)); + if (strcmp(attr[i], "cy") == 0) cy = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigY(p), nsvg__actualHeight(p)); + if (strcmp(attr[i], "rx") == 0) rx = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualWidth(p))); + if (strcmp(attr[i], "ry") == 0) ry = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualHeight(p))); + } + } + + if (rx > 0.0f && ry > 0.0f) { + + nsvg__resetPath(p); + + nsvg__moveTo(p, cx+rx, cy); + nsvg__cubicBezTo(p, cx+rx, cy+ry*NSVG_KAPPA90, cx+rx*NSVG_KAPPA90, cy+ry, cx, cy+ry); + nsvg__cubicBezTo(p, cx-rx*NSVG_KAPPA90, cy+ry, cx-rx, cy+ry*NSVG_KAPPA90, cx-rx, cy); + nsvg__cubicBezTo(p, cx-rx, cy-ry*NSVG_KAPPA90, cx-rx*NSVG_KAPPA90, cy-ry, cx, cy-ry); + nsvg__cubicBezTo(p, cx+rx*NSVG_KAPPA90, cy-ry, cx+rx, cy-ry*NSVG_KAPPA90, cx+rx, cy); + + nsvg__addPath(p, 1); + + nsvg__addShape(p); + } +} + +static void nsvg__parseLine(NSVGparser* p, const char** attr) +{ + float x1 = 0.0; + float y1 = 0.0; + float x2 = 0.0; + float y2 = 0.0; + int i; + + for (i = 0; attr[i]; i += 2) { + if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) { + if (strcmp(attr[i], "x1") == 0) x1 = nsvg__parseCoordinate(p, attr[i + 1], nsvg__actualOrigX(p), nsvg__actualWidth(p)); + if (strcmp(attr[i], "y1") == 0) y1 = nsvg__parseCoordinate(p, attr[i + 1], nsvg__actualOrigY(p), nsvg__actualHeight(p)); + if (strcmp(attr[i], "x2") == 0) x2 = nsvg__parseCoordinate(p, attr[i + 1], nsvg__actualOrigX(p), nsvg__actualWidth(p)); + if (strcmp(attr[i], "y2") == 0) y2 = nsvg__parseCoordinate(p, attr[i + 1], nsvg__actualOrigY(p), nsvg__actualHeight(p)); + } + } + + nsvg__resetPath(p); + + nsvg__moveTo(p, x1, y1); + nsvg__lineTo(p, x2, y2); + + nsvg__addPath(p, 0); + + nsvg__addShape(p); +} + +static void nsvg__parsePoly(NSVGparser* p, const char** attr, int closeFlag) +{ + int i; + const char* s; + float args[2]; + int nargs, npts = 0; + char item[64]; + + nsvg__resetPath(p); + + for (i = 0; attr[i]; i += 2) { + if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) { + if (strcmp(attr[i], "points") == 0) { + s = attr[i + 1]; + nargs = 0; + while (*s) { + s = nsvg__getNextPathItem(s, item); + args[nargs++] = (float)nsvg__atof(item); + if (nargs >= 2) { + if (npts == 0) + nsvg__moveTo(p, args[0], args[1]); + else + nsvg__lineTo(p, args[0], args[1]); + nargs = 0; + npts++; + } + } + } + } + } + + nsvg__addPath(p, (char)closeFlag); + + nsvg__addShape(p); +} + +static void nsvg__parseSVG(NSVGparser* p, const char** attr) +{ + int i; + for (i = 0; attr[i]; i += 2) { + if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) { + if (strcmp(attr[i], "width") == 0) { + p->image->width = nsvg__parseCoordinate(p, attr[i + 1], 0.0f, 0.0f); + } else if (strcmp(attr[i], "height") == 0) { + p->image->height = nsvg__parseCoordinate(p, attr[i + 1], 0.0f, 0.0f); + } else if (strcmp(attr[i], "viewBox") == 0) { + const char *s = attr[i + 1]; + char buf[64]; + s = nsvg__parseNumber(s, buf, 64); + p->viewMinx = nsvg__atof(buf); + while (*s && (nsvg__isspace(*s) || *s == '%' || *s == ',')) s++; + if (!*s) return; + s = nsvg__parseNumber(s, buf, 64); + p->viewMiny = nsvg__atof(buf); + while (*s && (nsvg__isspace(*s) || *s == '%' || *s == ',')) s++; + if (!*s) return; + s = nsvg__parseNumber(s, buf, 64); + p->viewWidth = nsvg__atof(buf); + while (*s && (nsvg__isspace(*s) || *s == '%' || *s == ',')) s++; + if (!*s) return; + s = nsvg__parseNumber(s, buf, 64); + p->viewHeight = nsvg__atof(buf); + } else if (strcmp(attr[i], "preserveAspectRatio") == 0) { + if (strstr(attr[i + 1], "none") != 0) { + // No uniform scaling + p->alignType = NSVG_ALIGN_NONE; + } else { + // Parse X align + if (strstr(attr[i + 1], "xMin") != 0) + p->alignX = NSVG_ALIGN_MIN; + else if (strstr(attr[i + 1], "xMid") != 0) + p->alignX = NSVG_ALIGN_MID; + else if (strstr(attr[i + 1], "xMax") != 0) + p->alignX = NSVG_ALIGN_MAX; + // Parse X align + if (strstr(attr[i + 1], "yMin") != 0) + p->alignY = NSVG_ALIGN_MIN; + else if (strstr(attr[i + 1], "yMid") != 0) + p->alignY = NSVG_ALIGN_MID; + else if (strstr(attr[i + 1], "yMax") != 0) + p->alignY = NSVG_ALIGN_MAX; + // Parse meet/slice + p->alignType = NSVG_ALIGN_MEET; + if (strstr(attr[i + 1], "slice") != 0) + p->alignType = NSVG_ALIGN_SLICE; + } + } + } + } +} + +static void nsvg__parseGradient(NSVGparser* p, const char** attr, signed char type) +{ + int i; + NSVGgradientData* grad = (NSVGgradientData*)malloc(sizeof(NSVGgradientData)); + if (grad == NULL) return; + memset(grad, 0, sizeof(NSVGgradientData)); + grad->units = NSVG_OBJECT_SPACE; + grad->type = type; + if (grad->type == NSVG_PAINT_LINEAR_GRADIENT) { + grad->linear.x1 = nsvg__coord(0.0f, NSVG_UNITS_PERCENT); + grad->linear.y1 = nsvg__coord(0.0f, NSVG_UNITS_PERCENT); + grad->linear.x2 = nsvg__coord(100.0f, NSVG_UNITS_PERCENT); + grad->linear.y2 = nsvg__coord(0.0f, NSVG_UNITS_PERCENT); + } else if (grad->type == NSVG_PAINT_RADIAL_GRADIENT) { + grad->radial.cx = nsvg__coord(50.0f, NSVG_UNITS_PERCENT); + grad->radial.cy = nsvg__coord(50.0f, NSVG_UNITS_PERCENT); + grad->radial.r = nsvg__coord(50.0f, NSVG_UNITS_PERCENT); + } + + nsvg__xformIdentity(grad->xform); + + for (i = 0; attr[i]; i += 2) { + if (strcmp(attr[i], "id") == 0) { + strncpy(grad->id, attr[i+1], 63); + grad->id[63] = '\0'; + } else if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) { + if (strcmp(attr[i], "gradientUnits") == 0) { + if (strcmp(attr[i+1], "objectBoundingBox") == 0) + grad->units = NSVG_OBJECT_SPACE; + else + grad->units = NSVG_USER_SPACE; + } else if (strcmp(attr[i], "gradientTransform") == 0) { + nsvg__parseTransform(grad->xform, attr[i + 1]); + } else if (strcmp(attr[i], "cx") == 0) { + grad->radial.cx = nsvg__parseCoordinateRaw(attr[i + 1]); + } else if (strcmp(attr[i], "cy") == 0) { + grad->radial.cy = nsvg__parseCoordinateRaw(attr[i + 1]); + } else if (strcmp(attr[i], "r") == 0) { + grad->radial.r = nsvg__parseCoordinateRaw(attr[i + 1]); + } else if (strcmp(attr[i], "fx") == 0) { + grad->radial.fx = nsvg__parseCoordinateRaw(attr[i + 1]); + } else if (strcmp(attr[i], "fy") == 0) { + grad->radial.fy = nsvg__parseCoordinateRaw(attr[i + 1]); + } else if (strcmp(attr[i], "x1") == 0) { + grad->linear.x1 = nsvg__parseCoordinateRaw(attr[i + 1]); + } else if (strcmp(attr[i], "y1") == 0) { + grad->linear.y1 = nsvg__parseCoordinateRaw(attr[i + 1]); + } else if (strcmp(attr[i], "x2") == 0) { + grad->linear.x2 = nsvg__parseCoordinateRaw(attr[i + 1]); + } else if (strcmp(attr[i], "y2") == 0) { + grad->linear.y2 = nsvg__parseCoordinateRaw(attr[i + 1]); + } else if (strcmp(attr[i], "spreadMethod") == 0) { + if (strcmp(attr[i+1], "pad") == 0) + grad->spread = NSVG_SPREAD_PAD; + else if (strcmp(attr[i+1], "reflect") == 0) + grad->spread = NSVG_SPREAD_REFLECT; + else if (strcmp(attr[i+1], "repeat") == 0) + grad->spread = NSVG_SPREAD_REPEAT; + } else if (strcmp(attr[i], "xlink:href") == 0) { + const char *href = attr[i+1]; + strncpy(grad->ref, href+1, 62); + grad->ref[62] = '\0'; + } + } + } + + grad->next = p->gradients; + p->gradients = grad; +} + +static void nsvg__parseGradientStop(NSVGparser* p, const char** attr) +{ + NSVGattrib* curAttr = nsvg__getAttr(p); + NSVGgradientData* grad; + NSVGgradientStop* stop; + int i, idx; + + curAttr->stopOffset = 0; + curAttr->stopColor = 0; + curAttr->stopOpacity = 1.0f; + + for (i = 0; attr[i]; i += 2) { + nsvg__parseAttr(p, attr[i], attr[i + 1]); + } + + // Add stop to the last gradient. + grad = p->gradients; + if (grad == NULL) return; + + grad->nstops++; + grad->stops = (NSVGgradientStop*)realloc(grad->stops, sizeof(NSVGgradientStop)*grad->nstops); + if (grad->stops == NULL) return; + + // Insert + idx = grad->nstops-1; + for (i = 0; i < grad->nstops-1; i++) { + if (curAttr->stopOffset < grad->stops[i].offset) { + idx = i; + break; + } + } + if (idx != grad->nstops-1) { + for (i = grad->nstops-1; i > idx; i--) + grad->stops[i] = grad->stops[i-1]; + } + + stop = &grad->stops[idx]; + stop->color = curAttr->stopColor; + stop->color |= (unsigned int)(curAttr->stopOpacity*255) << 24; + stop->offset = curAttr->stopOffset; +} + +static void nsvg__startElement(void* ud, const char* el, const char** attr) +{ + NSVGparser* p = (NSVGparser*)ud; + + if (p->defsFlag) { + // Skip everything but gradients and styles in defs + if (strcmp(el, "linearGradient") == 0) { + nsvg__parseGradient(p, attr, NSVG_PAINT_LINEAR_GRADIENT); + } else if (strcmp(el, "radialGradient") == 0) { + nsvg__parseGradient(p, attr, NSVG_PAINT_RADIAL_GRADIENT); + } else if (strcmp(el, "stop") == 0) { + nsvg__parseGradientStop(p, attr); + } else if (strcmp(el, "style") == 0) { + p->styleFlag = 1; + } + return; + } + + if (strcmp(el, "g") == 0) { + nsvg__pushAttr(p); + nsvg__parseAttribs(p, attr); + } else if (strcmp(el, "path") == 0) { + if (p->pathFlag) // Do not allow nested paths. + return; + nsvg__pushAttr(p); + nsvg__parsePath(p, attr); + nsvg__popAttr(p); + } else if (strcmp(el, "rect") == 0) { + nsvg__pushAttr(p); + nsvg__parseRect(p, attr); + nsvg__popAttr(p); + } else if (strcmp(el, "circle") == 0) { + nsvg__pushAttr(p); + nsvg__parseCircle(p, attr); + nsvg__popAttr(p); + } else if (strcmp(el, "ellipse") == 0) { + nsvg__pushAttr(p); + nsvg__parseEllipse(p, attr); + nsvg__popAttr(p); + } else if (strcmp(el, "line") == 0) { + nsvg__pushAttr(p); + nsvg__parseLine(p, attr); + nsvg__popAttr(p); + } else if (strcmp(el, "polyline") == 0) { + nsvg__pushAttr(p); + nsvg__parsePoly(p, attr, 0); + nsvg__popAttr(p); + } else if (strcmp(el, "polygon") == 0) { + nsvg__pushAttr(p); + nsvg__parsePoly(p, attr, 1); + nsvg__popAttr(p); + } else if (strcmp(el, "linearGradient") == 0) { + nsvg__parseGradient(p, attr, NSVG_PAINT_LINEAR_GRADIENT); + } else if (strcmp(el, "radialGradient") == 0) { + nsvg__parseGradient(p, attr, NSVG_PAINT_RADIAL_GRADIENT); + } else if (strcmp(el, "stop") == 0) { + nsvg__parseGradientStop(p, attr); + } else if (strcmp(el, "defs") == 0) { + p->defsFlag = 1; + } else if (strcmp(el, "svg") == 0) { + nsvg__parseSVG(p, attr); + } else if (strcmp(el, "style") == 0) { + p->styleFlag = 1; + } +} + +static void nsvg__endElement(void* ud, const char* el) +{ + NSVGparser* p = (NSVGparser*)ud; + + if (strcmp(el, "g") == 0) { + nsvg__popAttr(p); + } else if (strcmp(el, "path") == 0) { + p->pathFlag = 0; + } else if (strcmp(el, "defs") == 0) { + p->defsFlag = 0; + } else if (strcmp(el, "style") == 0) { + p->styleFlag = 0; + } +} + +static char *nsvg__strndup(const char *s, size_t n) +{ + char *result = (char *)malloc(n + 1); + if (result == NULL) + return NULL; + + memcpy(result, s, n); + result[n] = '\0'; + return result; +} + +static void nsvg__content(void* ud, const char* s) +{ + NSVGparser* p = (NSVGparser*)ud; + if (!p->styleFlag) + return; + + // Parse all the styles inside the style block. Each style's content will be later processed using nsvg__parseStyle(). + // Note: We only support selector lists of simple class selectors (e.g. ".foo, .bar { ... }"). + while (*s) { + NSVGstyleDeclaration* styles[NSVG_MAX_CLASSES]; + int nstyles = 0; + const char* propsStart; + const char* propsEnd; + int i; + + // 1) Parse the selector list up to '{'. For each simple class selector ('.name'), + // allocate a new NSVGstyleDeclaration into the local staging array. Styles are + // only committed to p->styles in step 3 below, once their propertiesText has + // also been allocated successfully. + while (*s && *s != '{') { + const char* selStart; + const char* selEnd; + NSVGstyleDeclaration* style; + + while (*s && (nsvg__isspace(*s) || *s == ',')) + s++; + if (!*s || *s == '{') + break; + + selStart = s; + while (*s && !nsvg__isspace(*s) && *s != ',' && *s != '{') + s++; + selEnd = s; + + if (*selStart != '.' || nstyles >= NSVG_MAX_CLASSES) + continue; // unsupported selector, or staging array full + selStart++; // strip leading '.' + + style = (NSVGstyleDeclaration*)malloc(sizeof(NSVGstyleDeclaration)); + if (style == NULL) + continue; + style->className = nsvg__strndup(selStart, (size_t)(selEnd - selStart)); + if (style->className == NULL) { + free(style); + continue; + } + style->propertiesText = NULL; + style->next = NULL; + styles[nstyles++] = style; + } + if (!*s) { + // No '{' found - discard pending styles and stop. + for (i = 0; i < nstyles; i++) { + free(styles[i]->className); + free(styles[i]); + } + break; + } + s++; // advance past '{' + + // 2) Find the end of the properties block (up to '}'). + propsStart = s; + while (*s && *s != '}') + s++; + propsEnd = s; + + // 3) Allocate propertiesText for each pending style. Commit successful ones to + // p->styles (head-insertion); free any whose allocation fails. + for (i = 0; i < nstyles; i++) { + styles[i]->propertiesText = nsvg__strndup(propsStart, (size_t)(propsEnd - propsStart)); + if (styles[i]->propertiesText == NULL) { + free(styles[i]->className); + free(styles[i]); + } else { + styles[i]->next = p->styles; + p->styles = styles[i]; + } + } + + if (*s) + s++; // advance past '}' + } +} + +static void nsvg__imageBounds(NSVGparser* p, float* bounds) +{ + NSVGshape* shape; + shape = p->image->shapes; + if (shape == NULL) { + bounds[0] = bounds[1] = bounds[2] = bounds[3] = 0.0; + return; + } + bounds[0] = shape->bounds[0]; + bounds[1] = shape->bounds[1]; + bounds[2] = shape->bounds[2]; + bounds[3] = shape->bounds[3]; + for (shape = shape->next; shape != NULL; shape = shape->next) { + bounds[0] = nsvg__minf(bounds[0], shape->bounds[0]); + bounds[1] = nsvg__minf(bounds[1], shape->bounds[1]); + bounds[2] = nsvg__maxf(bounds[2], shape->bounds[2]); + bounds[3] = nsvg__maxf(bounds[3], shape->bounds[3]); + } +} + +static float nsvg__viewAlign(float content, float container, int type) +{ + if (type == NSVG_ALIGN_MIN) + return 0; + else if (type == NSVG_ALIGN_MAX) + return container - content; + // mid + return (container - content) * 0.5f; +} + +static void nsvg__scaleGradient(NSVGgradient* grad, float tx, float ty, float sx, float sy) +{ + float t[6]; + nsvg__xformSetTranslation(t, tx, ty); + nsvg__xformMultiply (grad->xform, t); + + nsvg__xformSetScale(t, sx, sy); + nsvg__xformMultiply (grad->xform, t); +} + +static void nsvg__scaleToViewbox(NSVGparser* p, const char* units) +{ + NSVGshape* shape; + NSVGpath* path; + float tx, ty, sx, sy, us, bounds[4], t[6], avgs; + int i; + float* pt; + + // Guess image size if not set completely. + nsvg__imageBounds(p, bounds); + + if (p->viewWidth == 0) { + if (p->image->width > 0) { + p->viewWidth = p->image->width; + } else { + p->viewMinx = bounds[0]; + p->viewWidth = bounds[2] - bounds[0]; + } + } + if (p->viewHeight == 0) { + if (p->image->height > 0) { + p->viewHeight = p->image->height; + } else { + p->viewMiny = bounds[1]; + p->viewHeight = bounds[3] - bounds[1]; + } + } + if (p->image->width == 0) + p->image->width = p->viewWidth; + if (p->image->height == 0) + p->image->height = p->viewHeight; + + tx = -p->viewMinx; + ty = -p->viewMiny; + sx = p->viewWidth > 0 ? p->image->width / p->viewWidth : 0; + sy = p->viewHeight > 0 ? p->image->height / p->viewHeight : 0; + // Unit scaling + us = 1.0f / nsvg__convertToPixels(p, nsvg__coord(1.0f, nsvg__parseUnits(units)), 0.0f, 1.0f); + + // Fix aspect ratio + if (p->alignType == NSVG_ALIGN_MEET) { + // fit whole image into viewbox + sx = sy = nsvg__minf(sx, sy); + tx += nsvg__viewAlign(p->viewWidth*sx, p->image->width, p->alignX) / sx; + ty += nsvg__viewAlign(p->viewHeight*sy, p->image->height, p->alignY) / sy; + } else if (p->alignType == NSVG_ALIGN_SLICE) { + // fill whole viewbox with image + sx = sy = nsvg__maxf(sx, sy); + tx += nsvg__viewAlign(p->viewWidth*sx, p->image->width, p->alignX) / sx; + ty += nsvg__viewAlign(p->viewHeight*sy, p->image->height, p->alignY) / sy; + } + + // Transform + sx *= us; + sy *= us; + avgs = (sx+sy) / 2.0f; + for (shape = p->image->shapes; shape != NULL; shape = shape->next) { + shape->bounds[0] = (shape->bounds[0] + tx) * sx; + shape->bounds[1] = (shape->bounds[1] + ty) * sy; + shape->bounds[2] = (shape->bounds[2] + tx) * sx; + shape->bounds[3] = (shape->bounds[3] + ty) * sy; + for (path = shape->paths; path != NULL; path = path->next) { + path->bounds[0] = (path->bounds[0] + tx) * sx; + path->bounds[1] = (path->bounds[1] + ty) * sy; + path->bounds[2] = (path->bounds[2] + tx) * sx; + path->bounds[3] = (path->bounds[3] + ty) * sy; + for (i =0; i < path->npts; i++) { + pt = &path->pts[i*2]; + pt[0] = (pt[0] + tx) * sx; + pt[1] = (pt[1] + ty) * sy; + } + } + + if (shape->fill.type == NSVG_PAINT_LINEAR_GRADIENT || shape->fill.type == NSVG_PAINT_RADIAL_GRADIENT) { + nsvg__scaleGradient(shape->fill.gradient, tx,ty, sx,sy); + memcpy(t, shape->fill.gradient->xform, sizeof(float)*6); + nsvg__xformInverse(shape->fill.gradient->xform, t); + } + if (shape->stroke.type == NSVG_PAINT_LINEAR_GRADIENT || shape->stroke.type == NSVG_PAINT_RADIAL_GRADIENT) { + nsvg__scaleGradient(shape->stroke.gradient, tx,ty, sx,sy); + memcpy(t, shape->stroke.gradient->xform, sizeof(float)*6); + nsvg__xformInverse(shape->stroke.gradient->xform, t); + } + + shape->strokeWidth *= avgs; + shape->strokeDashOffset *= avgs; + for (i = 0; i < shape->strokeDashCount; i++) + shape->strokeDashArray[i] *= avgs; + } +} + +static void nsvg__createGradients(NSVGparser* p) +{ + NSVGshape* shape; + + for (shape = p->image->shapes; shape != NULL; shape = shape->next) { + if (shape->fill.type == NSVG_PAINT_UNDEF) { + if (shape->fillGradient[0] != '\0') { + float inv[6], localBounds[4]; + nsvg__xformInverse(inv, shape->xform); + nsvg__getLocalBounds(localBounds, shape, inv); + shape->fill.gradient = nsvg__createGradient(p, shape->fillGradient, localBounds, shape->xform, &shape->fill.type); + } + if (shape->fill.type == NSVG_PAINT_UNDEF) { + shape->fill.type = NSVG_PAINT_NONE; + } + } + if (shape->stroke.type == NSVG_PAINT_UNDEF) { + if (shape->strokeGradient[0] != '\0') { + float inv[6], localBounds[4]; + nsvg__xformInverse(inv, shape->xform); + nsvg__getLocalBounds(localBounds, shape, inv); + shape->stroke.gradient = nsvg__createGradient(p, shape->strokeGradient, localBounds, shape->xform, &shape->stroke.type); + } + if (shape->stroke.type == NSVG_PAINT_UNDEF) { + shape->stroke.type = NSVG_PAINT_NONE; + } + } + } +} + +NSVGimage* nsvgParse(char* input, const char* units, float dpi) +{ + NSVGparser* p; + NSVGimage* ret = 0; + + p = nsvg__createParser(); + if (p == NULL) { + return NULL; + } + p->dpi = dpi; + + nsvg__parseXML(input, nsvg__startElement, nsvg__endElement, nsvg__content, p); + + // Create gradients after all definitions have been parsed + nsvg__createGradients(p); + + // Scale to viewBox + nsvg__scaleToViewbox(p, units); + + ret = p->image; + p->image = NULL; + + nsvg__deleteParser(p); + + return ret; +} + +NSVGimage* nsvgParseFromFile(const char* filename, const char* units, float dpi) +{ + FILE* fp = NULL; + size_t size; + char* data = NULL; + NSVGimage* image = NULL; + + fp = fopen(filename, "rb"); + if (!fp) goto error; + if (fseek(fp, 0, SEEK_END)) goto error; + size = ftell(fp); + if (size == -1l) goto error; + if (fseek(fp, 0, SEEK_SET)) goto error; + data = (char*)malloc(size+1); + if (data == NULL) goto error; + if (fread(data, 1, size, fp) != size) goto error; + data[size] = '\0'; // Must be null terminated. + fclose(fp); + image = nsvgParse(data, units, dpi); + free(data); + + return image; + +error: + if (fp) fclose(fp); + if (data) free(data); + if (image) nsvgDelete(image); + return NULL; +} + +NSVGpath* nsvgDuplicatePath(NSVGpath* p) +{ + NSVGpath* res = NULL; + + if (p == NULL) + return NULL; + + res = (NSVGpath*)malloc(sizeof(NSVGpath)); + if (res == NULL) goto error; + memset(res, 0, sizeof(NSVGpath)); + + res->pts = (float*)malloc(p->npts*2*sizeof(float)); + if (res->pts == NULL) goto error; + memcpy(res->pts, p->pts, p->npts * sizeof(float) * 2); + res->npts = p->npts; + + memcpy(res->bounds, p->bounds, sizeof(p->bounds)); + + res->closed = p->closed; + + return res; + +error: + if (res != NULL) { + free(res->pts); + free(res); + } + return NULL; +} + +void nsvgDelete(NSVGimage* image) +{ + NSVGshape *snext, *shape; + if (image == NULL) return; + shape = image->shapes; + while (shape != NULL) { + snext = shape->next; + nsvg__deletePaths(shape->paths); + nsvg__deletePaint(&shape->fill); + nsvg__deletePaint(&shape->stroke); + free(shape); + shape = snext; + } + free(image); +} + +#endif // NANOSVG_IMPLEMENTATION + +#endif // NANOSVG_H diff --git a/Libraries/nanosvg/src/nanosvgrast.h b/Libraries/nanosvg/src/nanosvgrast.h new file mode 100644 index 000000000..ba512c74e --- /dev/null +++ b/Libraries/nanosvg/src/nanosvgrast.h @@ -0,0 +1,1472 @@ +/* + * Copyright (c) 2013-14 Mikko Mononen memon@inside.org + * + * This software is provided 'as-is', without any express or implied + * warranty. In no event will the authors be held liable for any damages + * arising from the use of this software. + * + * Permission is granted to anyone to use this software for any purpose, + * including commercial applications, and to alter it and redistribute it + * freely, subject to the following restrictions: + * + * 1. The origin of this software must not be misrepresented; you must not + * claim that you wrote the original software. If you use this software + * in a product, an acknowledgment in the product documentation would be + * appreciated but is not required. + * 2. Altered source versions must be plainly marked as such, and must not be + * misrepresented as being the original software. + * 3. This notice may not be removed or altered from any source distribution. + * + * The polygon rasterization is heavily based on stb_truetype rasterizer + * by Sean Barrett - http://nothings.org/ + * + */ + +#ifndef NANOSVGRAST_H +#define NANOSVGRAST_H + +#include "nanosvg.h" + +#ifndef NANOSVGRAST_CPLUSPLUS +#ifdef __cplusplus +extern "C" { +#endif +#endif + +typedef struct NSVGrasterizer NSVGrasterizer; + +/* Example Usage: + // Load SVG + NSVGimage* image; + image = nsvgParseFromFile("test.svg", "px", 96); + + // Create rasterizer (can be used to render multiple images). + struct NSVGrasterizer* rast = nsvgCreateRasterizer(); + // Allocate memory for image + unsigned char* img = malloc(w*h*4); + // Rasterize + nsvgRasterize(rast, image, 0,0,1, img, w, h, w*4); +*/ + +// Allocated rasterizer context. +NSVGrasterizer* nsvgCreateRasterizer(void); + +// Rasterizes SVG image, returns RGBA image (non-premultiplied alpha) +// r - pointer to rasterizer context +// image - pointer to image to rasterize +// tx,ty - image offset (applied after scaling) +// scale - image scale +// dst - pointer to destination image data, 4 bytes per pixel (RGBA) +// w - width of the image to render +// h - height of the image to render +// stride - number of bytes per scaleline in the destination buffer +void nsvgRasterize(NSVGrasterizer* r, + NSVGimage* image, float tx, float ty, float scale, + unsigned char* dst, int w, int h, int stride); + +// Deletes rasterizer context. +void nsvgDeleteRasterizer(NSVGrasterizer*); + + +#ifndef NANOSVGRAST_CPLUSPLUS +#ifdef __cplusplus +} +#endif +#endif + +#ifdef NANOSVGRAST_IMPLEMENTATION + +#include +#include +#include + +#define NSVG__SUBSAMPLES 5 +#define NSVG__FIXSHIFT 10 +#define NSVG__FIX (1 << NSVG__FIXSHIFT) +#define NSVG__FIXMASK (NSVG__FIX-1) +#define NSVG__MEMPAGE_SIZE 1024 + +typedef struct NSVGedge { + float x0,y0, x1,y1; + int dir; + struct NSVGedge* next; +} NSVGedge; + +typedef struct NSVGpoint { + float x, y; + float dx, dy; + float len; + float dmx, dmy; + unsigned char flags; +} NSVGpoint; + +typedef struct NSVGactiveEdge { + int x,dx; + float ey; + int dir; + struct NSVGactiveEdge *next; +} NSVGactiveEdge; + +typedef struct NSVGmemPage { + unsigned char mem[NSVG__MEMPAGE_SIZE]; + int size; + struct NSVGmemPage* next; +} NSVGmemPage; + +typedef struct NSVGcachedPaint { + signed char type; + char spread; + float xform[6]; + unsigned int colors[256]; +} NSVGcachedPaint; + +struct NSVGrasterizer +{ + float px, py; + + float tessTol; + float distTol; + + NSVGedge* edges; + int nedges; + int cedges; + + NSVGpoint* points; + int npoints; + int cpoints; + + NSVGpoint* points2; + int npoints2; + int cpoints2; + + NSVGactiveEdge* freelist; + NSVGmemPage* pages; + NSVGmemPage* curpage; + + unsigned char* scanline; + int cscanline; + + unsigned char* bitmap; + int width, height, stride; +}; + +NSVGrasterizer* nsvgCreateRasterizer(void) +{ + NSVGrasterizer* r = (NSVGrasterizer*)malloc(sizeof(NSVGrasterizer)); + if (r == NULL) goto error; + memset(r, 0, sizeof(NSVGrasterizer)); + + r->tessTol = 0.25f; + r->distTol = 0.01f; + + return r; + +error: + nsvgDeleteRasterizer(r); + return NULL; +} + +void nsvgDeleteRasterizer(NSVGrasterizer* r) +{ + NSVGmemPage* p; + + if (r == NULL) return; + + p = r->pages; + while (p != NULL) { + NSVGmemPage* next = p->next; + free(p); + p = next; + } + + if (r->edges) free(r->edges); + if (r->points) free(r->points); + if (r->points2) free(r->points2); + if (r->scanline) free(r->scanline); + + free(r); +} + +static NSVGmemPage* nsvg__nextPage(NSVGrasterizer* r, NSVGmemPage* cur) +{ + NSVGmemPage *newp; + + // If using existing chain, return the next page in chain + if (cur != NULL && cur->next != NULL) { + return cur->next; + } + + // Alloc new page + newp = (NSVGmemPage*)malloc(sizeof(NSVGmemPage)); + if (newp == NULL) return NULL; + memset(newp, 0, sizeof(NSVGmemPage)); + + // Add to linked list + if (cur != NULL) + cur->next = newp; + else + r->pages = newp; + + return newp; +} + +static void nsvg__resetPool(NSVGrasterizer* r) +{ + NSVGmemPage* p = r->pages; + while (p != NULL) { + p->size = 0; + p = p->next; + } + r->curpage = r->pages; +} + +static unsigned char* nsvg__alloc(NSVGrasterizer* r, int size) +{ + unsigned char* buf; + if (size > NSVG__MEMPAGE_SIZE) return NULL; + if (r->curpage == NULL || r->curpage->size+size > NSVG__MEMPAGE_SIZE) { + r->curpage = nsvg__nextPage(r, r->curpage); + } + buf = &r->curpage->mem[r->curpage->size]; + r->curpage->size += size; + return buf; +} + +static int nsvg__ptEquals(float x1, float y1, float x2, float y2, float tol) +{ + float dx = x2 - x1; + float dy = y2 - y1; + return dx*dx + dy*dy < tol*tol; +} + +static void nsvg__addPathPoint(NSVGrasterizer* r, float x, float y, int flags) +{ + NSVGpoint* pt; + + if (r->npoints > 0) { + pt = &r->points[r->npoints-1]; + if (nsvg__ptEquals(pt->x,pt->y, x,y, r->distTol)) { + pt->flags = (unsigned char)(pt->flags | flags); + return; + } + } + + if (r->npoints+1 > r->cpoints) { + r->cpoints = r->cpoints > 0 ? r->cpoints * 2 : 64; + r->points = (NSVGpoint*)realloc(r->points, sizeof(NSVGpoint) * r->cpoints); + if (r->points == NULL) return; + } + + pt = &r->points[r->npoints]; + pt->x = x; + pt->y = y; + pt->flags = (unsigned char)flags; + r->npoints++; +} + +static void nsvg__appendPathPoint(NSVGrasterizer* r, NSVGpoint pt) +{ + if (r->npoints+1 > r->cpoints) { + r->cpoints = r->cpoints > 0 ? r->cpoints * 2 : 64; + r->points = (NSVGpoint*)realloc(r->points, sizeof(NSVGpoint) * r->cpoints); + if (r->points == NULL) return; + } + r->points[r->npoints] = pt; + r->npoints++; +} + +static void nsvg__duplicatePoints(NSVGrasterizer* r) +{ + if (r->npoints > r->cpoints2) { + r->cpoints2 = r->npoints; + r->points2 = (NSVGpoint*)realloc(r->points2, sizeof(NSVGpoint) * r->cpoints2); + if (r->points2 == NULL) return; + } + + memcpy(r->points2, r->points, sizeof(NSVGpoint) * r->npoints); + r->npoints2 = r->npoints; +} + +static void nsvg__addEdge(NSVGrasterizer* r, float x0, float y0, float x1, float y1) +{ + NSVGedge* e; + + // Skip horizontal edges + if (y0 == y1) + return; + + if (r->nedges+1 > r->cedges) { + r->cedges = r->cedges > 0 ? r->cedges * 2 : 64; + r->edges = (NSVGedge*)realloc(r->edges, sizeof(NSVGedge) * r->cedges); + if (r->edges == NULL) return; + } + + e = &r->edges[r->nedges]; + r->nedges++; + + if (y0 < y1) { + e->x0 = x0; + e->y0 = y0; + e->x1 = x1; + e->y1 = y1; + e->dir = 1; + } else { + e->x0 = x1; + e->y0 = y1; + e->x1 = x0; + e->y1 = y0; + e->dir = -1; + } +} + +static float nsvg__normalize(float *x, float* y) +{ + float d = sqrtf((*x)*(*x) + (*y)*(*y)); + if (d > 1e-6f) { + float id = 1.0f / d; + *x *= id; + *y *= id; + } + return d; +} + +static float nsvg__absf(float x) { return x < 0 ? -x : x; } +static float nsvg__roundf(float x) { return (x >= 0) ? floorf(x + 0.5) : ceilf(x - 0.5); } + +static void nsvg__flattenCubicBez(NSVGrasterizer* r, + float x1, float y1, float x2, float y2, + float x3, float y3, float x4, float y4, + int level, int type) +{ + float x12,y12,x23,y23,x34,y34,x123,y123,x234,y234,x1234,y1234; + float dx,dy,d2,d3; + + if (level > 10) return; + + x12 = (x1+x2)*0.5f; + y12 = (y1+y2)*0.5f; + x23 = (x2+x3)*0.5f; + y23 = (y2+y3)*0.5f; + x34 = (x3+x4)*0.5f; + y34 = (y3+y4)*0.5f; + x123 = (x12+x23)*0.5f; + y123 = (y12+y23)*0.5f; + + dx = x4 - x1; + dy = y4 - y1; + d2 = nsvg__absf((x2 - x4) * dy - (y2 - y4) * dx); + d3 = nsvg__absf((x3 - x4) * dy - (y3 - y4) * dx); + + if ((d2 + d3)*(d2 + d3) < r->tessTol * (dx*dx + dy*dy)) { + nsvg__addPathPoint(r, x4, y4, type); + return; + } + + x234 = (x23+x34)*0.5f; + y234 = (y23+y34)*0.5f; + x1234 = (x123+x234)*0.5f; + y1234 = (y123+y234)*0.5f; + + nsvg__flattenCubicBez(r, x1,y1, x12,y12, x123,y123, x1234,y1234, level+1, 0); + nsvg__flattenCubicBez(r, x1234,y1234, x234,y234, x34,y34, x4,y4, level+1, type); +} + +static void nsvg__flattenShape(NSVGrasterizer* r, NSVGshape* shape, float scale) +{ + int i, j; + NSVGpath* path; + + for (path = shape->paths; path != NULL; path = path->next) { + r->npoints = 0; + // Flatten path + nsvg__addPathPoint(r, path->pts[0]*scale, path->pts[1]*scale, 0); + for (i = 0; i < path->npts-1; i += 3) { + float* p = &path->pts[i*2]; + nsvg__flattenCubicBez(r, p[0]*scale,p[1]*scale, p[2]*scale,p[3]*scale, p[4]*scale,p[5]*scale, p[6]*scale,p[7]*scale, 0, 0); + } + // Close path + nsvg__addPathPoint(r, path->pts[0]*scale, path->pts[1]*scale, 0); + // Build edges + for (i = 0, j = r->npoints-1; i < r->npoints; j = i++) + nsvg__addEdge(r, r->points[j].x, r->points[j].y, r->points[i].x, r->points[i].y); + } +} + +enum NSVGpointFlags +{ + NSVG_PT_CORNER = 0x01, + NSVG_PT_BEVEL = 0x02, + NSVG_PT_LEFT = 0x04 +}; + +static void nsvg__initClosed(NSVGpoint* left, NSVGpoint* right, NSVGpoint* p0, NSVGpoint* p1, float lineWidth) +{ + float w = lineWidth * 0.5f; + float dx = p1->x - p0->x; + float dy = p1->y - p0->y; + float len = nsvg__normalize(&dx, &dy); + float px = p0->x + dx*len*0.5f, py = p0->y + dy*len*0.5f; + float dlx = dy, dly = -dx; + float lx = px - dlx*w, ly = py - dly*w; + float rx = px + dlx*w, ry = py + dly*w; + left->x = lx; left->y = ly; + right->x = rx; right->y = ry; +} + +static void nsvg__buttCap(NSVGrasterizer* r, NSVGpoint* left, NSVGpoint* right, NSVGpoint* p, float dx, float dy, float lineWidth, int connect) +{ + float w = lineWidth * 0.5f; + float px = p->x, py = p->y; + float dlx = dy, dly = -dx; + float lx = px - dlx*w, ly = py - dly*w; + float rx = px + dlx*w, ry = py + dly*w; + + nsvg__addEdge(r, lx, ly, rx, ry); + + if (connect) { + nsvg__addEdge(r, left->x, left->y, lx, ly); + nsvg__addEdge(r, rx, ry, right->x, right->y); + } + left->x = lx; left->y = ly; + right->x = rx; right->y = ry; +} + +static void nsvg__squareCap(NSVGrasterizer* r, NSVGpoint* left, NSVGpoint* right, NSVGpoint* p, float dx, float dy, float lineWidth, int connect) +{ + float w = lineWidth * 0.5f; + float px = p->x - dx*w, py = p->y - dy*w; + float dlx = dy, dly = -dx; + float lx = px - dlx*w, ly = py - dly*w; + float rx = px + dlx*w, ry = py + dly*w; + + nsvg__addEdge(r, lx, ly, rx, ry); + + if (connect) { + nsvg__addEdge(r, left->x, left->y, lx, ly); + nsvg__addEdge(r, rx, ry, right->x, right->y); + } + left->x = lx; left->y = ly; + right->x = rx; right->y = ry; +} + +#ifndef NSVG_PI +#define NSVG_PI (3.14159265358979323846264338327f) +#endif + +static void nsvg__roundCap(NSVGrasterizer* r, NSVGpoint* left, NSVGpoint* right, NSVGpoint* p, float dx, float dy, float lineWidth, int ncap, int connect) +{ + int i; + float w = lineWidth * 0.5f; + float px = p->x, py = p->y; + float dlx = dy, dly = -dx; + float lx = 0, ly = 0, rx = 0, ry = 0, prevx = 0, prevy = 0; + + for (i = 0; i < ncap; i++) { + float a = (float)i/(float)(ncap-1)*NSVG_PI; + float ax = cosf(a) * w, ay = sinf(a) * w; + float x = px - dlx*ax - dx*ay; + float y = py - dly*ax - dy*ay; + + if (i > 0) + nsvg__addEdge(r, prevx, prevy, x, y); + + prevx = x; + prevy = y; + + if (i == 0) { + lx = x; ly = y; + } else if (i == ncap-1) { + rx = x; ry = y; + } + } + + if (connect) { + nsvg__addEdge(r, left->x, left->y, lx, ly); + nsvg__addEdge(r, rx, ry, right->x, right->y); + } + + left->x = lx; left->y = ly; + right->x = rx; right->y = ry; +} + +static void nsvg__bevelJoin(NSVGrasterizer* r, NSVGpoint* left, NSVGpoint* right, NSVGpoint* p0, NSVGpoint* p1, float lineWidth) +{ + float w = lineWidth * 0.5f; + float dlx0 = p0->dy, dly0 = -p0->dx; + float dlx1 = p1->dy, dly1 = -p1->dx; + float lx0 = p1->x - (dlx0 * w), ly0 = p1->y - (dly0 * w); + float rx0 = p1->x + (dlx0 * w), ry0 = p1->y + (dly0 * w); + float lx1 = p1->x - (dlx1 * w), ly1 = p1->y - (dly1 * w); + float rx1 = p1->x + (dlx1 * w), ry1 = p1->y + (dly1 * w); + + nsvg__addEdge(r, lx0, ly0, left->x, left->y); + nsvg__addEdge(r, lx1, ly1, lx0, ly0); + + nsvg__addEdge(r, right->x, right->y, rx0, ry0); + nsvg__addEdge(r, rx0, ry0, rx1, ry1); + + left->x = lx1; left->y = ly1; + right->x = rx1; right->y = ry1; +} + +static void nsvg__miterJoin(NSVGrasterizer* r, NSVGpoint* left, NSVGpoint* right, NSVGpoint* p0, NSVGpoint* p1, float lineWidth) +{ + float w = lineWidth * 0.5f; + float dlx0 = p0->dy, dly0 = -p0->dx; + float dlx1 = p1->dy, dly1 = -p1->dx; + float lx0, rx0, lx1, rx1; + float ly0, ry0, ly1, ry1; + + if (p1->flags & NSVG_PT_LEFT) { + lx0 = lx1 = p1->x - p1->dmx * w; + ly0 = ly1 = p1->y - p1->dmy * w; + nsvg__addEdge(r, lx1, ly1, left->x, left->y); + + rx0 = p1->x + (dlx0 * w); + ry0 = p1->y + (dly0 * w); + rx1 = p1->x + (dlx1 * w); + ry1 = p1->y + (dly1 * w); + nsvg__addEdge(r, right->x, right->y, rx0, ry0); + nsvg__addEdge(r, rx0, ry0, rx1, ry1); + } else { + lx0 = p1->x - (dlx0 * w); + ly0 = p1->y - (dly0 * w); + lx1 = p1->x - (dlx1 * w); + ly1 = p1->y - (dly1 * w); + nsvg__addEdge(r, lx0, ly0, left->x, left->y); + nsvg__addEdge(r, lx1, ly1, lx0, ly0); + + rx0 = rx1 = p1->x + p1->dmx * w; + ry0 = ry1 = p1->y + p1->dmy * w; + nsvg__addEdge(r, right->x, right->y, rx1, ry1); + } + + left->x = lx1; left->y = ly1; + right->x = rx1; right->y = ry1; +} + +static void nsvg__roundJoin(NSVGrasterizer* r, NSVGpoint* left, NSVGpoint* right, NSVGpoint* p0, NSVGpoint* p1, float lineWidth, int ncap) +{ + int i, n; + float w = lineWidth * 0.5f; + float dlx0 = p0->dy, dly0 = -p0->dx; + float dlx1 = p1->dy, dly1 = -p1->dx; + float a0 = atan2f(dly0, dlx0); + float a1 = atan2f(dly1, dlx1); + float da = a1 - a0; + float lx, ly, rx, ry; + + if (da < NSVG_PI) da += NSVG_PI*2; + if (da > NSVG_PI) da -= NSVG_PI*2; + + n = (int)ceilf((nsvg__absf(da) / NSVG_PI) * (float)ncap); + if (n < 2) n = 2; + if (n > ncap) n = ncap; + + lx = left->x; + ly = left->y; + rx = right->x; + ry = right->y; + + for (i = 0; i < n; i++) { + float u = (float)i/(float)(n-1); + float a = a0 + u*da; + float ax = cosf(a) * w, ay = sinf(a) * w; + float lx1 = p1->x - ax, ly1 = p1->y - ay; + float rx1 = p1->x + ax, ry1 = p1->y + ay; + + nsvg__addEdge(r, lx1, ly1, lx, ly); + nsvg__addEdge(r, rx, ry, rx1, ry1); + + lx = lx1; ly = ly1; + rx = rx1; ry = ry1; + } + + left->x = lx; left->y = ly; + right->x = rx; right->y = ry; +} + +static void nsvg__straightJoin(NSVGrasterizer* r, NSVGpoint* left, NSVGpoint* right, NSVGpoint* p1, float lineWidth) +{ + float w = lineWidth * 0.5f; + float lx = p1->x - (p1->dmx * w), ly = p1->y - (p1->dmy * w); + float rx = p1->x + (p1->dmx * w), ry = p1->y + (p1->dmy * w); + + nsvg__addEdge(r, lx, ly, left->x, left->y); + nsvg__addEdge(r, right->x, right->y, rx, ry); + + left->x = lx; left->y = ly; + right->x = rx; right->y = ry; +} + +static int nsvg__curveDivs(float r, float arc, float tol) +{ + float da = acosf(r / (r + tol)) * 2.0f; + int divs = (int)ceilf(arc / da); + if (divs < 2) divs = 2; + return divs; +} + +static void nsvg__expandStroke(NSVGrasterizer* r, NSVGpoint* points, int npoints, int closed, int lineJoin, int lineCap, float lineWidth) +{ + int ncap = nsvg__curveDivs(lineWidth*0.5f, NSVG_PI, r->tessTol); // Calculate divisions per half circle. + NSVGpoint left = {0,0,0,0,0,0,0,0}, right = {0,0,0,0,0,0,0,0}, firstLeft = {0,0,0,0,0,0,0,0}, firstRight = {0,0,0,0,0,0,0,0}; + NSVGpoint* p0, *p1; + int j, s, e; + + // Build stroke edges + if (closed) { + // Looping + p0 = &points[npoints-1]; + p1 = &points[0]; + s = 0; + e = npoints; + } else { + // Add cap + p0 = &points[0]; + p1 = &points[1]; + s = 1; + e = npoints-1; + } + + if (closed) { + nsvg__initClosed(&left, &right, p0, p1, lineWidth); + firstLeft = left; + firstRight = right; + } else { + // Add cap + float dx = p1->x - p0->x; + float dy = p1->y - p0->y; + nsvg__normalize(&dx, &dy); + if (lineCap == NSVG_CAP_BUTT) + nsvg__buttCap(r, &left, &right, p0, dx, dy, lineWidth, 0); + else if (lineCap == NSVG_CAP_SQUARE) + nsvg__squareCap(r, &left, &right, p0, dx, dy, lineWidth, 0); + else if (lineCap == NSVG_CAP_ROUND) + nsvg__roundCap(r, &left, &right, p0, dx, dy, lineWidth, ncap, 0); + } + + for (j = s; j < e; ++j) { + if (p1->flags & NSVG_PT_CORNER) { + if (lineJoin == NSVG_JOIN_ROUND) + nsvg__roundJoin(r, &left, &right, p0, p1, lineWidth, ncap); + else if (lineJoin == NSVG_JOIN_BEVEL || (p1->flags & NSVG_PT_BEVEL)) + nsvg__bevelJoin(r, &left, &right, p0, p1, lineWidth); + else + nsvg__miterJoin(r, &left, &right, p0, p1, lineWidth); + } else { + nsvg__straightJoin(r, &left, &right, p1, lineWidth); + } + p0 = p1++; + } + + if (closed) { + // Loop it + nsvg__addEdge(r, firstLeft.x, firstLeft.y, left.x, left.y); + nsvg__addEdge(r, right.x, right.y, firstRight.x, firstRight.y); + } else { + // Add cap + float dx = p1->x - p0->x; + float dy = p1->y - p0->y; + nsvg__normalize(&dx, &dy); + if (lineCap == NSVG_CAP_BUTT) + nsvg__buttCap(r, &right, &left, p1, -dx, -dy, lineWidth, 1); + else if (lineCap == NSVG_CAP_SQUARE) + nsvg__squareCap(r, &right, &left, p1, -dx, -dy, lineWidth, 1); + else if (lineCap == NSVG_CAP_ROUND) + nsvg__roundCap(r, &right, &left, p1, -dx, -dy, lineWidth, ncap, 1); + } +} + +static void nsvg__prepareStroke(NSVGrasterizer* r, float miterLimit, int lineJoin) +{ + int i, j; + NSVGpoint* p0, *p1; + + p0 = &r->points[r->npoints-1]; + p1 = &r->points[0]; + for (i = 0; i < r->npoints; i++) { + // Calculate segment direction and length + p0->dx = p1->x - p0->x; + p0->dy = p1->y - p0->y; + p0->len = nsvg__normalize(&p0->dx, &p0->dy); + // Advance + p0 = p1++; + } + + // calculate joins + p0 = &r->points[r->npoints-1]; + p1 = &r->points[0]; + for (j = 0; j < r->npoints; j++) { + float dlx0, dly0, dlx1, dly1, dmr2, cross; + dlx0 = p0->dy; + dly0 = -p0->dx; + dlx1 = p1->dy; + dly1 = -p1->dx; + // Calculate extrusions + p1->dmx = (dlx0 + dlx1) * 0.5f; + p1->dmy = (dly0 + dly1) * 0.5f; + dmr2 = p1->dmx*p1->dmx + p1->dmy*p1->dmy; + if (dmr2 > 0.000001f) { + float s2 = 1.0f / dmr2; + if (s2 > 600.0f) { + s2 = 600.0f; + } + p1->dmx *= s2; + p1->dmy *= s2; + } + + // Clear flags, but keep the corner. + p1->flags = (p1->flags & NSVG_PT_CORNER) ? NSVG_PT_CORNER : 0; + + // Keep track of left turns. + cross = p1->dx * p0->dy - p0->dx * p1->dy; + if (cross > 0.0f) + p1->flags |= NSVG_PT_LEFT; + + // Check to see if the corner needs to be beveled. + if (p1->flags & NSVG_PT_CORNER) { + if ((dmr2 * miterLimit*miterLimit) < 1.0f || lineJoin == NSVG_JOIN_BEVEL || lineJoin == NSVG_JOIN_ROUND) { + p1->flags |= NSVG_PT_BEVEL; + } + } + + p0 = p1++; + } +} + +static void nsvg__flattenShapeStroke(NSVGrasterizer* r, NSVGshape* shape, float scale) +{ + int i, j, closed; + NSVGpath* path; + NSVGpoint* p0, *p1; + float miterLimit = shape->miterLimit; + int lineJoin = shape->strokeLineJoin; + int lineCap = shape->strokeLineCap; + float lineWidth = shape->strokeWidth * scale; + + for (path = shape->paths; path != NULL; path = path->next) { + // Flatten path + r->npoints = 0; + nsvg__addPathPoint(r, path->pts[0]*scale, path->pts[1]*scale, NSVG_PT_CORNER); + for (i = 0; i < path->npts-1; i += 3) { + float* p = &path->pts[i*2]; + nsvg__flattenCubicBez(r, p[0]*scale,p[1]*scale, p[2]*scale,p[3]*scale, p[4]*scale,p[5]*scale, p[6]*scale,p[7]*scale, 0, NSVG_PT_CORNER); + } + if (r->npoints < 2) + continue; + + closed = path->closed; + + // If the first and last points are the same, remove the last, mark as closed path. + p0 = &r->points[r->npoints-1]; + p1 = &r->points[0]; + if (nsvg__ptEquals(p0->x,p0->y, p1->x,p1->y, r->distTol)) { + r->npoints--; + p0 = &r->points[r->npoints-1]; + closed = 1; + } + + if (shape->strokeDashCount > 0) { + int idash = 0, dashState = 1; + float totalDist = 0, dashLen, allDashLen, dashOffset; + NSVGpoint cur; + + if (closed) + nsvg__appendPathPoint(r, r->points[0]); + + // Duplicate points -> points2. + nsvg__duplicatePoints(r); + + r->npoints = 0; + cur = r->points2[0]; + nsvg__appendPathPoint(r, cur); + + // Figure out dash offset. + allDashLen = 0; + for (j = 0; j < shape->strokeDashCount; j++) + allDashLen += shape->strokeDashArray[j]; + if (shape->strokeDashCount & 1) + allDashLen *= 2.0f; + // Find location inside pattern + dashOffset = fmodf(shape->strokeDashOffset, allDashLen); + if (dashOffset < 0.0f) + dashOffset += allDashLen; + + while (dashOffset > shape->strokeDashArray[idash]) { + dashOffset -= shape->strokeDashArray[idash]; + idash = (idash + 1) % shape->strokeDashCount; + } + dashLen = (shape->strokeDashArray[idash] - dashOffset) * scale; + + for (j = 1; j < r->npoints2; ) { + float dx = r->points2[j].x - cur.x; + float dy = r->points2[j].y - cur.y; + float dist = sqrtf(dx*dx + dy*dy); + + if ((totalDist + dist) > dashLen) { + // Calculate intermediate point + float d = (dashLen - totalDist) / dist; + float x = cur.x + dx * d; + float y = cur.y + dy * d; + nsvg__addPathPoint(r, x, y, NSVG_PT_CORNER); + + // Stroke + if (r->npoints > 1 && dashState) { + nsvg__prepareStroke(r, miterLimit, lineJoin); + nsvg__expandStroke(r, r->points, r->npoints, 0, lineJoin, lineCap, lineWidth); + } + // Advance dash pattern + dashState = !dashState; + idash = (idash+1) % shape->strokeDashCount; + dashLen = shape->strokeDashArray[idash] * scale; + // Restart + cur.x = x; + cur.y = y; + cur.flags = NSVG_PT_CORNER; + totalDist = 0.0f; + r->npoints = 0; + nsvg__appendPathPoint(r, cur); + } else { + totalDist += dist; + cur = r->points2[j]; + nsvg__appendPathPoint(r, cur); + j++; + } + } + // Stroke any leftover path + if (r->npoints > 1 && dashState) { + nsvg__prepareStroke(r, miterLimit, lineJoin); + nsvg__expandStroke(r, r->points, r->npoints, 0, lineJoin, lineCap, lineWidth); + } + } else { + nsvg__prepareStroke(r, miterLimit, lineJoin); + nsvg__expandStroke(r, r->points, r->npoints, closed, lineJoin, lineCap, lineWidth); + } + } +} + +static int nsvg__cmpEdge(const void *p, const void *q) +{ + const NSVGedge* a = (const NSVGedge*)p; + const NSVGedge* b = (const NSVGedge*)q; + + if (a->y0 < b->y0) return -1; + if (a->y0 > b->y0) return 1; + return 0; +} + + +static NSVGactiveEdge* nsvg__addActive(NSVGrasterizer* r, NSVGedge* e, float startPoint) +{ + NSVGactiveEdge* z; + + if (r->freelist != NULL) { + // Restore from freelist. + z = r->freelist; + r->freelist = z->next; + } else { + // Alloc new edge. + z = (NSVGactiveEdge*)nsvg__alloc(r, sizeof(NSVGactiveEdge)); + if (z == NULL) return NULL; + } + + float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0); +// STBTT_assert(e->y0 <= start_point); + // round dx down to avoid going too far + if (dxdy < 0) + z->dx = (int)(-nsvg__roundf(NSVG__FIX * -dxdy)); + else + z->dx = (int)nsvg__roundf(NSVG__FIX * dxdy); + z->x = (int)nsvg__roundf(NSVG__FIX * (e->x0 + dxdy * (startPoint - e->y0))); +// z->x -= off_x * FIX; + z->ey = e->y1; + z->next = 0; + z->dir = e->dir; + + return z; +} + +static void nsvg__freeActive(NSVGrasterizer* r, NSVGactiveEdge* z) +{ + z->next = r->freelist; + r->freelist = z; +} + +static void nsvg__fillScanline(unsigned char* scanline, int len, int x0, int x1, int maxWeight, int* xmin, int* xmax) +{ + int i = x0 >> NSVG__FIXSHIFT; + int j = x1 >> NSVG__FIXSHIFT; + if (i < *xmin) *xmin = i; + if (j > *xmax) *xmax = j; + if (i < len && j >= 0) { + if (i == j) { + // x0,x1 are the same pixel, so compute combined coverage + scanline[i] = (unsigned char)(scanline[i] + ((x1 - x0) * maxWeight >> NSVG__FIXSHIFT)); + } else { + if (i >= 0) // add antialiasing for x0 + scanline[i] = (unsigned char)(scanline[i] + (((NSVG__FIX - (x0 & NSVG__FIXMASK)) * maxWeight) >> NSVG__FIXSHIFT)); + else + i = -1; // clip + + if (j < len) // add antialiasing for x1 + scanline[j] = (unsigned char)(scanline[j] + (((x1 & NSVG__FIXMASK) * maxWeight) >> NSVG__FIXSHIFT)); + else + j = len; // clip + + for (++i; i < j; ++i) // fill pixels between x0 and x1 + scanline[i] = (unsigned char)(scanline[i] + maxWeight); + } + } +} + +// note: this routine clips fills that extend off the edges... ideally this +// wouldn't happen, but it could happen if the truetype glyph bounding boxes +// are wrong, or if the user supplies a too-small bitmap +static void nsvg__fillActiveEdges(unsigned char* scanline, int len, NSVGactiveEdge* e, int maxWeight, int* xmin, int* xmax, char fillRule) +{ + // non-zero winding fill + int x0 = 0, w = 0; + + if (fillRule == NSVG_FILLRULE_NONZERO) { + // Non-zero + while (e != NULL) { + if (w == 0) { + // if we're currently at zero, we need to record the edge start point + x0 = e->x; w += e->dir; + } else { + int x1 = e->x; w += e->dir; + // if we went to zero, we need to draw + if (w == 0) + nsvg__fillScanline(scanline, len, x0, x1, maxWeight, xmin, xmax); + } + e = e->next; + } + } else if (fillRule == NSVG_FILLRULE_EVENODD) { + // Even-odd + while (e != NULL) { + if (w == 0) { + // if we're currently at zero, we need to record the edge start point + x0 = e->x; w = 1; + } else { + int x1 = e->x; w = 0; + nsvg__fillScanline(scanline, len, x0, x1, maxWeight, xmin, xmax); + } + e = e->next; + } + } +} + +static float nsvg__clampf(float a, float mn, float mx) { + if (isnan(a)) + return mn; + return a < mn ? mn : (a > mx ? mx : a); +} + +static unsigned int nsvg__RGBA(unsigned char r, unsigned char g, unsigned char b, unsigned char a) +{ + return ((unsigned int)r) | ((unsigned int)g << 8) | ((unsigned int)b << 16) | ((unsigned int)a << 24); +} + +static unsigned int nsvg__lerpRGBA(unsigned int c0, unsigned int c1, float u) +{ + int iu = (int)(nsvg__clampf(u, 0.0f, 1.0f) * 256.0f); + int r = (((c0) & 0xff)*(256-iu) + (((c1) & 0xff)*iu)) >> 8; + int g = (((c0>>8) & 0xff)*(256-iu) + (((c1>>8) & 0xff)*iu)) >> 8; + int b = (((c0>>16) & 0xff)*(256-iu) + (((c1>>16) & 0xff)*iu)) >> 8; + int a = (((c0>>24) & 0xff)*(256-iu) + (((c1>>24) & 0xff)*iu)) >> 8; + return nsvg__RGBA((unsigned char)r, (unsigned char)g, (unsigned char)b, (unsigned char)a); +} + +static unsigned int nsvg__applyOpacity(unsigned int c, float u) +{ + int iu = (int)(nsvg__clampf(u, 0.0f, 1.0f) * 256.0f); + int r = (c) & 0xff; + int g = (c>>8) & 0xff; + int b = (c>>16) & 0xff; + int a = (((c>>24) & 0xff)*iu) >> 8; + return nsvg__RGBA((unsigned char)r, (unsigned char)g, (unsigned char)b, (unsigned char)a); +} + +static inline int nsvg__div255(int x) +{ + return ((x+1) * 257) >> 16; +} + +static void nsvg__scanlineSolid(unsigned char* dst, int count, unsigned char* cover, int x, int y, + float tx, float ty, float scale, NSVGcachedPaint* cache) +{ + + if (cache->type == NSVG_PAINT_COLOR) { + int i, cr, cg, cb, ca; + cr = cache->colors[0] & 0xff; + cg = (cache->colors[0] >> 8) & 0xff; + cb = (cache->colors[0] >> 16) & 0xff; + ca = (cache->colors[0] >> 24) & 0xff; + + for (i = 0; i < count; i++) { + int r,g,b; + int a = nsvg__div255((int)cover[0] * ca); + int ia = 255 - a; + // Premultiply + r = nsvg__div255(cr * a); + g = nsvg__div255(cg * a); + b = nsvg__div255(cb * a); + + // Blend over + r += nsvg__div255(ia * (int)dst[0]); + g += nsvg__div255(ia * (int)dst[1]); + b += nsvg__div255(ia * (int)dst[2]); + a += nsvg__div255(ia * (int)dst[3]); + + dst[0] = (unsigned char)r; + dst[1] = (unsigned char)g; + dst[2] = (unsigned char)b; + dst[3] = (unsigned char)a; + + cover++; + dst += 4; + } + } else if (cache->type == NSVG_PAINT_LINEAR_GRADIENT) { + // TODO: spread modes. + // TODO: plenty of opportunities to optimize. + float fx, fy, dx, gy; + float* t = cache->xform; + int i, cr, cg, cb, ca; + unsigned int c; + + fx = ((float)x - tx) / scale; + fy = ((float)y - ty) / scale; + dx = 1.0f / scale; + + for (i = 0; i < count; i++) { + int r,g,b,a,ia; + gy = fx*t[1] + fy*t[3] + t[5]; + c = cache->colors[(int)nsvg__clampf(gy*255.0f, 0, 255.0f)]; + cr = (c) & 0xff; + cg = (c >> 8) & 0xff; + cb = (c >> 16) & 0xff; + ca = (c >> 24) & 0xff; + + a = nsvg__div255((int)cover[0] * ca); + ia = 255 - a; + + // Premultiply + r = nsvg__div255(cr * a); + g = nsvg__div255(cg * a); + b = nsvg__div255(cb * a); + + // Blend over + r += nsvg__div255(ia * (int)dst[0]); + g += nsvg__div255(ia * (int)dst[1]); + b += nsvg__div255(ia * (int)dst[2]); + a += nsvg__div255(ia * (int)dst[3]); + + dst[0] = (unsigned char)r; + dst[1] = (unsigned char)g; + dst[2] = (unsigned char)b; + dst[3] = (unsigned char)a; + + cover++; + dst += 4; + fx += dx; + } + } else if (cache->type == NSVG_PAINT_RADIAL_GRADIENT) { + // TODO: spread modes. + // TODO: plenty of opportunities to optimize. + // TODO: focus (fx,fy) + float fx, fy, dx, gx, gy, gd; + float* t = cache->xform; + int i, cr, cg, cb, ca; + unsigned int c; + + fx = ((float)x - tx) / scale; + fy = ((float)y - ty) / scale; + dx = 1.0f / scale; + + for (i = 0; i < count; i++) { + int r,g,b,a,ia; + gx = fx*t[0] + fy*t[2] + t[4]; + gy = fx*t[1] + fy*t[3] + t[5]; + gd = sqrtf(gx*gx + gy*gy); + c = cache->colors[(int)nsvg__clampf(gd*255.0f, 0, 255.0f)]; + cr = (c) & 0xff; + cg = (c >> 8) & 0xff; + cb = (c >> 16) & 0xff; + ca = (c >> 24) & 0xff; + + a = nsvg__div255((int)cover[0] * ca); + ia = 255 - a; + + // Premultiply + r = nsvg__div255(cr * a); + g = nsvg__div255(cg * a); + b = nsvg__div255(cb * a); + + // Blend over + r += nsvg__div255(ia * (int)dst[0]); + g += nsvg__div255(ia * (int)dst[1]); + b += nsvg__div255(ia * (int)dst[2]); + a += nsvg__div255(ia * (int)dst[3]); + + dst[0] = (unsigned char)r; + dst[1] = (unsigned char)g; + dst[2] = (unsigned char)b; + dst[3] = (unsigned char)a; + + cover++; + dst += 4; + fx += dx; + } + } +} + +static void nsvg__rasterizeSortedEdges(NSVGrasterizer *r, float tx, float ty, float scale, NSVGcachedPaint* cache, char fillRule) +{ + NSVGactiveEdge *active = NULL; + int y, s; + int e = 0; + int maxWeight = (255 / NSVG__SUBSAMPLES); // weight per vertical scanline + int xmin, xmax; + + for (y = 0; y < r->height; y++) { + memset(r->scanline, 0, r->width); + xmin = r->width; + xmax = 0; + for (s = 0; s < NSVG__SUBSAMPLES; ++s) { + // find center of pixel for this scanline + float scany = (float)(y*NSVG__SUBSAMPLES + s) + 0.5f; + NSVGactiveEdge **step = &active; + + // update all active edges; + // remove all active edges that terminate before the center of this scanline + while (*step) { + NSVGactiveEdge *z = *step; + if (z->ey <= scany) { + *step = z->next; // delete from list +// NSVG__assert(z->valid); + nsvg__freeActive(r, z); + } else { + z->x += z->dx; // advance to position for current scanline + step = &((*step)->next); // advance through list + } + } + + // resort the list if needed + for (;;) { + int changed = 0; + step = &active; + while (*step && (*step)->next) { + if ((*step)->x > (*step)->next->x) { + NSVGactiveEdge* t = *step; + NSVGactiveEdge* q = t->next; + t->next = q->next; + q->next = t; + *step = q; + changed = 1; + } + step = &(*step)->next; + } + if (!changed) break; + } + + // insert all edges that start before the center of this scanline -- omit ones that also end on this scanline + while (e < r->nedges && r->edges[e].y0 <= scany) { + if (r->edges[e].y1 > scany) { + NSVGactiveEdge* z = nsvg__addActive(r, &r->edges[e], scany); + if (z == NULL) break; + // find insertion point + if (active == NULL) { + active = z; + } else if (z->x < active->x) { + // insert at front + z->next = active; + active = z; + } else { + // find thing to insert AFTER + NSVGactiveEdge* p = active; + while (p->next && p->next->x < z->x) + p = p->next; + // at this point, p->next->x is NOT < z->x + z->next = p->next; + p->next = z; + } + } + e++; + } + + // now process all active edges in non-zero fashion + if (active != NULL) + nsvg__fillActiveEdges(r->scanline, r->width, active, maxWeight, &xmin, &xmax, fillRule); + } + // Blit + if (xmin < 0) xmin = 0; + if (xmax > r->width-1) xmax = r->width-1; + if (xmin <= xmax) { + nsvg__scanlineSolid(&r->bitmap[y * r->stride] + xmin*4, xmax-xmin+1, &r->scanline[xmin], xmin, y, tx,ty, scale, cache); + } + } + +} + +static void nsvg__unpremultiplyAlpha(unsigned char* image, int w, int h, int stride) +{ + int x,y; + + // Unpremultiply + for (y = 0; y < h; y++) { + unsigned char *row = &image[y*stride]; + for (x = 0; x < w; x++) { + int r = row[0], g = row[1], b = row[2], a = row[3]; + if (a != 0) { + row[0] = (unsigned char)(r*255/a); + row[1] = (unsigned char)(g*255/a); + row[2] = (unsigned char)(b*255/a); + } + row += 4; + } + } + + // Defringe + for (y = 0; y < h; y++) { + unsigned char *row = &image[y*stride]; + for (x = 0; x < w; x++) { + int r = 0, g = 0, b = 0, a = row[3], n = 0; + if (a == 0) { + if (x-1 > 0 && row[-1] != 0) { + r += row[-4]; + g += row[-3]; + b += row[-2]; + n++; + } + if (x+1 < w && row[7] != 0) { + r += row[4]; + g += row[5]; + b += row[6]; + n++; + } + if (y-1 > 0 && row[-stride+3] != 0) { + r += row[-stride]; + g += row[-stride+1]; + b += row[-stride+2]; + n++; + } + if (y+1 < h && row[stride+3] != 0) { + r += row[stride]; + g += row[stride+1]; + b += row[stride+2]; + n++; + } + if (n > 0) { + row[0] = (unsigned char)(r/n); + row[1] = (unsigned char)(g/n); + row[2] = (unsigned char)(b/n); + } + } + row += 4; + } + } +} + + +static void nsvg__initPaint(NSVGcachedPaint* cache, NSVGpaint* paint, float opacity) +{ + int i, j; + NSVGgradient* grad; + + cache->type = paint->type; + + if (paint->type == NSVG_PAINT_COLOR) { + cache->colors[0] = nsvg__applyOpacity(paint->color, opacity); + return; + } + + grad = paint->gradient; + + cache->spread = grad->spread; + memcpy(cache->xform, grad->xform, sizeof(float)*6); + + if (grad->nstops == 0) { + for (i = 0; i < 256; i++) + cache->colors[i] = 0; + } else if (grad->nstops == 1) { + unsigned int color = nsvg__applyOpacity(grad->stops[0].color, opacity); + for (i = 0; i < 256; i++) + cache->colors[i] = color; + } else { + unsigned int ca, cb = 0; + float ua, ub, du, u; + int ia, ib, count; + + ca = nsvg__applyOpacity(grad->stops[0].color, opacity); + ua = nsvg__clampf(grad->stops[0].offset, 0, 1); + ub = nsvg__clampf(grad->stops[grad->nstops-1].offset, ua, 1); + ia = (int)(ua * 255.0f); + ib = (int)(ub * 255.0f); + for (i = 0; i < ia; i++) { + cache->colors[i] = ca; + } + + for (i = 0; i < grad->nstops-1; i++) { + ca = nsvg__applyOpacity(grad->stops[i].color, opacity); + cb = nsvg__applyOpacity(grad->stops[i+1].color, opacity); + ua = nsvg__clampf(grad->stops[i].offset, 0, 1); + ub = nsvg__clampf(grad->stops[i+1].offset, 0, 1); + ia = (int)(ua * 255.0f); + ib = (int)(ub * 255.0f); + count = ib - ia; + if (count <= 0) continue; + u = 0; + du = 1.0f / (float)count; + for (j = 0; j < count; j++) { + cache->colors[ia+j] = nsvg__lerpRGBA(ca,cb,u); + u += du; + } + } + + for (i = ib; i < 256; i++) + cache->colors[i] = cb; + } + +} + +/* +static void dumpEdges(NSVGrasterizer* r, const char* name) +{ + float xmin = 0, xmax = 0, ymin = 0, ymax = 0; + NSVGedge *e = NULL; + int i; + if (r->nedges == 0) return; + FILE* fp = fopen(name, "w"); + if (fp == NULL) return; + + xmin = xmax = r->edges[0].x0; + ymin = ymax = r->edges[0].y0; + for (i = 0; i < r->nedges; i++) { + e = &r->edges[i]; + xmin = nsvg__minf(xmin, e->x0); + xmin = nsvg__minf(xmin, e->x1); + xmax = nsvg__maxf(xmax, e->x0); + xmax = nsvg__maxf(xmax, e->x1); + ymin = nsvg__minf(ymin, e->y0); + ymin = nsvg__minf(ymin, e->y1); + ymax = nsvg__maxf(ymax, e->y0); + ymax = nsvg__maxf(ymax, e->y1); + } + + fprintf(fp, "", xmin, ymin, (xmax - xmin), (ymax - ymin)); + + for (i = 0; i < r->nedges; i++) { + e = &r->edges[i]; + fprintf(fp ,"", e->x0,e->y0, e->x1,e->y1); + } + + for (i = 0; i < r->npoints; i++) { + if (i+1 < r->npoints) + fprintf(fp ,"", r->points[i].x, r->points[i].y, r->points[i+1].x, r->points[i+1].y); + fprintf(fp ,"", r->points[i].x, r->points[i].y, r->points[i].flags == 0 ? "#f00" : "#0f0"); + } + + fprintf(fp, ""); + fclose(fp); +} +*/ + +void nsvgRasterize(NSVGrasterizer* r, + NSVGimage* image, float tx, float ty, float scale, + unsigned char* dst, int w, int h, int stride) +{ + NSVGshape *shape = NULL; + NSVGedge *e = NULL; + NSVGcachedPaint cache; + int i; + int j; + unsigned char paintOrder; + + r->bitmap = dst; + r->width = w; + r->height = h; + r->stride = stride; + + if (w > r->cscanline) { + r->cscanline = w; + r->scanline = (unsigned char*)realloc(r->scanline, w); + if (r->scanline == NULL) return; + } + + for (i = 0; i < h; i++) + memset(&dst[i*stride], 0, w*4); + + for (shape = image->shapes; shape != NULL; shape = shape->next) { + if (!(shape->flags & NSVG_FLAGS_VISIBLE)) + continue; + + for (j = 0; j < 3; j++) { + paintOrder = (shape->paintOrder >> (2 * j)) & 0x03; + + if (paintOrder == NSVG_PAINT_FILL && shape->fill.type != NSVG_PAINT_NONE) { + nsvg__resetPool(r); + r->freelist = NULL; + r->nedges = 0; + + nsvg__flattenShape(r, shape, scale); + + // Scale and translate edges + for (i = 0; i < r->nedges; i++) { + e = &r->edges[i]; + e->x0 = tx + e->x0; + e->y0 = (ty + e->y0) * NSVG__SUBSAMPLES; + e->x1 = tx + e->x1; + e->y1 = (ty + e->y1) * NSVG__SUBSAMPLES; + } + + // Rasterize edges + if (r->nedges != 0) + qsort(r->edges, r->nedges, sizeof(NSVGedge), nsvg__cmpEdge); + + // now, traverse the scanlines and find the intersections on each scanline, use non-zero rule + nsvg__initPaint(&cache, &shape->fill, shape->opacity); + + nsvg__rasterizeSortedEdges(r, tx,ty,scale, &cache, shape->fillRule); + } + if (paintOrder == NSVG_PAINT_STROKE && shape->stroke.type != NSVG_PAINT_NONE && (shape->strokeWidth * scale) > 0.01f) { + nsvg__resetPool(r); + r->freelist = NULL; + r->nedges = 0; + + nsvg__flattenShapeStroke(r, shape, scale); + + // dumpEdges(r, "edge.svg"); + + // Scale and translate edges + for (i = 0; i < r->nedges; i++) { + e = &r->edges[i]; + e->x0 = tx + e->x0; + e->y0 = (ty + e->y0) * NSVG__SUBSAMPLES; + e->x1 = tx + e->x1; + e->y1 = (ty + e->y1) * NSVG__SUBSAMPLES; + } + + // Rasterize edges + if (r->nedges != 0) + qsort(r->edges, r->nedges, sizeof(NSVGedge), nsvg__cmpEdge); + + // now, traverse the scanlines and find the intersections on each scanline, use non-zero rule + nsvg__initPaint(&cache, &shape->stroke, shape->opacity); + + nsvg__rasterizeSortedEdges(r, tx,ty,scale, &cache, NSVG_FILLRULE_NONZERO); + } + } + } + + nsvg__unpremultiplyAlpha(dst, w, h, stride); + + r->bitmap = NULL; + r->width = 0; + r->height = 0; + r->stride = 0; +} + +#endif // NANOSVGRAST_IMPLEMENTATION + +#endif // NANOSVGRAST_H diff --git a/Modules/app-module/include/app/manager.h b/Modules/app-module/include/app/manager.h index 7a7e64966..a7b0d343d 100644 --- a/Modules/app-module/include/app/manager.h +++ b/Modules/app-module/include/app/manager.h @@ -61,6 +61,22 @@ error_t app_manager_add_package(const struct PackageManifest* package, const cha */ error_t app_manager_remove_package(const char* package_id); +/** + * Called after a package was registered or unregistered, on the thread that changed it and with no + * app-module lock held. Must not block: signal another task and return. + */ +typedef void (*AppPackageListenerFn)(void* context); + +/** + * Registers a listener for app_manager_add_package() and app_manager_remove_package(). + * @retval ERROR_ALREADY_EXISTS the same listener and context are registered already + * @retval ERROR_NONE on success + */ +error_t app_manager_add_package_listener(AppPackageListenerFn listener, void* context); + +/** Unregisters a listener added with app_manager_add_package_listener(). Does nothing when it isn't registered. */ +void app_manager_remove_package_listener(AppPackageListenerFn listener, void* context); + /** * @param[out] out_package set to a copy of the package on success * @retval ERROR_NOT_FOUND no package with this id is registered diff --git a/Modules/app-module/private/app/private/ledger.h b/Modules/app-module/private/app/private/ledger.h index 636e07a99..fd67137e0 100644 --- a/Modules/app-module/private/app/private/ledger.h +++ b/Modules/app-module/private/app/private/ledger.h @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -93,10 +94,16 @@ struct AppPackageRecord { std::vector> app_ids; }; +struct AppPackageListener { + AppPackageListenerFn function; + void* context; +}; + struct AppLedger { std::unordered_map manifests; std::unordered_map, std::equal_to, tt::OptExternalAllocator>> packages; std::unordered_map, std::equal_to, tt::OptExternalAllocator>> instances; + std::vector> package_listeners; uint32_t next_instance_id = 1; Mutex mutex {}; diff --git a/Modules/app-module/source/manager.cpp b/Modules/app-module/source/manager.cpp index dde95d662..2b98748a3 100644 --- a/Modules/app-module/source/manager.cpp +++ b/Modules/app-module/source/manager.cpp @@ -26,8 +26,41 @@ #define TAG "app_manager" +static void notify_package_listeners() { + auto& ledger = app_ledger(); + mutex_lock(&ledger.mutex); + const auto listeners = ledger.package_listeners; + mutex_unlock(&ledger.mutex); + for (const auto& listener : listeners) { + listener.function(listener.context); + } +} + extern "C" { +error_t app_manager_add_package_listener(AppPackageListenerFn listener, void* context) { + auto& ledger = app_ledger(); + mutex_lock(&ledger.mutex); + for (const auto& existing : ledger.package_listeners) { + if (existing.function == listener && existing.context == context) { + mutex_unlock(&ledger.mutex); + return ERROR_ALREADY_EXISTS; + } + } + ledger.package_listeners.push_back({ listener, context }); + mutex_unlock(&ledger.mutex); + return ERROR_NONE; +} + +void app_manager_remove_package_listener(AppPackageListenerFn listener, void* context) { + auto& ledger = app_ledger(); + mutex_lock(&ledger.mutex); + std::erase_if(ledger.package_listeners, [&](const AppPackageListener& existing) { + return existing.function == listener && existing.context == context; + }); + mutex_unlock(&ledger.mutex); +} + error_t app_manager_add(const AppManifest* manifest) { auto& ledger = app_ledger(); mutex_lock(&ledger.mutex); @@ -107,6 +140,7 @@ error_t app_manager_add_package(const PackageManifest* package, const char* cons ledger.packages[package->id] = std::move(record); mutex_unlock(&ledger.mutex); + notify_package_listeners(); return ERROR_NONE; } @@ -135,6 +169,7 @@ error_t app_manager_remove_package(const char* package_id) { ledger.packages.erase(iterator); mutex_unlock(&ledger.mutex); + notify_package_listeners(); return ERROR_NONE; } diff --git a/Modules/app-module/source/module.cpp b/Modules/app-module/source/module.cpp index dc77c8bfe..eeddc1105 100644 --- a/Modules/app-module/source/module.cpp +++ b/Modules/app-module/source/module.cpp @@ -80,6 +80,8 @@ static const ModuleSymbol SYMBOLS[] = { DEFINE_MODULE_SYMBOL(app_manager_remove), DEFINE_MODULE_SYMBOL(app_manager_add_package), DEFINE_MODULE_SYMBOL(app_manager_remove_package), + DEFINE_MODULE_SYMBOL(app_manager_add_package_listener), + DEFINE_MODULE_SYMBOL(app_manager_remove_package_listener), DEFINE_MODULE_SYMBOL(app_manager_find_package), DEFINE_MODULE_SYMBOL(app_manager_for_each_package), DEFINE_MODULE_SYMBOL(app_manager_get_topmost_instance_id), diff --git a/Modules/app-module/tests/source/manager_test.cpp b/Modules/app-module/tests/source/manager_test.cpp index dfe158045..53d50bd18 100644 --- a/Modules/app-module/tests/source/manager_test.cpp +++ b/Modules/app-module/tests/source/manager_test.cpp @@ -570,3 +570,27 @@ TEST_CASE("a package can't register an app id that another package has") { app_manager_remove_package("test.owner.first"); } + +TEST_CASE("package listeners are called when a package is added or removed") { + static int calls; + calls = 0; + auto listener = [](void* context) { (*static_cast(context))++; }; + REQUIRE_EQ(app_manager_add_package_listener(listener, &calls), ERROR_NONE); + CHECK_EQ(app_manager_add_package_listener(listener, &calls), ERROR_ALREADY_EXISTS); + + PackageManifest package {}; + strcpy(package.id, "test.listener.package"); + const char* const app_ids[] = { "test.listener.app" }; + REQUIRE_EQ(app_manager_add_package(&package, app_ids, 1), ERROR_NONE); + CHECK_EQ(calls, 1); + // A failed add doesn't notify + CHECK_EQ(app_manager_add_package(&package, app_ids, 1), ERROR_INVALID_ARGUMENT); + CHECK_EQ(calls, 1); + REQUIRE_EQ(app_manager_remove_package("test.listener.package"), ERROR_NONE); + CHECK_EQ(calls, 2); + + app_manager_remove_package_listener(listener, &calls); + REQUIRE_EQ(app_manager_add_package(&package, app_ids, 1), ERROR_NONE); + CHECK_EQ(calls, 2); + app_manager_remove_package("test.listener.package"); +} diff --git a/Modules/lvgl-module/CMakeLists.txt b/Modules/lvgl-module/CMakeLists.txt index e3f39e0d1..c184289d4 100644 --- a/Modules/lvgl-module/CMakeLists.txt +++ b/Modules/lvgl-module/CMakeLists.txt @@ -34,6 +34,7 @@ list(APPEND REQUIRES_LIST binfont-module lodepng-module lvgl + nanosvg QRCode ) diff --git a/Modules/lvgl-module/include/lvgl/svg.h b/Modules/lvgl-module/include/lvgl/svg.h new file mode 100644 index 000000000..120fc6905 --- /dev/null +++ b/Modules/lvgl-module/include/lvgl/svg.h @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +#include + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Rasterizes SVG text into a square ARGB8888 draw buffer, scaled to fit and centered. + * @param[in] data the SVG document + * @param[in] length the number of bytes in @a data + * @param[in] size width and height in pixels + * @return the draw buffer, to be freed with lv_draw_buf_destroy(), or NULL when the document can't be parsed + */ +lv_draw_buf_t* lvgl_svg_rasterize_data(const char* data, size_t length, uint32_t size); + +/** + * Rasterizes an SVG file into a square ARGB8888 draw buffer, scaled to fit and centered. + * Reads the file, so it must not be called on the LVGL thread. + * @param[in] path a file system path (not an LVGL drive path) + * @param[in] size width and height in pixels + * @return the draw buffer, to be freed with lv_draw_buf_destroy(), or NULL when the file can't be read or parsed + */ +lv_draw_buf_t* lvgl_svg_rasterize_file(const char* path, uint32_t size); + +/** + * Rasterizes a colour or a mono variant of an icon, from SVG text. + * The preferred variant is used when it can be parsed, otherwise the other one. + * @param[in] colour_data the colour variant, or NULL + * @param[in] mono_data the mono variant, or NULL + * @param[in] prefer_mono true on a mono theme + * @param[out] out_is_mono true when the mono variant was rasterized, so the caller can tint it with the theme colour. Can be NULL. + * @return the draw buffer, or NULL when neither variant exists or can be parsed + */ +lv_draw_buf_t* lvgl_svg_rasterize_variants( + const char* colour_data, size_t colour_length, + const char* mono_data, size_t mono_length, + bool prefer_mono, uint32_t size, bool* out_is_mono +); + +/** + * Same as lvgl_svg_rasterize_variants(), for files. Reads files, so it must not be called on the LVGL thread. + * @param[in] colour_path the colour variant or NULL, a file system path + * @param[in] mono_path the mono variant or NULL, a file system path + */ +lv_draw_buf_t* lvgl_svg_rasterize_file_variants( + const char* colour_path, const char* mono_path, + bool prefer_mono, uint32_t size, bool* out_is_mono +); + +#ifdef __cplusplus +} +#endif diff --git a/Modules/lvgl-module/source/svg.c b/Modules/lvgl-module/source/svg.c new file mode 100644 index 000000000..c9eab4723 --- /dev/null +++ b/Modules/lvgl-module/source/svg.c @@ -0,0 +1,125 @@ +// SPDX-License-Identifier: Apache-2.0 +#include + +#include +#include +#include + +#define NANOSVG_IMPLEMENTATION +#define NANOSVGRAST_IMPLEMENTATION +#include +#include + +#define SVG_DPI 96.0f + +lv_draw_buf_t* lvgl_svg_rasterize_data(const char* data, size_t length, uint32_t size) { + if (size == 0) return NULL; + + // nanosvg modifies the text it parses + char* text = malloc(length + 1); + if (text == NULL) return NULL; + memcpy(text, data, length); + text[length] = '\0'; + NSVGimage* image = nsvgParse(text, "px", SVG_DPI); + free(text); + if (image == NULL) return NULL; + + const float longest_side = image->width > image->height ? image->width : image->height; + if (longest_side <= 0.0f) { + nsvgDelete(image); + return NULL; + } + + NSVGrasterizer* rasterizer = nsvgCreateRasterizer(); + unsigned char* rgba = malloc((size_t)size * size * 4); + lv_draw_buf_t* draw_buf = lv_draw_buf_create(size, size, LV_COLOR_FORMAT_ARGB8888, LV_STRIDE_AUTO); + if (rasterizer == NULL || rgba == NULL || draw_buf == NULL) { + if (draw_buf != NULL) lv_draw_buf_destroy(draw_buf); + free(rgba); + if (rasterizer != NULL) nsvgDeleteRasterizer(rasterizer); + nsvgDelete(image); + return NULL; + } + + const float scale = (float)size / longest_side; + const float offset_x = ((float)size - image->width * scale) / 2.0f; + const float offset_y = ((float)size - image->height * scale) / 2.0f; + for (size_t i = 0; i < (size_t)size * size * 4; i++) { + rgba[i] = 0; + } + nsvgRasterize(rasterizer, image, offset_x, offset_y, scale, rgba, (int)size, (int)size, (int)size * 4); + + // nanosvg outputs RGBA bytes, LVGL's ARGB8888 is BGRA in memory + for (uint32_t y = 0; y < size; y++) { + const unsigned char* source = rgba + (size_t)y * size * 4; + lv_color32_t* target = (lv_color32_t*)(draw_buf->data + (size_t)y * draw_buf->header.stride); + for (uint32_t x = 0; x < size; x++) { + target[x].red = source[x * 4]; + target[x].green = source[x * 4 + 1]; + target[x].blue = source[x * 4 + 2]; + target[x].alpha = source[x * 4 + 3]; + } + } + + free(rgba); + nsvgDeleteRasterizer(rasterizer); + nsvgDelete(image); + return draw_buf; +} + +lv_draw_buf_t* lvgl_svg_rasterize_file(const char* path, uint32_t size) { + FILE* file = fopen(path, "rb"); + if (file == NULL) return NULL; + + lv_draw_buf_t* draw_buf = NULL; + if (fseek(file, 0, SEEK_END) == 0) { + const long length = ftell(file); + if (length > 0 && fseek(file, 0, SEEK_SET) == 0) { + char* data = malloc((size_t)length); + if (data != NULL) { + if (fread(data, 1, (size_t)length, file) == (size_t)length) { + draw_buf = lvgl_svg_rasterize_data(data, (size_t)length, size); + } + free(data); + } + } + } + fclose(file); + return draw_buf; +} + +lv_draw_buf_t* lvgl_svg_rasterize_variants( + const char* colour_data, size_t colour_length, + const char* mono_data, size_t mono_length, + bool prefer_mono, uint32_t size, bool* out_is_mono +) { + for (int attempt = 0; attempt < 2; attempt++) { + const bool mono = prefer_mono == (attempt == 0); + const char* data = mono ? mono_data : colour_data; + const size_t length = mono ? mono_length : colour_length; + if (data == NULL) continue; + lv_draw_buf_t* draw_buf = lvgl_svg_rasterize_data(data, length, size); + if (draw_buf != NULL) { + if (out_is_mono != NULL) *out_is_mono = mono; + return draw_buf; + } + } + return NULL; +} + +lv_draw_buf_t* lvgl_svg_rasterize_file_variants( + const char* colour_path, const char* mono_path, + bool prefer_mono, uint32_t size, bool* out_is_mono +) { + for (int attempt = 0; attempt < 2; attempt++) { + const bool mono = prefer_mono == (attempt == 0); + const char* path = mono ? mono_path : colour_path; + if (path == NULL) continue; + lv_draw_buf_t* draw_buf = lvgl_svg_rasterize_file(path, size); + if (draw_buf != NULL) { + if (out_is_mono != NULL) *out_is_mono = mono; + return draw_buf; + } + } + return NULL; +} diff --git a/Modules/lvgl-module/source/symbols.c b/Modules/lvgl-module/source/symbols.c index 2a4b9e871..2fc75312e 100644 --- a/Modules/lvgl-module/source/symbols.c +++ b/Modules/lvgl-module/source/symbols.c @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include diff --git a/Modules/lvgl-module/tests/CMakeLists.txt b/Modules/lvgl-module/tests/CMakeLists.txt index 66417dffa..bde6dddab 100644 --- a/Modules/lvgl-module/tests/CMakeLists.txt +++ b/Modules/lvgl-module/tests/CMakeLists.txt @@ -7,6 +7,7 @@ add_executable(LvglModuleTests EXCLUDE_FROM_ALL ${TEST_SOURCES} ${PROJECT_SOURCE_DIR}/../source/insets_math.cpp ${PROJECT_SOURCE_DIR}/../source/widgets/qr.cpp + ${PROJECT_SOURCE_DIR}/../source/svg.c # LVGL allocates through the kernel ${PROJECT_SOURCE_DIR}/../source/lv_mem_custom.c ) @@ -17,10 +18,13 @@ target_include_directories(LvglModuleTests PRIVATE ${PROJECT_SOURCE_DIR}/../private ) +target_compile_definitions(LvglModuleTests PRIVATE APP_ICON_DIR="${PROJECT_SOURCE_DIR}/../../../Data/system/app_icon" FILE_ICON_DIR="${PROJECT_SOURCE_DIR}/../../../Data/system/file_icon") + add_test(NAME LvglModuleTests COMMAND LvglModuleTests) target_link_libraries(LvglModuleTests PUBLIC TactilityKernel lvgl + nanosvg QRCode ) diff --git a/Modules/lvgl-module/tests/source/svg_test.cpp b/Modules/lvgl-module/tests/source/svg_test.cpp new file mode 100644 index 000000000..f75a54a2c --- /dev/null +++ b/Modules/lvgl-module/tests/source/svg_test.cpp @@ -0,0 +1,172 @@ +#include "doctest.h" + +#include +#include + +#include +#include +#include +#include + +static std::string writeSvg(const char* name, const char* content) { + std::string path = std::string("/tmp/") + name; + FILE* file = fopen(path.c_str(), "w"); + REQUIRE_NE(file, nullptr); + fputs(content, file); + fclose(file); + return path; +} + +static lv_color32_t pixelAt(const lv_draw_buf_t* buf, uint32_t x, uint32_t y) { + return reinterpret_cast(buf->data + y * buf->header.stride)[x]; +} + +TEST_CASE("lvgl_svg_rasterize_file draws a scaled, centered shape") { + lv_init(); + // A red square on a 10x10 canvas is scaled up to fill the 32x32 buffer + auto path = writeSvg("tt_svg_test_square.svg", + "" + ""); + + lv_draw_buf_t* buf = lvgl_svg_rasterize_file(path.c_str(), 32); + REQUIRE_NE(buf, nullptr); + CHECK_EQ(buf->header.w, 32); + CHECK_EQ(buf->header.h, 32); + auto center = pixelAt(buf, 16, 16); + CHECK_EQ(center.red, 255); + CHECK_EQ(center.green, 0); + CHECK_EQ(center.blue, 0); + CHECK_EQ(center.alpha, 255); + lv_draw_buf_destroy(buf); + remove(path.c_str()); + lv_deinit(); +} + +TEST_CASE("lvgl_svg_rasterize_file keeps the aspect ratio and leaves the rest transparent") { + lv_init(); + // A 20x10 shape is scaled to 32x16 and centered vertically + auto path = writeSvg("tt_svg_test_wide.svg", + "" + ""); + + lv_draw_buf_t* buf = lvgl_svg_rasterize_file(path.c_str(), 32); + REQUIRE_NE(buf, nullptr); + CHECK_EQ(pixelAt(buf, 16, 16).alpha, 255); + CHECK_EQ(pixelAt(buf, 16, 2).alpha, 0); + CHECK_EQ(pixelAt(buf, 16, 29).alpha, 0); + lv_draw_buf_destroy(buf); + remove(path.c_str()); + lv_deinit(); +} + +TEST_CASE("lvgl_svg_rasterize_file fails on missing and invalid files") { + lv_init(); + CHECK_EQ(lvgl_svg_rasterize_file("/tmp/tt_svg_test_missing.svg", 32), nullptr); + auto path = writeSvg("tt_svg_test_invalid.svg", "not an svg"); + CHECK_EQ(lvgl_svg_rasterize_file(path.c_str(), 32), nullptr); + CHECK_EQ(lvgl_svg_rasterize_file(path.c_str(), 0), nullptr); + remove(path.c_str()); + lv_deinit(); +} + +static int rasterizeAllIn(const char* directory) { + int count = 0; + for (const auto& entry : std::filesystem::directory_iterator(directory)) { + if (entry.path().extension() != ".svg") continue; + for (uint32_t size : { 24u, 48u }) { + lv_draw_buf_t* buf = lvgl_svg_rasterize_file(entry.path().c_str(), size); + INFO(entry.path().string()); + REQUIRE_NE(buf, nullptr); + bool visible = false; + for (uint32_t y = 0; y < size && !visible; y++) { + for (uint32_t x = 0; x < size; x++) { + if (pixelAt(buf, x, y).alpha > 0) { visible = true; break; } + } + } + CHECK(visible); + lv_draw_buf_destroy(buf); + } + count++; + } + return count; +} + +TEST_CASE("every app and file icon rasterizes to a visible image") { + lv_init(); + CHECK_EQ(rasterizeAllIn(APP_ICON_DIR), 58); + CHECK_EQ(rasterizeAllIn(FILE_ICON_DIR), 18); + lv_deinit(); +} + +static void checkEveryIconHasMonoVariant(const char* directory) { + for (const auto& entry : std::filesystem::directory_iterator(directory)) { + const auto stem = entry.path().stem().string(); + if (stem.ends_with("_mono")) continue; + INFO(entry.path().string()); + CHECK(std::filesystem::exists(entry.path().parent_path() / (stem + "_mono.svg"))); + } +} + +TEST_CASE("every colour icon has a mono variant") { + checkEveryIconHasMonoVariant(APP_ICON_DIR); + checkEveryIconHasMonoVariant(FILE_ICON_DIR); +} + +static const char* SQUARE = ""; + +TEST_CASE("lvgl_svg_rasterize_variants picks the variant of the theme and falls back to the other one") { + lv_init(); + const size_t length = strlen(SQUARE); + bool mono = false; + + lv_draw_buf_t* buf = lvgl_svg_rasterize_variants(SQUARE, length, SQUARE, length, true, 16, &mono); + REQUIRE_NE(buf, nullptr); + CHECK(mono); + lv_draw_buf_destroy(buf); + + buf = lvgl_svg_rasterize_variants(SQUARE, length, SQUARE, length, false, 16, &mono); + REQUIRE_NE(buf, nullptr); + CHECK_FALSE(mono); + lv_draw_buf_destroy(buf); + + // The mono variant is missing on a mono theme + buf = lvgl_svg_rasterize_variants(SQUARE, length, nullptr, 0, true, 16, &mono); + REQUIRE_NE(buf, nullptr); + CHECK_FALSE(mono); + lv_draw_buf_destroy(buf); + + // The colour variant is missing on a colour theme + buf = lvgl_svg_rasterize_variants(nullptr, 0, SQUARE, length, false, 16, &mono); + REQUIRE_NE(buf, nullptr); + CHECK(mono); + lv_draw_buf_destroy(buf); + + // The preferred variant can't be parsed + buf = lvgl_svg_rasterize_variants("invalid", 7, SQUARE, length, false, 16, &mono); + REQUIRE_NE(buf, nullptr); + CHECK(mono); + lv_draw_buf_destroy(buf); + + CHECK_EQ(lvgl_svg_rasterize_variants(nullptr, 0, nullptr, 0, true, 16, &mono), nullptr); + lv_deinit(); +} + +TEST_CASE("lvgl_svg_rasterize_file_variants falls back when a file is missing") { + lv_init(); + auto colour = writeSvg("tt_svg_test_variant.svg", SQUARE); + bool mono = true; + + lv_draw_buf_t* buf = lvgl_svg_rasterize_file_variants(colour.c_str(), "/tmp/tt_svg_test_variant_missing.svg", true, 16, &mono); + REQUIRE_NE(buf, nullptr); + CHECK_FALSE(mono); + lv_draw_buf_destroy(buf); + + buf = lvgl_svg_rasterize_file_variants(nullptr, colour.c_str(), false, 16, &mono); + REQUIRE_NE(buf, nullptr); + CHECK(mono); + lv_draw_buf_destroy(buf); + + CHECK_EQ(lvgl_svg_rasterize_file_variants("/tmp/tt_svg_test_a_missing.svg", "/tmp/tt_svg_test_b_missing.svg", true, 16, &mono), nullptr); + remove(colour.c_str()); + lv_deinit(); +} diff --git a/Tactility/Private/Tactility/app/TileGrid.h b/Tactility/Private/Tactility/app/TileGrid.h index fa2871dad..f168ea8cc 100644 --- a/Tactility/Private/Tactility/app/TileGrid.h +++ b/Tactility/Private/Tactility/app/TileGrid.h @@ -16,6 +16,10 @@ struct TileGridItem { const char* icon; /** Marked with a badge */ bool highlighted; + /** Shown instead of the icon glyph when set. Must outlive the tile. */ + const lv_image_dsc_t* image = nullptr; + /** Paints the image in the icon colour, for single colour images. Also applies to an image from Callbacks::resolveImage. */ + bool imageRecolor = false; }; /** @@ -34,8 +38,8 @@ class TileGrid final { void (*onLongPressed)(const TileGridItem& item, void* userData); /** Optional */ void (*onKey)(const TileGridItem& item, uint32_t key, void* userData); - /** Optional: returns the icon of an item without one. Only called for the items on the shown page. */ - const char* (*resolveIcon)(const TileGridItem& item, void* userData); + /** Optional: returns the image of an item without an icon or image. Only called for the items on the shown page. */ + const lv_image_dsc_t* (*resolveImage)(const TileGridItem& item, void* userData); /** Optional: called after the user went to another page */ void (*onPageChanged)(void* userData); void* userData; diff --git a/Tactility/Private/Tactility/app/files/View.h b/Tactility/Private/Tactility/app/files/View.h index 6109ff69c..cc988560f 100644 --- a/Tactility/Private/Tactility/app/files/View.h +++ b/Tactility/Private/Tactility/app/files/View.h @@ -31,6 +31,11 @@ class View final { AppStream inputDialogStream {}; uint8_t inputDialogBuffer[256] {}; + /** Rasterized file type icons, indexed by FileIcon. Freed after the widgets are gone. */ + lv_draw_buf_t* icons[9] = {}; + /** Mono icons are painted in the theme's icon colour */ + bool iconRecolor[9] = {}; + TileGrid grid; /** Shown in the toolbar while file operations are pending */ @@ -45,7 +50,7 @@ class View final { uint32_t installDialogId = 0; static std::vector collectItems(void* userData); - static const char* resolveIcon(const TileGridItem& item, void* userData); + static const lv_image_dsc_t* resolveImage(const TileGridItem& item, void* userData); static void onTileClicked(const TileGridItem& item, void* userData); static void onTileLongPressed(const TileGridItem& item, void* userData); static void onTileKey(const TileGridItem& item, uint32_t key, void* userData); @@ -90,6 +95,9 @@ class View final { /** Shows the directories that were read by the file operations task. Runs on the app task. */ void onFileOpsCompleted(); + /** Rasterizes the file type icons. Call before the widgets are created. */ + void loadIcons(); + void init(uint32_t appInstanceId, lv_obj_t* parent); /** Forgets the widgets, which are deleted when another window covers this one. Runs on the LVGL task with the lock held. */ void destroyWidgets(); diff --git a/Tactility/Private/Tactility/app/launcher/LauncherMode.h b/Tactility/Private/Tactility/app/launcher/LauncherMode.h index 37abab502..d34d4dce7 100644 --- a/Tactility/Private/Tactility/app/launcher/LauncherMode.h +++ b/Tactility/Private/Tactility/app/launcher/LauncherMode.h @@ -24,6 +24,27 @@ struct LauncherMode { /** Reads the favourites from their file into memory. File operation, see . */ void loadFavourites(void* context); +/** Rasterizes the icon.svg of every installed package into memory. File operation, see . */ +void loadPackageIcons(void* context); + +/** Rasterizes the icons of the settings apps into memory, once. File operation, see . */ +void loadSettingsIcons(void* context); + +/** @return true after loadSettingsIcons() ran */ +bool areSettingsIconsLoaded(); + +/** @return false when the app icons were rasterized for another theme (mono or colour) than the current one */ +bool areAppIconsCurrent(); + +/** @return false when the settings icons are not loaded, or were rasterized for another theme than the current one */ +bool areSettingsIconsCurrent(); + +/** + * The icon of apps that have none. Available after loadPackageIcons() ran, nullptr before. + * @param[out] recolor true when the icon is single colour and should be painted in the theme's icon colour + */ +const lv_image_dsc_t* defaultAppIcon(bool* recolor); + extern const LauncherMode APPS_MODE; extern const LauncherMode SETTINGS_MODE; diff --git a/Tactility/Source/app/TileGrid.cpp b/Tactility/Source/app/TileGrid.cpp index 4e15f3a69..e8a30a002 100644 --- a/Tactility/Source/app/TileGrid.cpp +++ b/Tactility/Source/app/TileGrid.cpp @@ -386,19 +386,35 @@ void TileGrid::populate() { lv_obj_set_flex_align(tile, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER); lv_obj_set_user_data(tile, const_cast(&item)); - lv_obj_t* icon = lv_label_create(tile); - lv_obj_set_style_text_font(icon, lvgl_get_shared_icon_large_font(), LV_STATE_DEFAULT); - lv_obj_set_style_text_align(icon, LV_TEXT_ALIGN_CENTER, LV_STATE_DEFAULT); - lv_obj_set_size(icon, layout.iconSize, layout.iconSize); - const char* icon_text = item.icon; - if (icon_text == nullptr && callbacks.resolveIcon != nullptr) { - icon_text = callbacks.resolveIcon(item, callbacks.userData); + const lv_image_dsc_t* image_src = item.image; + if (image_src == nullptr && item.icon == nullptr && callbacks.resolveImage != nullptr) { + image_src = callbacks.resolveImage(item, callbacks.userData); } - lv_label_set_text(icon, icon_text != nullptr ? icon_text : ""); - if (iconColor == IconColor::Primary) { - lv_obj_set_style_text_color(icon, lv_theme_get_color_primary(icon), LV_STATE_DEFAULT); - } else if (iconColor == IconColor::Secondary) { - lv_obj_set_style_text_color(icon, lv_theme_get_color_secondary(icon), LV_STATE_DEFAULT); + if (image_src != nullptr) { + lv_obj_t* image = lv_image_create(tile); + lv_image_set_src(image, image_src); + lv_obj_set_size(image, layout.iconSize, layout.iconSize); + if (item.imageRecolor) { + lv_color_t color = lv_obj_get_style_text_color(tile, LV_PART_MAIN); + if (iconColor == IconColor::Primary) { + color = lv_theme_get_color_primary(image); + } else if (iconColor == IconColor::Secondary) { + color = lv_theme_get_color_secondary(image); + } + lv_obj_set_style_image_recolor(image, color, LV_STATE_DEFAULT); + lv_obj_set_style_image_recolor_opa(image, LV_OPA_COVER, LV_STATE_DEFAULT); + } + } else { + lv_obj_t* icon = lv_label_create(tile); + lv_obj_set_style_text_font(icon, lvgl_get_shared_icon_large_font(), LV_STATE_DEFAULT); + lv_obj_set_style_text_align(icon, LV_TEXT_ALIGN_CENTER, LV_STATE_DEFAULT); + lv_obj_set_size(icon, layout.iconSize, layout.iconSize); + lv_label_set_text(icon, item.icon != nullptr ? item.icon : ""); + if (iconColor == IconColor::Primary) { + lv_obj_set_style_text_color(icon, lv_theme_get_color_primary(icon), LV_STATE_DEFAULT); + } else if (iconColor == IconColor::Secondary) { + lv_obj_set_style_text_color(icon, lv_theme_get_color_secondary(icon), LV_STATE_DEFAULT); + } } lv_obj_t* label = lv_label_create(tile); diff --git a/Tactility/Source/app/files/FilesApp.cpp b/Tactility/Source/app/files/FilesApp.cpp index 94ccee96d..2e6a172df 100644 --- a/Tactility/Source/app/files/FilesApp.cpp +++ b/Tactility/Source/app/files/FilesApp.cpp @@ -42,6 +42,7 @@ int32_t appMain(int argc, char* argv[]) { // The view releases its event group bit when it is destroyed, so it ends before the event group does { View view(state, &event_group); + view.loadIcons(); CreateContext createContext { &view, appInstanceId }; AppEventSubscription sub {}; diff --git a/Tactility/Source/app/files/View.cpp b/Tactility/Source/app/files/View.cpp index 1d26a6d2c..122900b4c 100644 --- a/Tactility/Source/app/files/View.cpp +++ b/Tactility/Source/app/files/View.cpp @@ -11,10 +11,14 @@ #include #include #include +#include +#include #include #include #include +#include + #include #include #include @@ -122,26 +126,50 @@ static bool isUsbMountPoint(const char* name) { return strncmp(name, "usb", 3) == 0 && isdigit((unsigned char)name[3]); } -// Returns nullptr for the files that View::resolveIcon() checks, as that reads the file -static const char* getIcon(const dirent& entry, bool isRoot) { +enum class FileIcon { Folder, SdCard, Usb, Link, Image, Text, App, Executable, File, Unknown }; + +struct FileIconAsset { + const uint8_t* colour; + size_t colourSize; + const uint8_t* mono; + size_t monoSize; +}; + +#define FILE_ICON_ASSET(name) { asset_file_icon_##name##_svg, asset_file_icon_##name##_svg_SIZE, asset_file_icon_##name##_mono_svg, asset_file_icon_##name##_mono_svg_SIZE } + +// Indexed by FileIcon, Unknown has no icon +constexpr FileIconAsset FILE_ICON_ASSETS[] = { + FILE_ICON_ASSET(folder), + FILE_ICON_ASSET(sd_card), + FILE_ICON_ASSET(usb), + FILE_ICON_ASSET(link), + FILE_ICON_ASSET(image), + FILE_ICON_ASSET(text), + FILE_ICON_ASSET(app), + FILE_ICON_ASSET(executable), + FILE_ICON_ASSET(file), +}; + +// Returns Unknown for the files that View::resolveImage() checks, as that reads the file +static FileIcon getIcon(const dirent& entry, bool isRoot) { if (entry.d_type == file::TT_DT_DIR || entry.d_type == file::TT_DT_CHR) { if (isRoot && strncmp(entry.d_name, "sd", 2) == 0) { - return LVGL_ICON_SHARED_SD_CARD; + return FileIcon::SdCard; } else if (isRoot && isUsbMountPoint(entry.d_name)) { - return LVGL_ICON_SHARED_USB; + return FileIcon::Usb; } else { - return LVGL_ICON_SHARED_FOLDER; + return FileIcon::Folder; } } else if (entry.d_type == file::TT_DT_LNK) { - return LVGL_ICON_SHARED_LINK; + return FileIcon::Link; } else if (isSupportedImageFile(entry.d_name)) { - return LVGL_ICON_SHARED_IMAGE; + return FileIcon::Image; } else if (isSupportedTextFile(entry.d_name)) { - return LVGL_ICON_SHARED_DESCRIPTION; + return FileIcon::Text; } else if (isSupportedAppFile(entry.d_name)) { - return LVGL_ICON_SHARED_DEPLOYED_CODE; + return FileIcon::App; } else { - return nullptr; + return FileIcon::Unknown; } } @@ -342,7 +370,7 @@ View::View(const std::shared_ptr& state, TaskEventGroup* eventGroup) : .onClicked = onTileClicked, .onLongPressed = onTileLongPressed, .onKey = onTileKey, - .resolveIcon = resolveIcon, + .resolveImage = resolveImage, .onPageChanged = onPageChanged, .userData = this }) { @@ -350,7 +378,26 @@ View::View(const std::shared_ptr& state, TaskEventGroup* eventGroup) : check(file_ops_subscribe(&fileOpsSub, eventGroup) == ERROR_NONE); } +void View::loadIcons() { + const auto size = static_cast(lvgl_get_shared_icon_large_font_height()); + const bool preferMono = lvgl_theme_is_mono(); + for (size_t i = 0; i < std::size(FILE_ICON_ASSETS); i++) { + const auto& asset = FILE_ICON_ASSETS[i]; + icons[i] = lvgl_svg_rasterize_variants( + reinterpret_cast(asset.colour), asset.colourSize, + reinterpret_cast(asset.mono), asset.monoSize, + preferMono, size, &iconRecolor[i] + ); + if (icons[i] == nullptr) { + LOG_W(TAG, "Failed to rasterize file icon %d", static_cast(i)); + } + } +} + View::~View() { + for (auto* icon : icons) { + if (icon != nullptr) lv_draw_buf_destroy(icon); + } file_ops_unsubscribe(&fileOpsSub); task_event_group_release_bit(eventGroup, pasteBit); } @@ -362,15 +409,20 @@ std::vector View::collectItems(void* userData) { view->state->withEntries([&](const std::vector& entries) { items.reserve(entries.size()); for (const auto& entry : entries) { - items.push_back({ entry.d_name, entry.d_name, getIcon(entry, is_root), false }); + const auto icon = getIcon(entry, is_root); + const lv_image_dsc_t* image = icon == FileIcon::Unknown ? nullptr : reinterpret_cast(view->icons[static_cast(icon)]); + // Files that are resolved later are shown as an executable or a plain file, which are rasterized from the same set + const bool recolor = view->iconRecolor[static_cast(icon == FileIcon::Unknown ? FileIcon::File : icon)]; + items.push_back({ entry.d_name, entry.d_name, nullptr, false, image, recolor }); } }); return items; } -const char* View::resolveIcon(const TileGridItem& item, void* userData) { +const lv_image_dsc_t* View::resolveImage(const TileGridItem& item, void* userData) { auto* view = static_cast(userData); - return view->state->isExecutable(item.id) ? LVGL_ICON_SHARED_PLAY_ARROW : LVGL_ICON_SHARED_DRAFT; + const auto icon = view->state->isExecutable(item.id) ? FileIcon::Executable : FileIcon::File; + return reinterpret_cast(view->icons[static_cast(icon)]); } void View::onTileClicked(const TileGridItem& item, void* userData) { diff --git a/Tactility/Source/app/launcher/AppsMode.cpp b/Tactility/Source/app/launcher/AppsMode.cpp index eeeaeb01f..8fdb347f9 100644 --- a/Tactility/Source/app/launcher/AppsMode.cpp +++ b/Tactility/Source/app/launcher/AppsMode.cpp @@ -1,17 +1,27 @@ #include #include +#include + +#include #include #include #include +#include #include +#include +#include +#include +#include #include #include +#include #include #include #include +#include #include #include @@ -36,30 +46,102 @@ void saveFavourites(void* context) { delete job; } -struct IconEntry { +struct BuiltInIconAsset { const char* id; - const char* icon; + const uint8_t* colour; + size_t colourSize; + const uint8_t* mono; + size_t monoSize; +}; + +#define BUILT_IN_ICON(id, name) { id, asset_app_icon_##name##_svg, asset_app_icon_##name##_svg_SIZE, asset_app_icon_##name##_mono_svg, asset_app_icon_##name##_mono_svg_SIZE } + +const BuiltInIconAsset BUILT_IN_ICONS[] = { + BUILT_IN_ICON("tactility.apphub", tactility_apphub), + BUILT_IN_ICON("tactility.camera", tactility_camera), + BUILT_IN_ICON("tactility.chat", tactility_chat), + BUILT_IN_ICON("tactility.files", tactility_files), + BUILT_IN_ICON("tactility.i2cscanner", tactility_i2cscanner), + BUILT_IN_ICON("tactility.maps", tactility_maps), + BUILT_IN_ICON("tactility.meshchannels", tactility_meshchannels), + BUILT_IN_ICON("tactility.meshcontacts", tactility_meshcontacts), + BUILT_IN_ICON("tactility.notes", tactility_notes), + BUILT_IN_ICON("tactility.systeminfo", tactility_systeminfo), + BUILT_IN_ICON("tactility.terminal", tactility_terminal), }; -constexpr IconEntry ICONS[] = { - {"tactility.apphub", LVGL_ICON_SHARED_DOWNLOAD}, - {"tactility.camera", LVGL_ICON_SHARED_CAMERA}, - {"tactility.chat", LVGL_ICON_SHARED_FORUM}, - {"tactility.files", LVGL_ICON_SHARED_FOLDER}, - {"tactility.i2cscanner", LVGL_ICON_SHARED_CABLE}, - {"tactility.maps", LVGL_ICON_SHARED_MAP}, - {"tactility.meshchannels", LVGL_ICON_SHARED_FORUM}, - {"tactility.meshcontacts", LVGL_ICON_SHARED_FORUM}, - {"tactility.notes", LVGL_ICON_SHARED_EDIT_NOTE}, - {"tactility.systeminfo", LVGL_ICON_SHARED_DEVICES}, - {"tactility.terminal", LVGL_ICON_SHARED_TERMINAL}, +const BuiltInIconAsset DEFAULT_ICON = BUILT_IN_ICON("", default); + +constexpr auto* PACKAGE_ICON_FILE = "icon.svg"; +constexpr auto* PACKAGE_ICON_MONO_FILE = "icon_mono.svg"; + +struct PackageIcon { + std::string packageId; + std::vector appIds; + time_t modified; + lv_draw_buf_t* image; + // Mono icons are painted in the theme's icon colour + bool recolor; + // The theme the variant was picked for + bool forMono; }; -const char* appIcon(const ::AppManifest* manifest) { - for (const auto& entry : ICONS) { - if (!strcmp(manifest->id, entry.id)) return entry.icon; +// Written by loadPackageIcons() on the file operations task, read when collecting items on the LVGL thread +struct PackageIcons { + Mutex mutex; + std::vector icons; + // The icons of built-in apps and the one for apps without an icon + std::vector builtIn; + PackageIcon defaultIcon {}; + bool builtInLoaded = false; + bool builtInForMono = false; + // Replaced images may still be shown by tiles, so they are freed by the next load + std::vector retired; + + PackageIcons() { mutex_construct(&mutex); } +}; + +PackageIcons& packageIcons() { + static PackageIcons* instance = newObject(); + check(instance != nullptr); + return *instance; +} + +const lv_image_dsc_t* toImageDsc(const lv_draw_buf_t* image) { + return reinterpret_cast(image); +} + +const lv_image_dsc_t* packageIcon(const char* appId, bool* recolor) { + auto& state = packageIcons(); + const lv_image_dsc_t* image = nullptr; + mutex_lock(&state.mutex); + for (const auto& icon : state.icons) { + if (::std::ranges::find(icon.appIds, appId) != icon.appIds.end()) { + image = toImageDsc(icon.image); + *recolor = icon.recolor; + break; + } + } + mutex_unlock(&state.mutex); + return image; +} + +// Image of a built-in app, or the default one +const lv_image_dsc_t* builtInIcon(const char* appId, bool* recolor) { + auto& state = packageIcons(); + const lv_image_dsc_t* image = nullptr; + mutex_lock(&state.mutex); + const PackageIcon* found = &state.defaultIcon; + for (const auto& icon : state.builtIn) { + if (icon.packageId == appId) { + found = &icon; + break; + } } - return LVGL_ICON_SHARED_DEPLOYED_CODE; + image = toImageDsc(found->image); + *recolor = found->recolor; + mutex_unlock(&state.mutex); + return image; } bool isShown(const ::AppManifest& manifest) { @@ -106,7 +188,13 @@ std::vector collectItems() { std::vector items; items.reserve(collected.size()); for (const auto& manifest : collected) { - items.push_back({ manifest.id, manifest.name, appIcon(&manifest), Favourites::contains(favouriteIds, manifest.id) }); + bool recolor = false; + const lv_image_dsc_t* image = packageIcon(manifest.id, &recolor); + if (image == nullptr) { + image = builtInIcon(manifest.id, &recolor); + } + // The glyph is shown when the image failed to load + items.push_back({ manifest.id, manifest.name, LVGL_ICON_SHARED_DEPLOYED_CODE, Favourites::contains(favouriteIds, manifest.id), image, recolor }); } ::std::ranges::sort(items, [](const TileGridItem& a, const TileGridItem& b) { if (a.highlighted != b.highlighted) { @@ -152,10 +240,153 @@ void onKey(TileGrid& grid, const TileGridItem& item, uint32_t key) { } // namespace +const lv_image_dsc_t* defaultAppIcon(bool* recolor) { + auto& state = packageIcons(); + mutex_lock(&state.mutex); + const lv_image_dsc_t* image = toImageDsc(state.defaultIcon.image); + *recolor = state.defaultIcon.recolor; + mutex_unlock(&state.mutex); + return image; +} + +bool areAppIconsCurrent() { + auto& state = packageIcons(); + mutex_lock(&state.mutex); + const bool current = state.builtInLoaded && state.builtInForMono == lvgl_theme_is_mono(); + mutex_unlock(&state.mutex); + return current; +} + void loadFavourites(void*) { favourites.load(); } +namespace { + +struct PackageApps { + std::string packageId; + std::vector appIds; +}; + +void collectPackageApps(const AppPackage* package, void* context) { + auto* packages = static_cast*>(context); + PackageApps entry { package->package.id, {} }; + for (size_t i = 0; i < package->app_id_count; i++) { + entry.appIds.emplace_back(package->app_ids[i]); + } + packages->push_back(::std::move(entry)); +} + +PackageIcon rasterizeBuiltIn(const BuiltInIconAsset& asset, uint32_t size, bool preferMono) { + bool mono = false; + auto* image = lvgl_svg_rasterize_variants( + reinterpret_cast(asset.colour), asset.colourSize, + reinterpret_cast(asset.mono), asset.monoSize, + preferMono, size, &mono + ); + if (image == nullptr) { + LOG_W(TAG, "Failed to rasterize the icon of %s", asset.id); + } + return { asset.id, {}, 0, image, mono, preferMono }; +} + +// Replaces the built-in icons, which is needed on the first load and when the theme changed +void loadBuiltInIcons(PackageIcons& state, uint32_t size, bool preferMono) { + std::vector icons; + for (const auto& asset : BUILT_IN_ICONS) { + auto icon = rasterizeBuiltIn(asset, size, preferMono); + if (icon.image != nullptr) { + icons.push_back(::std::move(icon)); + } + } + auto defaultIcon = rasterizeBuiltIn(DEFAULT_ICON, size, preferMono); + + mutex_lock(&state.mutex); + for (const auto& icon : state.builtIn) { + state.retired.push_back(icon.image); + } + if (state.defaultIcon.image != nullptr) { + state.retired.push_back(state.defaultIcon.image); + } + state.builtIn = ::std::move(icons); + state.defaultIcon = ::std::move(defaultIcon); + state.builtInLoaded = true; + state.builtInForMono = preferMono; + mutex_unlock(&state.mutex); +} + +} // namespace + +void loadPackageIcons(void*) { + auto& state = packageIcons(); + for (auto* image : state.retired) { + lv_draw_buf_destroy(image); + } + state.retired.clear(); + + const auto size = static_cast(lvgl_get_shared_icon_large_font_height()); + const bool preferMono = lvgl_theme_is_mono(); + if (!state.builtInLoaded || state.builtInForMono != preferMono) { + loadBuiltInIcons(state, size, preferMono); + } + + std::vector packages; + app_manager_for_each_package(collectPackageApps, &packages); + + // Only this task changes the icons, so reading them here needs no lock + std::vector loaded; + std::vector reused(state.icons.size(), false); + for (auto& package : packages) { + char install_path[256]; + if (app_get_install_path(package.packageId.c_str(), install_path, sizeof(install_path)) != ERROR_NONE) continue; + + // Either variant can be missing: the other one is used instead + const std::string colour_path = std::string(install_path) + "/" + PACKAGE_ICON_FILE; + const std::string mono_path = std::string(install_path) + "/" + PACKAGE_ICON_MONO_FILE; + struct stat colour_stat; + struct stat mono_stat; + const bool has_colour = stat(colour_path.c_str(), &colour_stat) == 0; + const bool has_mono = stat(mono_path.c_str(), &mono_stat) == 0; + if (!has_colour && !has_mono) continue; + const time_t modified = ::std::max(has_colour ? colour_stat.st_mtime : 0, has_mono ? mono_stat.st_mtime : 0); + + // An unchanged icon keeps its image + bool found = false; + for (size_t i = 0; i < state.icons.size(); i++) { + const auto& existing = state.icons[i]; + if (existing.packageId == package.packageId && existing.modified == modified && existing.forMono == preferMono && existing.appIds == package.appIds) { + loaded.push_back(existing); + reused[i] = true; + found = true; + break; + } + } + if (found) continue; + + // One rasterized image per package, shared by its apps + bool mono = false; + lv_draw_buf_t* image = lvgl_svg_rasterize_file_variants( + has_colour ? colour_path.c_str() : nullptr, + has_mono ? mono_path.c_str() : nullptr, + preferMono, size, &mono + ); + if (image == nullptr) { + LOG_W(TAG, "Failed to load the icon of %s", package.packageId.c_str()); + continue; + } + loaded.push_back({ package.packageId, ::std::move(package.appIds), modified, image, mono, preferMono }); + } + + mutex_lock(&state.mutex); + for (size_t i = 0; i < state.icons.size(); i++) { + if (!reused[i]) { + state.retired.push_back(state.icons[i].image); + } + } + state.icons = ::std::move(loaded); + mutex_unlock(&state.mutex); +} + const LauncherMode APPS_MODE = { .buttonIcon = LVGL_ICON_SHARED_APPS, .iconColor = TileGrid::IconColor::Primary, diff --git a/Tactility/Source/app/launcher/Launcher.cpp b/Tactility/Source/app/launcher/Launcher.cpp index 09f40b58d..28c1274c6 100644 --- a/Tactility/Source/app/launcher/Launcher.cpp +++ b/Tactility/Source/app/launcher/Launcher.cpp @@ -1,9 +1,11 @@ #include #include +#include #include #include #include +#include #include #include #include @@ -52,6 +54,16 @@ Mode getOtherMode(Mode mode) { struct Context { Mode mode = Mode::Apps; + // Set while the widgets exist, accessed with the LVGL lock held + bool widgetsExist = false; + // Set by the package listener, handled by appMain + TaskEventGroup* eventGroup = nullptr; + uint32_t packagesChangedBit = 0; + std::atomic packagesChanged { false }; + // Set when the settings are shown before their icons are loaded + std::atomic settingsIconsRequested { false }; + // What the queued icon job loads + struct { bool packages; bool settings; } iconJob {}; lv_obj_t* modeButtonIcon = nullptr; lvgl::SystemBarsListenerId systemBarsListener = 0; TileGrid grid { TileGrid::Callbacks { @@ -59,14 +71,30 @@ struct Context { .onClicked = onAppClicked, .onLongPressed = onAppLongPressed, .onKey = onAppKey, - .resolveIcon = nullptr, + .resolveImage = nullptr, .onPageChanged = nullptr, .userData = this, } }; }; std::vector collectItems(void* userData) { - return getLauncherMode(static_cast(userData)->mode).collect(); + auto* ctx = static_cast(userData); + // The theme changed since the icons were rasterized: the file operations task rasterizes them again, then the grid is rebuilt + const bool appIconsOutdated = !areAppIconsCurrent(); + const bool settingsIconsOutdated = areSettingsIconsLoaded() && !areSettingsIconsCurrent(); + if (appIconsOutdated || settingsIconsOutdated) { + ctx->packagesChanged = ctx->packagesChanged || appIconsOutdated; + ctx->settingsIconsRequested = ctx->settingsIconsRequested || settingsIconsOutdated; + task_event_group_signal(ctx->eventGroup, ctx->packagesChangedBit); + } + return getLauncherMode(ctx->mode).collect(); +} + +// Runs on the thread that installs or removes the package +void onPackagesChanged(void* userData) { + auto* ctx = static_cast(userData); + ctx->packagesChanged = true; + task_event_group_signal(ctx->eventGroup, ctx->packagesChangedBit); } struct StartAppJob { @@ -118,6 +146,10 @@ void applyIconColor(Context* ctx) { void onModeButtonPressed(lv_event_t* e) { auto* ctx = static_cast(lv_event_get_user_data(e)); ctx->mode = getOtherMode(ctx->mode); + if (ctx->mode == Mode::Settings && !areSettingsIconsCurrent()) { + ctx->settingsIconsRequested = true; + task_event_group_signal(ctx->eventGroup, ctx->packagesChangedBit); + } applyIconColor(ctx); ctx->grid.showFirstPage(); ctx->grid.requestRepopulate(false); @@ -142,10 +174,12 @@ void createWidgets(lv_obj_t* parent, void* userData) { ctx->systemBarsListener = lvgl::systemBarsAddListener([ctx] { ctx->grid.setBarSideContainer(lvgl::systemBarsGetActionContainer()); }); + ctx->widgetsExist = true; } void destroyWidgets(void* userData) { auto* ctx = static_cast(userData); + ctx->widgetsExist = false; lvgl::systemBarsRemoveListener(ctx->systemBarsListener); ctx->systemBarsListener = 0; ctx->grid.destroyWidgets(); @@ -180,6 +214,19 @@ void runAutoStart(void*) { } } +// Rasterizes icons, so it runs on the file operations task +void loadIcons(void* context) { + auto* job = static_cast(context); + if (job->packages) loadPackageIcons(nullptr); + if (job->settings) loadSettingsIcons(nullptr); +} + +// Reads files, so it runs on the file operations task +void loadLauncherData(void*) { + loadFavourites(nullptr); + loadPackageIcons(nullptr); +} + int32_t appMain(int argc, char* argv[]) { uint32_t appInstanceId = app_scheduler_current_app_id(); @@ -193,11 +240,16 @@ int32_t appMain(int argc, char* argv[]) { check(file_ops_subscribe(&file_ops_sub, &event_group) == ERROR_NONE); Context ctx; + ctx.eventGroup = &event_group; + check(task_event_group_claim_bit(&event_group, &ctx.packagesChangedBit) == ERROR_NONE); + check(app_manager_add_package_listener(onPackagesChanged, &ctx) == ERROR_NONE); + WindowId window = 0; bool windowCreated = false; + bool iconsReloading = false; // The window is created once the favourites are loaded, so its first render has the final order - check(file_ops_queue(loadFavourites, nullptr, &file_ops_sub) == ERROR_NONE); + check(file_ops_queue(loadLauncherData, nullptr, &file_ops_sub) == ERROR_NONE); // The launcher is meant to stay resident (it's the home screen) - it only gives up its // thread when app-module's scheduler asks it to (e.g. another new-model app is started). @@ -211,6 +263,28 @@ int32_t appMain(int argc, char* argv[]) { check(file_ops_queue(runAutoStart, nullptr, nullptr) == ERROR_NONE); } + if (windowCreated && iconsReloading && file_ops_poll(&file_ops_sub) == ERROR_NONE) { + iconsReloading = false; + // A buried window has no widgets: it collects the items again when it surfaces + lvgl_lock(); + if (ctx.widgetsExist) { + ctx.grid.requestRepopulate(true); + } + lvgl_unlock(); + } + if (windowCreated && !iconsReloading) { + const bool packages = ctx.packagesChanged.exchange(false); + const bool settings = ctx.settingsIconsRequested.exchange(false); + if (packages || settings) { + ctx.iconJob = { packages, settings }; + if (file_ops_queue(loadIcons, &ctx.iconJob, &file_ops_sub) == ERROR_NONE) { + iconsReloading = true; + } else { + LOG_E(TAG, "Failed to queue loading the icons"); + } + } + } + bool shouldClose = false; AppEvent event {}; while (app_event_poll(&sub, &event) == ERROR_NONE) { @@ -225,6 +299,8 @@ int32_t appMain(int argc, char* argv[]) { if (windowCreated) { window_manager_remove(window); } + app_manager_remove_package_listener(onPackagesChanged, &ctx); + task_event_group_release_bit(&event_group, ctx.packagesChangedBit); file_ops_unsubscribe(&file_ops_sub); check(app_event_unsubscribe(&sub) == ERROR_NONE); task_event_group_destruct(&event_group); diff --git a/Tactility/Source/app/launcher/SettingsMode.cpp b/Tactility/Source/app/launcher/SettingsMode.cpp index 8ed7f47cf..07bf06c9d 100644 --- a/Tactility/Source/app/launcher/SettingsMode.cpp +++ b/Tactility/Source/app/launcher/SettingsMode.cpp @@ -3,7 +3,16 @@ #include #include +#include + +#include #include +#include +#include + +#include +#include +#include #include #include @@ -13,36 +22,78 @@ namespace tt::app::launcher { namespace { -struct IconEntry { +struct SettingsIconAsset { const char* id; - const char* icon; + const uint8_t* colour; + size_t colourSize; + const uint8_t* mono; + size_t monoSize; +}; + +#define SETTINGS_ICON(id, name) { id, asset_app_icon_##name##_svg, asset_app_icon_##name##_svg_SIZE, asset_app_icon_##name##_mono_svg, asset_app_icon_##name##_mono_svg_SIZE } + +const SettingsIconAsset SETTINGS_ICONS[] = { + SETTINGS_ICON("tactility.appearance", tactility_appearance), + SETTINGS_ICON("tactility.audiosettings", tactility_audiosettings), + SETTINGS_ICON("tactility.btmanage", tactility_btmanage), + SETTINGS_ICON("tactility.development", tactility_development), + SETTINGS_ICON("tactility.display", tactility_display), + SETTINGS_ICON("tactility.grovesettings", tactility_grovesettings), + SETTINGS_ICON("tactility.keyboardsettings", tactility_keyboardsettings), + SETTINGS_ICON("tactility.ledstripsettings", tactility_ledstripsettings), + SETTINGS_ICON("tactility.locationsettings", tactility_locationsettings), + SETTINGS_ICON("tactility.meshsettings", tactility_meshsettings), + SETTINGS_ICON("tactility.power", tactility_power), + SETTINGS_ICON("tactility.timedatesettings", tactility_timedatesettings), + SETTINGS_ICON("tactility.touchcalibration", tactility_touchcalibration), + SETTINGS_ICON("tactility.trackballsettings", tactility_trackballsettings), + SETTINGS_ICON("tactility.usbsettings", tactility_usbsettings), + SETTINGS_ICON("tactility.vibrationsettings", tactility_vibrationsettings), + SETTINGS_ICON("tactility.wifimanage", tactility_wifimanage), }; -constexpr IconEntry ICONS[] = { - {"tactility.appearance", LVGL_ICON_SHARED_PALETTE}, - {"tactility.audiosettings", LVGL_ICON_SHARED_MUSIC_NOTE}, - {"tactility.btmanage", LVGL_ICON_SHARED_BLUETOOTH}, - {"tactility.development", LVGL_ICON_SHARED_LOGO_DEV}, - {"tactility.display", LVGL_ICON_SHARED_DISPLAY_SETTINGS}, - {"tactility.grovesettings", LVGL_ICON_SHARED_CABLE}, - {"tactility.keyboardsettings", LVGL_ICON_SHARED_KEYBOARD_ALT}, - {"tactility.ledstripsettings", LVGL_ICON_SHARED_LIGHTSTRIP}, - {"tactility.locationsettings", LVGL_ICON_SHARED_LOCATION_ON}, - {"tactility.meshsettings", LVGL_ICON_SHARED_HUB}, - {"tactility.power", LVGL_ICON_SHARED_POWER_SETTINGS_NEW}, - {"tactility.timedatesettings", LVGL_ICON_SHARED_CALENDAR_MONTH}, - {"tactility.touchcalibration", LVGL_ICON_SHARED_CIRCLE}, - {"tactility.trackballsettings", LVGL_ICON_SHARED_DEVICES}, - {"tactility.usbsettings", LVGL_ICON_SHARED_USB}, - {"tactility.vibrationsettings", LVGL_ICON_SHARED_PHONE_ANDROID}, - {"tactility.wifimanage", LVGL_ICON_SHARED_WIFI}, +constexpr size_t SETTINGS_ICON_COUNT = sizeof(SETTINGS_ICONS) / sizeof(SETTINGS_ICONS[0]); + +// Written by loadSettingsIcons() on the file operations task, read when collecting items on the LVGL thread +struct SettingsIcons { + Mutex mutex; + lv_draw_buf_t* images[SETTINGS_ICON_COUNT] = {}; + // Mono icons are painted in the theme's icon colour + bool recolor[SETTINGS_ICON_COUNT] = {}; + bool loaded = false; + bool forMono = false; + // Replaced images may still be shown by tiles, so they are freed by the next load + lv_draw_buf_t* retired[SETTINGS_ICON_COUNT] = {}; + + SettingsIcons() { mutex_construct(&mutex); } }; -const char* appIcon(const ::AppManifest* manifest) { - for (const auto& entry : ICONS) { - if (!strcmp(manifest->id, entry.id)) return entry.icon; +SettingsIcons& settingsIcons() { + static SettingsIcons* instance = newObject(); + check(instance != nullptr); + return *instance; +} + +// Returns the default icon for apps without one, or nullptr until the icons are loaded +const lv_image_dsc_t* settingsIcon(const char* appId, bool* recolor) { + auto& state = settingsIcons(); + mutex_lock(&state.mutex); + const bool loaded = state.loaded; + const lv_image_dsc_t* image = nullptr; + if (loaded) { + for (size_t i = 0; i < SETTINGS_ICON_COUNT; i++) { + if (!strcmp(appId, SETTINGS_ICONS[i].id)) { + image = reinterpret_cast(state.images[i]); + *recolor = state.recolor[i]; + break; + } + } + } + mutex_unlock(&state.mutex); + if (loaded && image == nullptr) { + image = defaultAppIcon(recolor); } - return LVGL_ICON_SHARED_DEPLOYED_CODE; + return image; } void collectManifest(const ::AppManifest* manifest, void* context) { @@ -64,7 +115,10 @@ std::vector collectItems() { std::vector items; for (const auto& manifest : collected) { if (manifest.category == APP_CATEGORY_SETTINGS && (manifest.flags & APP_MANIFEST_FLAG_HIDDEN) == 0) { - items.push_back({ manifest.id, manifest.name, appIcon(&manifest), false }); + // The glyph is shown until the icons are loaded + bool recolor = false; + const lv_image_dsc_t* image = settingsIcon(manifest.id, &recolor); + items.push_back({ manifest.id, manifest.name, LVGL_ICON_SHARED_DEPLOYED_CODE, false, image, recolor }); } } return items; @@ -72,6 +126,57 @@ std::vector collectItems() { } // namespace +void loadSettingsIcons(void*) { + auto& state = settingsIcons(); + const bool preferMono = lvgl_theme_is_mono(); + // Only this task writes the icons, so reading them here needs no lock + if (state.loaded && state.forMono == preferMono) return; + + // Replaced images are freed now, as the tiles that showed them were rebuilt since + for (auto*& image : state.retired) { + if (image != nullptr) lv_draw_buf_destroy(image); + image = nullptr; + } + + const auto size = static_cast(lvgl_get_shared_icon_large_font_height()); + lv_draw_buf_t* images[SETTINGS_ICON_COUNT] = {}; + bool recolor[SETTINGS_ICON_COUNT] = {}; + for (size_t i = 0; i < SETTINGS_ICON_COUNT; i++) { + const auto& asset = SETTINGS_ICONS[i]; + images[i] = lvgl_svg_rasterize_variants( + reinterpret_cast(asset.colour), asset.colourSize, + reinterpret_cast(asset.mono), asset.monoSize, + preferMono, size, &recolor[i] + ); + } + + mutex_lock(&state.mutex); + for (size_t i = 0; i < SETTINGS_ICON_COUNT; i++) { + state.retired[i] = state.images[i]; + state.images[i] = images[i]; + state.recolor[i] = recolor[i]; + } + state.loaded = true; + state.forMono = preferMono; + mutex_unlock(&state.mutex); +} + +bool areSettingsIconsLoaded() { + auto& state = settingsIcons(); + mutex_lock(&state.mutex); + const bool loaded = state.loaded; + mutex_unlock(&state.mutex); + return loaded; +} + +bool areSettingsIconsCurrent() { + auto& state = settingsIcons(); + mutex_lock(&state.mutex); + const bool current = state.loaded && state.forMono == lvgl_theme_is_mono(); + mutex_unlock(&state.mutex); + return current; +} + const LauncherMode SETTINGS_MODE = { .buttonIcon = LVGL_ICON_SHARED_SETTINGS, .iconColor = TileGrid::IconColor::Secondary, From e530408553d8ab77c7def97174bfec382cc146d4 Mon Sep 17 00:00:00 2001 From: Ken Van Hoeylandt Date: Sat, 14 Nov 2026 00:15:39 +0100 Subject: [PATCH 02/12] Default colour fixc --- Tactility/Source/app/TileGrid.cpp | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/Tactility/Source/app/TileGrid.cpp b/Tactility/Source/app/TileGrid.cpp index e8a30a002..ee169a0f6 100644 --- a/Tactility/Source/app/TileGrid.cpp +++ b/Tactility/Source/app/TileGrid.cpp @@ -410,11 +410,8 @@ void TileGrid::populate() { lv_obj_set_style_text_align(icon, LV_TEXT_ALIGN_CENTER, LV_STATE_DEFAULT); lv_obj_set_size(icon, layout.iconSize, layout.iconSize); lv_label_set_text(icon, item.icon != nullptr ? item.icon : ""); - if (iconColor == IconColor::Primary) { - lv_obj_set_style_text_color(icon, lv_theme_get_color_primary(icon), LV_STATE_DEFAULT); - } else if (iconColor == IconColor::Secondary) { - lv_obj_set_style_text_color(icon, lv_theme_get_color_secondary(icon), LV_STATE_DEFAULT); - } + // A placeholder for an image that isn't loaded yet has the theme's text colour + lv_obj_set_style_text_color(icon, lv_obj_get_style_text_color(tile, LV_PART_MAIN), LV_STATE_DEFAULT); } lv_obj_t* label = lv_label_create(tile); From ab484f21211cf3ce5fc05e66bdb6e23a7cb386fd Mon Sep 17 00:00:00 2001 From: Ken Van Hoeylandt Date: Sat, 14 Nov 2026 00:31:58 +0100 Subject: [PATCH 03/12] Disable svg loading when no PSRAM available on ESP32 --- .../Tactility/app/launcher/LauncherMode.h | 6 +++++ Tactility/Source/app/launcher/AppsMode.cpp | 24 +++++++++++++++---- .../Source/app/launcher/SettingsMode.cpp | 4 ++++ 3 files changed, 30 insertions(+), 4 deletions(-) diff --git a/Tactility/Private/Tactility/app/launcher/LauncherMode.h b/Tactility/Private/Tactility/app/launcher/LauncherMode.h index d34d4dce7..099c554b7 100644 --- a/Tactility/Private/Tactility/app/launcher/LauncherMode.h +++ b/Tactility/Private/Tactility/app/launcher/LauncherMode.h @@ -24,6 +24,12 @@ struct LauncherMode { /** Reads the favourites from their file into memory. File operation, see . */ void loadFavourites(void* context); +/** + * @return false on devices without PSRAM, where the SVG icons take too much memory. + * The tiles then show the fallback icon, and the icons are never loaded. + */ +bool areSvgIconsEnabled(); + /** Rasterizes the icon.svg of every installed package into memory. File operation, see . */ void loadPackageIcons(void* context); diff --git a/Tactility/Source/app/launcher/AppsMode.cpp b/Tactility/Source/app/launcher/AppsMode.cpp index 8fdb347f9..a20dad3e1 100644 --- a/Tactility/Source/app/launcher/AppsMode.cpp +++ b/Tactility/Source/app/launcher/AppsMode.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include @@ -185,15 +186,19 @@ std::vector collectItems() { return !isShown(manifest) || ::std::ranges::find(incompatibleIds, std::string(manifest.id)) != incompatibleIds.end(); }); + const bool svgIconsEnabled = areSvgIconsEnabled(); std::vector items; items.reserve(collected.size()); for (const auto& manifest : collected) { bool recolor = false; - const lv_image_dsc_t* image = packageIcon(manifest.id, &recolor); - if (image == nullptr) { - image = builtInIcon(manifest.id, &recolor); + const lv_image_dsc_t* image = nullptr; + if (svgIconsEnabled) { + image = packageIcon(manifest.id, &recolor); + if (image == nullptr) { + image = builtInIcon(manifest.id, &recolor); + } } - // The glyph is shown when the image failed to load + // The glyph is shown when the SVG icons are disabled or the image failed to load items.push_back({ manifest.id, manifest.name, LVGL_ICON_SHARED_DEPLOYED_CODE, Favourites::contains(favouriteIds, manifest.id), image, recolor }); } ::std::ranges::sort(items, [](const TileGridItem& a, const TileGridItem& b) { @@ -249,7 +254,16 @@ const lv_image_dsc_t* defaultAppIcon(bool* recolor) { return image; } +bool areSvgIconsEnabled() { +#ifdef ESP_PLATFORM + return memory_external_total() > 0; +#else + return true; +#endif +} + bool areAppIconsCurrent() { + if (!areSvgIconsEnabled()) return true; auto& state = packageIcons(); mutex_lock(&state.mutex); const bool current = state.builtInLoaded && state.builtInForMono == lvgl_theme_is_mono(); @@ -318,6 +332,8 @@ void loadBuiltInIcons(PackageIcons& state, uint32_t size, bool preferMono) { } // namespace void loadPackageIcons(void*) { + if (!areSvgIconsEnabled()) return; + auto& state = packageIcons(); for (auto* image : state.retired) { lv_draw_buf_destroy(image); diff --git a/Tactility/Source/app/launcher/SettingsMode.cpp b/Tactility/Source/app/launcher/SettingsMode.cpp index 07bf06c9d..11f63a390 100644 --- a/Tactility/Source/app/launcher/SettingsMode.cpp +++ b/Tactility/Source/app/launcher/SettingsMode.cpp @@ -127,6 +127,8 @@ std::vector collectItems() { } // namespace void loadSettingsIcons(void*) { + if (!areSvgIconsEnabled()) return; + auto& state = settingsIcons(); const bool preferMono = lvgl_theme_is_mono(); // Only this task writes the icons, so reading them here needs no lock @@ -170,6 +172,8 @@ bool areSettingsIconsLoaded() { } bool areSettingsIconsCurrent() { + if (!areSvgIconsEnabled()) return true; + auto& state = settingsIcons(); mutex_lock(&state.mutex); const bool current = state.loaded && state.forMono == lvgl_theme_is_mono(); From 631d67fcffdebd99ffe537e711f5ce170f7dc2ca Mon Sep 17 00:00:00 2001 From: Ken Van Hoeylandt Date: Sat, 14 Nov 2026 00:40:47 +0100 Subject: [PATCH 04/12] Fixes --- Devices/generic-esp32p4/device.properties | 2 +- Modules/app-module/include/app/manager.h | 6 +- Modules/app-module/include/app/paths.h | 11 ++ .../app-module/private/app/private/ledger.h | 16 ++- Modules/app-module/source/manager.cpp | 5 + Modules/app-module/source/module.cpp | 1 + Modules/app-module/source/paths.cpp | 18 +++- .../app-module/tests/source/manager_test.cpp | 101 ++++++++++++++++++ Modules/lvgl-module/include/lvgl/svg.h | 4 +- Modules/lvgl-module/source/svg.c | 4 +- Modules/lvgl-module/source/symbols.c | 6 ++ Modules/lvgl-module/tests/source/svg_test.cpp | 9 ++ Tactility/Private/Tactility/app/TileGrid.h | 2 + .../Tactility/app/launcher/LauncherMode.h | 7 ++ Tactility/Source/app/TileGrid.cpp | 3 + Tactility/Source/app/launcher/AppsMode.cpp | 42 +++++--- Tactility/Source/app/launcher/Launcher.cpp | 42 ++++++-- .../Source/app/launcher/SettingsMode.cpp | 24 +++-- 18 files changed, 264 insertions(+), 39 deletions(-) diff --git a/Devices/generic-esp32p4/device.properties b/Devices/generic-esp32p4/device.properties index 7c6147862..48522c58a 100644 --- a/Devices/generic-esp32p4/device.properties +++ b/Devices/generic-esp32p4/device.properties @@ -2,7 +2,7 @@ general.vendor=Generic general.name=ESP32-P4 hardware.target=ESP32P4 -hardware.flashSize=8MB +hardware.flashSize=16MB hardware.spiRam=false storage.path=/data diff --git a/Modules/app-module/include/app/manager.h b/Modules/app-module/include/app/manager.h index a7b0d343d..e75debec4 100644 --- a/Modules/app-module/include/app/manager.h +++ b/Modules/app-module/include/app/manager.h @@ -74,7 +74,11 @@ typedef void (*AppPackageListenerFn)(void* context); */ error_t app_manager_add_package_listener(AppPackageListenerFn listener, void* context); -/** Unregisters a listener added with app_manager_add_package_listener(). Does nothing when it isn't registered. */ +/** + * Unregisters a listener added with app_manager_add_package_listener(). Does nothing when it isn't registered. + * Waits for a notification that is running, so the listener and its context are no longer used when this returns. + * Don't call it while holding a lock that the listener needs. + */ void app_manager_remove_package_listener(AppPackageListenerFn listener, void* context); /** diff --git a/Modules/app-module/include/app/paths.h b/Modules/app-module/include/app/paths.h index 0042c956b..64b22df9b 100644 --- a/Modules/app-module/include/app/paths.h +++ b/Modules/app-module/include/app/paths.h @@ -30,6 +30,17 @@ error_t app_paths_get_user_data_directory(const char* app_id, char* out_path, si */ error_t app_paths_get_user_data_path(const char* app_id, const char* child_path, char* out_path, size_t out_path_size); +/** + * @brief Get the directory a package was installed in, resolved from where the app is registered: it holds manifest.properties, bin/ and assets/. No trailing "/". + * @param[in] app_id non-null app id + * @param[out] out_path buffer to store the path + * @param[in] out_path_size size of the output buffer + * @retval ERROR_NOT_FOUND if the app isn't registered or isn't loaded from a path + * @retval ERROR_BUFFER_OVERFLOW if out_path_size is too small + * @retval ERROR_NONE on success + */ +error_t app_paths_get_install_directory(const char* app_id, char* out_path, size_t out_path_size); + /** * @brief Get the assets directory for an app. Do not store configuration data here. No trailing "/". * @param[in] app_id non-null app id diff --git a/Modules/app-module/private/app/private/ledger.h b/Modules/app-module/private/app/private/ledger.h index fd67137e0..e772019de 100644 --- a/Modules/app-module/private/app/private/ledger.h +++ b/Modules/app-module/private/app/private/ledger.h @@ -11,6 +11,7 @@ #include #include +#include #include #include #include @@ -106,9 +107,18 @@ struct AppLedger { std::vector> package_listeners; uint32_t next_instance_id = 1; Mutex mutex {}; - - AppLedger() { mutex_construct(&mutex); } - ~AppLedger() { mutex_destruct(&mutex); } + // Held while the package listeners are called (not mutex, which the listeners must not be called under), + // so removing a listener waits for a notification that is running. Recursive: a listener can remove itself. + RecursiveMutex listener_dispatch_mutex {}; + + AppLedger() { + mutex_construct(&mutex); + recursive_mutex_construct(&listener_dispatch_mutex); + } + ~AppLedger() { + recursive_mutex_destruct(&listener_dispatch_mutex); + mutex_destruct(&mutex); + } }; inline AppLedger& app_ledger() { diff --git a/Modules/app-module/source/manager.cpp b/Modules/app-module/source/manager.cpp index 2b98748a3..f8fe8d334 100644 --- a/Modules/app-module/source/manager.cpp +++ b/Modules/app-module/source/manager.cpp @@ -28,12 +28,15 @@ static void notify_package_listeners() { auto& ledger = app_ledger(); + // Removing a listener waits for this, so a listener never runs after its removal returned + recursive_mutex_lock(&ledger.listener_dispatch_mutex); mutex_lock(&ledger.mutex); const auto listeners = ledger.package_listeners; mutex_unlock(&ledger.mutex); for (const auto& listener : listeners) { listener.function(listener.context); } + recursive_mutex_unlock(&ledger.listener_dispatch_mutex); } extern "C" { @@ -54,11 +57,13 @@ error_t app_manager_add_package_listener(AppPackageListenerFn listener, void* co void app_manager_remove_package_listener(AppPackageListenerFn listener, void* context) { auto& ledger = app_ledger(); + recursive_mutex_lock(&ledger.listener_dispatch_mutex); mutex_lock(&ledger.mutex); std::erase_if(ledger.package_listeners, [&](const AppPackageListener& existing) { return existing.function == listener && existing.context == context; }); mutex_unlock(&ledger.mutex); + recursive_mutex_unlock(&ledger.listener_dispatch_mutex); } error_t app_manager_add(const AppManifest* manifest) { diff --git a/Modules/app-module/source/module.cpp b/Modules/app-module/source/module.cpp index eeddc1105..9d476cf5b 100644 --- a/Modules/app-module/source/module.cpp +++ b/Modules/app-module/source/module.cpp @@ -102,6 +102,7 @@ static const ModuleSymbol SYMBOLS[] = { // app/paths DEFINE_MODULE_SYMBOL(app_paths_get_user_data_directory), DEFINE_MODULE_SYMBOL(app_paths_get_user_data_path), + DEFINE_MODULE_SYMBOL(app_paths_get_install_directory), DEFINE_MODULE_SYMBOL(app_paths_get_assets_directory), DEFINE_MODULE_SYMBOL(app_paths_get_assets_path), // app/scheduler diff --git a/Modules/app-module/source/paths.cpp b/Modules/app-module/source/paths.cpp index 8451195ff..c070d723d 100644 --- a/Modules/app-module/source/paths.cpp +++ b/Modules/app-module/source/paths.cpp @@ -56,7 +56,7 @@ error_t app_paths_get_user_data_path(const char* app_id, const char* child_path, return ERROR_NONE; } -error_t app_paths_get_assets_directory(const char* app_id, char* out_path, size_t out_path_size) { +error_t app_paths_get_install_directory(const char* app_id, char* out_path, size_t out_path_size) { AppManifest manifest; error_t error = app_manager_find_manifest(app_id, &manifest); if (error != ERROR_NONE) { @@ -72,7 +72,21 @@ error_t app_paths_get_assets_directory(const char* app_id, char* out_path, size_ return ERROR_NOT_FOUND; } - int written = std::snprintf(out_path, out_path_size, "%s/assets", install_dir.c_str()); + int written = std::snprintf(out_path, out_path_size, "%s", install_dir.c_str()); + if (written < 0 || (size_t)written >= out_path_size) { + return ERROR_BUFFER_OVERFLOW; + } + return ERROR_NONE; +} + +error_t app_paths_get_assets_directory(const char* app_id, char* out_path, size_t out_path_size) { + char install_dir[FILE_MAX_PATH_STRING_LENGTH]; + error_t error = app_paths_get_install_directory(app_id, install_dir, sizeof(install_dir)); + if (error != ERROR_NONE) { + return error; + } + + int written = std::snprintf(out_path, out_path_size, "%s/assets", install_dir); if (written < 0 || (size_t)written >= out_path_size) { return ERROR_BUFFER_OVERFLOW; } diff --git a/Modules/app-module/tests/source/manager_test.cpp b/Modules/app-module/tests/source/manager_test.cpp index 53d50bd18..7d146b976 100644 --- a/Modules/app-module/tests/source/manager_test.cpp +++ b/Modules/app-module/tests/source/manager_test.cpp @@ -2,12 +2,14 @@ #include #include +#include #include #include #include #include +#include #include #include @@ -594,3 +596,102 @@ TEST_CASE("package listeners are called when a package is added or removed") { CHECK_EQ(calls, 2); app_manager_remove_package("test.listener.package"); } + +TEST_CASE("app_paths_get_install_directory resolves the directory of the registered binary") { + AppManifest manifest { "test.paths.app", "Test Paths", APP_CATEGORY_USER, { APP_LOCATION_PATH, const_cast("/custom/root/mypackage/bin/linux-x86_64/app.so") } }; + REQUIRE_EQ(app_manager_add(&manifest), ERROR_NONE); + + char path[128]; + CHECK_EQ(app_paths_get_install_directory("test.paths.app", path, sizeof(path)), ERROR_NONE); + CHECK_EQ(std::string(path), "/custom/root/mypackage"); + CHECK_EQ(app_paths_get_assets_directory("test.paths.app", path, sizeof(path)), ERROR_NONE); + CHECK_EQ(std::string(path), "/custom/root/mypackage/assets"); + + char tiny[8]; + CHECK_EQ(app_paths_get_install_directory("test.paths.app", tiny, sizeof(tiny)), ERROR_BUFFER_OVERFLOW); + CHECK_EQ(app_paths_get_install_directory("test.paths.unknown", path, sizeof(path)), ERROR_NOT_FOUND); + app_manager_remove("test.paths.app"); + + AppManifest builtIn { "test.paths.builtin", "Test Builtin", APP_CATEGORY_USER, { APP_LOCATION_MEMORY, nullptr } }; + REQUIRE_EQ(app_manager_add(&builtIn), ERROR_NONE); + CHECK_EQ(app_paths_get_install_directory("test.paths.builtin", path, sizeof(path)), ERROR_NOT_FOUND); + app_manager_remove("test.paths.builtin"); +} + +TEST_CASE("a package listener can remove itself while it is called") { + static int calls; + calls = 0; + static auto listener = [](void* context) { + (*static_cast(context))++; + app_manager_remove_package_listener([](void* context) { (*static_cast(context))++; }, nullptr); + }; + // The removal inside the callback doesn't match this listener, so it must neither deadlock nor remove it + REQUIRE_EQ(app_manager_add_package_listener(listener, &calls), ERROR_NONE); + PackageManifest package {}; + strcpy(package.id, "test.selfremove.package"); + const char* const app_ids[] = { "test.selfremove.app" }; + REQUIRE_EQ(app_manager_add_package(&package, app_ids, 1), ERROR_NONE); + CHECK_EQ(calls, 1); + app_manager_remove_package_listener(listener, &calls); + app_manager_remove_package("test.selfremove.package"); + CHECK_EQ(calls, 1); +} + +namespace { + +struct ListenerWaitState { + std::atomic inCallback { false }; + std::atomic release { false }; + std::atomic callbackDone { false }; + std::atomic removed { false }; + PackageManifest package {}; + const char* const* appIds = nullptr; +}; + +void blockingListener(void* context) { + auto* state = static_cast(context); + state->inCallback = true; + while (!state->release) delay_millis(1); + state->callbackDone = true; +} + +} // namespace + +TEST_CASE("removing a package listener waits for a notification that is running") { + static ListenerWaitState state; + state.inCallback = false; + state.release = false; + state.callbackDone = false; + state.removed = false; + strcpy(state.package.id, "test.waitremove.package"); + static const char* const app_ids[] = { "test.waitremove.app" }; + state.appIds = app_ids; + REQUIRE_EQ(app_manager_add_package_listener(blockingListener, &state), ERROR_NONE); + + // The notification runs on the thread that adds the package + auto* notifier = thread_alloc_full("listener-notifier", 4096, [](void*) -> int32_t { + app_manager_add_package(&state.package, state.appIds, 1); + return 0; + }, nullptr, -1); + REQUIRE_EQ(thread_start(notifier), ERROR_NONE); + while (!state.inCallback) delay_millis(1); + + auto* remover = thread_alloc_full("listener-remover", 4096, [](void*) -> int32_t { + app_manager_remove_package_listener(blockingListener, &state); + state.removed = true; + return 0; + }, nullptr, -1); + REQUIRE_EQ(thread_start(remover), ERROR_NONE); + delay_millis(50); + // The callback still runs, so the removal must not have returned + CHECK_FALSE(state.removed); + + state.release = true; + CHECK_EQ(thread_join(remover, pdMS_TO_TICKS(2000), 1), ERROR_NONE); + CHECK_EQ(thread_join(notifier, pdMS_TO_TICKS(2000), 1), ERROR_NONE); + thread_free(remover); + thread_free(notifier); + CHECK(state.callbackDone); + CHECK(state.removed); + app_manager_remove_package("test.waitremove.package"); +} diff --git a/Modules/lvgl-module/include/lvgl/svg.h b/Modules/lvgl-module/include/lvgl/svg.h index 120fc6905..6f945fdf1 100644 --- a/Modules/lvgl-module/include/lvgl/svg.h +++ b/Modules/lvgl-module/include/lvgl/svg.h @@ -15,8 +15,8 @@ extern "C" { * Rasterizes SVG text into a square ARGB8888 draw buffer, scaled to fit and centered. * @param[in] data the SVG document * @param[in] length the number of bytes in @a data - * @param[in] size width and height in pixels - * @return the draw buffer, to be freed with lv_draw_buf_destroy(), or NULL when the document can't be parsed + * @param[in] size width and height in pixels, from 1 to 32767 + * @return the draw buffer, to be freed with lv_draw_buf_destroy(), or NULL when the document can't be parsed or the size is out of range */ lv_draw_buf_t* lvgl_svg_rasterize_data(const char* data, size_t length, uint32_t size); diff --git a/Modules/lvgl-module/source/svg.c b/Modules/lvgl-module/source/svg.c index c9eab4723..36079532d 100644 --- a/Modules/lvgl-module/source/svg.c +++ b/Modules/lvgl-module/source/svg.c @@ -11,9 +11,11 @@ #include #define SVG_DPI 96.0f +// (size_t)size * size * 4 must fit in size_t on 32-bit targets. +#define SVG_MAX_SIZE 32767u lv_draw_buf_t* lvgl_svg_rasterize_data(const char* data, size_t length, uint32_t size) { - if (size == 0) return NULL; + if (size == 0 || size > SVG_MAX_SIZE) return NULL; // nanosvg modifies the text it parses char* text = malloc(length + 1); diff --git a/Modules/lvgl-module/source/symbols.c b/Modules/lvgl-module/source/symbols.c index fd97b1de1..443e7168a 100644 --- a/Modules/lvgl-module/source/symbols.c +++ b/Modules/lvgl-module/source/symbols.c @@ -120,6 +120,11 @@ const struct ModuleSymbol lvgl_module_symbols[] = { DEFINE_MODULE_SYMBOL(lvgl_theme_is_mono), DEFINE_MODULE_SYMBOL(lvgl_theme_get_spacing), DEFINE_MODULE_SYMBOL(lvgl_theme_get_size), + // lvgl_svg + DEFINE_MODULE_SYMBOL(lvgl_svg_rasterize_data), + DEFINE_MODULE_SYMBOL(lvgl_svg_rasterize_file), + DEFINE_MODULE_SYMBOL(lvgl_svg_rasterize_variants), + DEFINE_MODULE_SYMBOL(lvgl_svg_rasterize_file_variants), // lvgl_badge DEFINE_MODULE_SYMBOL(lvgl_badge_create), // lvgl_focus_container @@ -645,6 +650,7 @@ const struct ModuleSymbol lvgl_module_symbols[] = { DEFINE_MODULE_SYMBOL(lv_malloc), // lv_draw DEFINE_MODULE_SYMBOL(lv_draw_buf_create), + DEFINE_MODULE_SYMBOL(lv_draw_buf_destroy), DEFINE_MODULE_SYMBOL(lv_draw_fill), DEFINE_MODULE_SYMBOL(lv_draw_fill_dsc_init), DEFINE_MODULE_SYMBOL(lv_draw_label), diff --git a/Modules/lvgl-module/tests/source/svg_test.cpp b/Modules/lvgl-module/tests/source/svg_test.cpp index f75a54a2c..e93c30070 100644 --- a/Modules/lvgl-module/tests/source/svg_test.cpp +++ b/Modules/lvgl-module/tests/source/svg_test.cpp @@ -170,3 +170,12 @@ TEST_CASE("lvgl_svg_rasterize_file_variants falls back when a file is missing") remove(colour.c_str()); lv_deinit(); } + +TEST_CASE("lvgl_svg_rasterize_data rejects sizes whose pixel buffer would overflow") { + lv_init(); + const size_t length = strlen(SQUARE); + CHECK_EQ(lvgl_svg_rasterize_data(SQUARE, length, 0), nullptr); + CHECK_EQ(lvgl_svg_rasterize_data(SQUARE, length, 32768), nullptr); + CHECK_EQ(lvgl_svg_rasterize_data(SQUARE, length, UINT32_MAX), nullptr); + lv_deinit(); +} diff --git a/Tactility/Private/Tactility/app/TileGrid.h b/Tactility/Private/Tactility/app/TileGrid.h index f168ea8cc..b713249e1 100644 --- a/Tactility/Private/Tactility/app/TileGrid.h +++ b/Tactility/Private/Tactility/app/TileGrid.h @@ -42,6 +42,8 @@ class TileGrid final { const lv_image_dsc_t* (*resolveImage)(const TileGridItem& item, void* userData); /** Optional: called after the user went to another page */ void (*onPageChanged)(void* userData); + /** Optional: called on every rebuild, after the old tiles were deleted and before collect. Nothing shows the images of earlier items anymore. */ + void (*onTilesCleared)(void* userData); void* userData; }; diff --git a/Tactility/Private/Tactility/app/launcher/LauncherMode.h b/Tactility/Private/Tactility/app/launcher/LauncherMode.h index 099c554b7..702638790 100644 --- a/Tactility/Private/Tactility/app/launcher/LauncherMode.h +++ b/Tactility/Private/Tactility/app/launcher/LauncherMode.h @@ -36,6 +36,13 @@ void loadPackageIcons(void* context); /** Rasterizes the icons of the settings apps into memory, once. File operation, see . */ void loadSettingsIcons(void* context); +/** + * Frees the icon images that a load replaced. Call it only when no tile shows them anymore: + * after the grid deleted its tiles, or when it has no widgets. Runs on any task. + */ +void releaseRetiredAppIcons(); +void releaseRetiredSettingsIcons(); + /** @return true after loadSettingsIcons() ran */ bool areSettingsIconsLoaded(); diff --git a/Tactility/Source/app/TileGrid.cpp b/Tactility/Source/app/TileGrid.cpp index ee169a0f6..e29111cd7 100644 --- a/Tactility/Source/app/TileGrid.cpp +++ b/Tactility/Source/app/TileGrid.cpp @@ -330,6 +330,9 @@ void TileGrid::populate() { // Old tiles hold pointers into items, so they are deleted before items is replaced. lv_obj_clean(grid); + if (callbacks.onTilesCleared != nullptr) { + callbacks.onTilesCleared(callbacks.userData); + } items = callbacks.collect(callbacks.userData); // Centers a full page of rows, so a partially filled last page keeps its rows in the same positions. diff --git a/Tactility/Source/app/launcher/AppsMode.cpp b/Tactility/Source/app/launcher/AppsMode.cpp index a20dad3e1..383ad9539 100644 --- a/Tactility/Source/app/launcher/AppsMode.cpp +++ b/Tactility/Source/app/launcher/AppsMode.cpp @@ -3,7 +3,7 @@ #include -#include +#include #include #include #include @@ -76,10 +76,19 @@ const BuiltInIconAsset DEFAULT_ICON = BUILT_IN_ICON("", default); constexpr auto* PACKAGE_ICON_FILE = "icon.svg"; constexpr auto* PACKAGE_ICON_MONO_FILE = "icon_mono.svg"; +// What was found for one icon file, to detect that it was added, removed or changed +struct IconFileStamp { + bool exists = false; + time_t modified = 0; + + bool operator==(const IconFileStamp&) const = default; +}; + struct PackageIcon { std::string packageId; std::vector appIds; - time_t modified; + IconFileStamp colourFile; + IconFileStamp monoFile; lv_draw_buf_t* image; // Mono icons are painted in the theme's icon colour bool recolor; @@ -96,7 +105,7 @@ struct PackageIcons { PackageIcon defaultIcon {}; bool builtInLoaded = false; bool builtInForMono = false; - // Replaced images may still be shown by tiles, so they are freed by the next load + // Replaced images may still be shown by tiles, so they are freed when the grid has deleted its tiles, see releaseRetiredAppIcons() std::vector retired; PackageIcons() { mutex_construct(&mutex); } @@ -262,6 +271,16 @@ bool areSvgIconsEnabled() { #endif } +void releaseRetiredAppIcons() { + auto& state = packageIcons(); + mutex_lock(&state.mutex); + for (auto* image : state.retired) { + lv_draw_buf_destroy(image); + } + state.retired.clear(); + mutex_unlock(&state.mutex); +} + bool areAppIconsCurrent() { if (!areSvgIconsEnabled()) return true; auto& state = packageIcons(); @@ -301,7 +320,7 @@ PackageIcon rasterizeBuiltIn(const BuiltInIconAsset& asset, uint32_t size, bool if (image == nullptr) { LOG_W(TAG, "Failed to rasterize the icon of %s", asset.id); } - return { asset.id, {}, 0, image, mono, preferMono }; + return { asset.id, {}, {}, {}, image, mono, preferMono }; } // Replaces the built-in icons, which is needed on the first load and when the theme changed @@ -335,10 +354,6 @@ void loadPackageIcons(void*) { if (!areSvgIconsEnabled()) return; auto& state = packageIcons(); - for (auto* image : state.retired) { - lv_draw_buf_destroy(image); - } - state.retired.clear(); const auto size = static_cast(lvgl_get_shared_icon_large_font_height()); const bool preferMono = lvgl_theme_is_mono(); @@ -353,8 +368,10 @@ void loadPackageIcons(void*) { std::vector loaded; std::vector reused(state.icons.size(), false); for (auto& package : packages) { + // The apps of a package share its directory, which depends on where the package was registered + if (package.appIds.empty()) continue; char install_path[256]; - if (app_get_install_path(package.packageId.c_str(), install_path, sizeof(install_path)) != ERROR_NONE) continue; + if (app_paths_get_install_directory(package.appIds.front().c_str(), install_path, sizeof(install_path)) != ERROR_NONE) continue; // Either variant can be missing: the other one is used instead const std::string colour_path = std::string(install_path) + "/" + PACKAGE_ICON_FILE; @@ -364,13 +381,14 @@ void loadPackageIcons(void*) { const bool has_colour = stat(colour_path.c_str(), &colour_stat) == 0; const bool has_mono = stat(mono_path.c_str(), &mono_stat) == 0; if (!has_colour && !has_mono) continue; - const time_t modified = ::std::max(has_colour ? colour_stat.st_mtime : 0, has_mono ? mono_stat.st_mtime : 0); + const IconFileStamp colour_file { has_colour, has_colour ? colour_stat.st_mtime : 0 }; + const IconFileStamp mono_file { has_mono, has_mono ? mono_stat.st_mtime : 0 }; // An unchanged icon keeps its image bool found = false; for (size_t i = 0; i < state.icons.size(); i++) { const auto& existing = state.icons[i]; - if (existing.packageId == package.packageId && existing.modified == modified && existing.forMono == preferMono && existing.appIds == package.appIds) { + if (existing.packageId == package.packageId && existing.colourFile == colour_file && existing.monoFile == mono_file && existing.forMono == preferMono && existing.appIds == package.appIds) { loaded.push_back(existing); reused[i] = true; found = true; @@ -390,7 +408,7 @@ void loadPackageIcons(void*) { LOG_W(TAG, "Failed to load the icon of %s", package.packageId.c_str()); continue; } - loaded.push_back({ package.packageId, ::std::move(package.appIds), modified, image, mono, preferMono }); + loaded.push_back({ package.packageId, ::std::move(package.appIds), colour_file, mono_file, image, mono, preferMono }); } mutex_lock(&state.mutex); diff --git a/Tactility/Source/app/launcher/Launcher.cpp b/Tactility/Source/app/launcher/Launcher.cpp index 28c1274c6..259e446e8 100644 --- a/Tactility/Source/app/launcher/Launcher.cpp +++ b/Tactility/Source/app/launcher/Launcher.cpp @@ -35,6 +35,7 @@ constexpr auto* TAG = "Launcher"; namespace { std::vector collectItems(void* userData); +void onTilesCleared(void* userData); void onAppClicked(const TileGridItem& item, void* userData); void onAppLongPressed(const TileGridItem& item, void* userData); void onAppKey(const TileGridItem& item, uint32_t key, void* userData); @@ -62,8 +63,6 @@ struct Context { std::atomic packagesChanged { false }; // Set when the settings are shown before their icons are loaded std::atomic settingsIconsRequested { false }; - // What the queued icon job loads - struct { bool packages; bool settings; } iconJob {}; lv_obj_t* modeButtonIcon = nullptr; lvgl::SystemBarsListenerId systemBarsListener = 0; TileGrid grid { TileGrid::Callbacks { @@ -73,6 +72,7 @@ struct Context { .onKey = onAppKey, .resolveImage = nullptr, .onPageChanged = nullptr, + .onTilesCleared = onTilesCleared, .userData = this, } }; }; @@ -83,13 +83,20 @@ std::vector collectItems(void* userData) { const bool appIconsOutdated = !areAppIconsCurrent(); const bool settingsIconsOutdated = areSettingsIconsLoaded() && !areSettingsIconsCurrent(); if (appIconsOutdated || settingsIconsOutdated) { - ctx->packagesChanged = ctx->packagesChanged || appIconsOutdated; - ctx->settingsIconsRequested = ctx->settingsIconsRequested || settingsIconsOutdated; + // Only set, never cleared: a package change from the listener can arrive at the same time + if (appIconsOutdated) ctx->packagesChanged = true; + if (settingsIconsOutdated) ctx->settingsIconsRequested = true; task_event_group_signal(ctx->eventGroup, ctx->packagesChangedBit); } return getLauncherMode(ctx->mode).collect(); } +// The tiles that showed replaced icon images are gone +void onTilesCleared(void*) { + releaseRetiredAppIcons(); + releaseRetiredSettingsIcons(); +} + // Runs on the thread that installs or removes the package void onPackagesChanged(void* userData) { auto* ctx = static_cast(userData); @@ -214,11 +221,19 @@ void runAutoStart(void*) { } } -// Rasterizes icons, so it runs on the file operations task +// What a queued icon job loads +struct IconJob { + bool packages; + bool settings; +}; + +// Rasterizes icons, so it runs on the file operations task, which frees the job. +// The job is not in the context of the app: queued work still runs after the app has closed. void loadIcons(void* context) { - auto* job = static_cast(context); + auto* job = static_cast(context); if (job->packages) loadPackageIcons(nullptr); if (job->settings) loadSettingsIcons(nullptr); + delete job; } // Reads files, so it runs on the file operations task @@ -266,9 +281,13 @@ int32_t appMain(int argc, char* argv[]) { if (windowCreated && iconsReloading && file_ops_poll(&file_ops_sub) == ERROR_NONE) { iconsReloading = false; // A buried window has no widgets: it collects the items again when it surfaces + // Replaced images are freed by the rebuild, or right away when there are no tiles lvgl_lock(); if (ctx.widgetsExist) { ctx.grid.requestRepopulate(true); + } else { + releaseRetiredAppIcons(); + releaseRetiredSettingsIcons(); } lvgl_unlock(); } @@ -276,11 +295,15 @@ int32_t appMain(int argc, char* argv[]) { const bool packages = ctx.packagesChanged.exchange(false); const bool settings = ctx.settingsIconsRequested.exchange(false); if (packages || settings) { - ctx.iconJob = { packages, settings }; - if (file_ops_queue(loadIcons, &ctx.iconJob, &file_ops_sub) == ERROR_NONE) { + auto* job = new (::std::nothrow) IconJob { packages, settings }; + if (job != nullptr && file_ops_queue(loadIcons, job, &file_ops_sub) == ERROR_NONE) { iconsReloading = true; } else { LOG_E(TAG, "Failed to queue loading the icons"); + delete job; + // Tried again when the next request arrives + if (packages) ctx.packagesChanged = true; + if (settings) ctx.settingsIconsRequested = true; } } } @@ -299,6 +322,9 @@ int32_t appMain(int argc, char* argv[]) { if (windowCreated) { window_manager_remove(window); } + // No tile shows an icon image anymore + releaseRetiredAppIcons(); + releaseRetiredSettingsIcons(); app_manager_remove_package_listener(onPackagesChanged, &ctx); task_event_group_release_bit(&event_group, ctx.packagesChangedBit); file_ops_unsubscribe(&file_ops_sub); diff --git a/Tactility/Source/app/launcher/SettingsMode.cpp b/Tactility/Source/app/launcher/SettingsMode.cpp index 11f63a390..96e74b665 100644 --- a/Tactility/Source/app/launcher/SettingsMode.cpp +++ b/Tactility/Source/app/launcher/SettingsMode.cpp @@ -62,8 +62,8 @@ struct SettingsIcons { bool recolor[SETTINGS_ICON_COUNT] = {}; bool loaded = false; bool forMono = false; - // Replaced images may still be shown by tiles, so they are freed by the next load - lv_draw_buf_t* retired[SETTINGS_ICON_COUNT] = {}; + // Replaced images may still be shown by tiles, so they are freed when the grid has deleted its tiles, see releaseRetiredSettingsIcons() + std::vector retired; SettingsIcons() { mutex_construct(&mutex); } }; @@ -134,12 +134,6 @@ void loadSettingsIcons(void*) { // Only this task writes the icons, so reading them here needs no lock if (state.loaded && state.forMono == preferMono) return; - // Replaced images are freed now, as the tiles that showed them were rebuilt since - for (auto*& image : state.retired) { - if (image != nullptr) lv_draw_buf_destroy(image); - image = nullptr; - } - const auto size = static_cast(lvgl_get_shared_icon_large_font_height()); lv_draw_buf_t* images[SETTINGS_ICON_COUNT] = {}; bool recolor[SETTINGS_ICON_COUNT] = {}; @@ -154,7 +148,9 @@ void loadSettingsIcons(void*) { mutex_lock(&state.mutex); for (size_t i = 0; i < SETTINGS_ICON_COUNT; i++) { - state.retired[i] = state.images[i]; + if (state.images[i] != nullptr) { + state.retired.push_back(state.images[i]); + } state.images[i] = images[i]; state.recolor[i] = recolor[i]; } @@ -163,6 +159,16 @@ void loadSettingsIcons(void*) { mutex_unlock(&state.mutex); } +void releaseRetiredSettingsIcons() { + auto& state = settingsIcons(); + mutex_lock(&state.mutex); + for (auto* image : state.retired) { + lv_draw_buf_destroy(image); + } + state.retired.clear(); + mutex_unlock(&state.mutex); +} + bool areSettingsIconsLoaded() { auto& state = settingsIcons(); mutex_lock(&state.mutex); From 2d81b72b13fdd16327e36b201cf5f1c6d54bb983 Mon Sep 17 00:00:00 2001 From: Ken Van Hoeylandt Date: Sat, 14 Nov 2026 10:51:15 +0100 Subject: [PATCH 05/12] Fixes --- Devices/cyd-2432s024c/device.properties | 1 + Devices/cyd-2432s024r/device.properties | 1 + Devices/cyd-2432s028r/device.properties | 3 +- Devices/cyd-2432s028rv2/device.properties | 3 +- Devices/cyd-2432s028rv3/device.properties | 3 +- Devices/cyd-2432s032c/device.properties | 1 + Devices/cyd-3248s035c/device.properties | 1 + Devices/cyd-8048s043c/device.properties | 3 - Devices/cyd-e32r28t/device.properties | 1 + Devices/cyd-e32r32p/device.properties | 1 + .../device.properties | 3 +- .../elecrow,crowpanel-advance-35.dts | 2 +- .../device.properties | 1 + .../device.properties | 5 +- .../elecrow,crowpanel-basic-35.dts | 2 +- .../device.properties | 1 + Devices/guition-jc2432w328c/device.properties | 1 + Devices/lilygo-tdeck-max/device.properties | 2 - .../bindings/ilitek,ili9488.yaml | 5 +- Drivers/ili9488-module/source/ili9488.cpp | 44 +++++-- Modules/app-module/include/app/manager.h | 1 + Modules/app-module/source/manager.cpp | 11 +- .../app-module/tests/source/manager_test.cpp | 78 ++++++++++++ Modules/binfont-module/source/generator.cpp | 5 +- Modules/cpp-symbols-module/CMakeLists.txt | 5 + .../source/function_instantiations.cpp | 20 +++ .../lvgl-module/source/devices/devices.cpp | 13 +- .../lvgl-module/source/widgets/toolbar.cpp | 3 + Platforms/platform-esp32/CMakeLists.txt | 2 +- Tactility/CMakeLists.txt | 27 ++++- .../app/touchcalibration/CalibrationMath.h | 42 +++++++ Tactility/Kconfig | 7 ++ Tactility/Private/Tactility/app/TileGrid.h | 8 ++ Tactility/Private/Tactility/app/files/View.h | 1 + .../Tactility/app/launcher/LauncherMode.h | 6 - Tactility/Source/InitModules.cpp | 4 + Tactility/Source/app/TileGrid.cpp | 22 +++- Tactility/Source/app/camera/Camera.cpp | 6 +- Tactility/Source/app/files/View.cpp | 27 ++++- Tactility/Source/app/launcher/AppsMode.cpp | 8 -- Tactility/Source/app/launcher/Launcher.cpp | 88 +++++++++++--- Tactility/Source/app/setup/Setup.cpp | 11 -- .../app/touchcalibration/CalibrationMath.cpp | 55 +++++++++ .../app/touchcalibration/TouchCalibration.cpp | 65 ++++++---- Tactility/Tests/CMakeLists.txt | 1 + .../Tests/Source/TouchCalibrationMathTest.cpp | 114 ++++++++++++++++++ TactilityKernel/include/tactility/memory.h | 12 +- TactilityKernel/source/memory.cpp | 12 ++ device.py | 9 ++ 49 files changed, 633 insertions(+), 114 deletions(-) create mode 100644 Tactility/Include/Tactility/app/touchcalibration/CalibrationMath.h create mode 100644 Tactility/Source/app/touchcalibration/CalibrationMath.cpp create mode 100644 Tactility/Tests/Source/TouchCalibrationMathTest.cpp diff --git a/Devices/cyd-2432s024c/device.properties b/Devices/cyd-2432s024c/device.properties index 548068e35..38ce9525b 100644 --- a/Devices/cyd-2432s024c/device.properties +++ b/Devices/cyd-2432s024c/device.properties @@ -4,6 +4,7 @@ general.name=2432S024C hardware.target=ESP32 hardware.flashSize=4MB hardware.spiRam=false +modules.audio=false storage.path=/sdcard diff --git a/Devices/cyd-2432s024r/device.properties b/Devices/cyd-2432s024r/device.properties index 35790c1b8..6bbf4d59d 100644 --- a/Devices/cyd-2432s024r/device.properties +++ b/Devices/cyd-2432s024r/device.properties @@ -4,6 +4,7 @@ general.name=2432S024R hardware.target=ESP32 hardware.flashSize=4MB hardware.spiRam=false +modules.audio=false storage.path=/sdcard diff --git a/Devices/cyd-2432s028r/device.properties b/Devices/cyd-2432s028r/device.properties index a378bcfb3..fc0efc405 100644 --- a/Devices/cyd-2432s028r/device.properties +++ b/Devices/cyd-2432s028r/device.properties @@ -4,6 +4,7 @@ general.name=2432S028R hardware.target=ESP32 hardware.flashSize=4MB hardware.spiRam=false +modules.audio=false storage.path=/sdcard @@ -13,8 +14,6 @@ display.dpi=143 touch.calibrationSupported=true touch.calibrationRequired=false -cdn.warningMessage=There are 3 hardware variants of this board. This build works on the original variant only ("v1"). - lvgl.colorDepth=16 lvgl.fsCacheSize=512 lvgl.uiSpacing=40 diff --git a/Devices/cyd-2432s028rv2/device.properties b/Devices/cyd-2432s028rv2/device.properties index b1bfedcbd..2dbe37f6f 100644 --- a/Devices/cyd-2432s028rv2/device.properties +++ b/Devices/cyd-2432s028rv2/device.properties @@ -5,6 +5,7 @@ general.incubating=true hardware.target=ESP32 hardware.flashSize=4MB hardware.spiRam=false +modules.audio=false storage.path=/sdcard @@ -14,7 +15,7 @@ display.dpi=143 touch.calibrationSupported=true touch.calibrationRequired=false -cdn.warningMessage=There are 3 hardware variants of this board. This build only supports board version 2. It has not been tested on real hardware yet. +cdn.warningMessage=This board has not been tested on real hardware yet. lvgl.colorDepth=16 lvgl.fsCacheSize=512 diff --git a/Devices/cyd-2432s028rv3/device.properties b/Devices/cyd-2432s028rv3/device.properties index 654a8b79f..98b101a40 100644 --- a/Devices/cyd-2432s028rv3/device.properties +++ b/Devices/cyd-2432s028rv3/device.properties @@ -4,6 +4,7 @@ general.name=2432S028R v3 hardware.target=ESP32 hardware.flashSize=4MB hardware.spiRam=false +modules.audio=false storage.path=/sdcard @@ -13,8 +14,6 @@ display.dpi=143 touch.calibrationSupported=true touch.calibrationRequired=false -cdn.warningMessage=There are 3 hardware variants of this board. This build only supports board version 3. - lvgl.colorDepth=16 lvgl.uiSpacing=40 lvgl.uiSize=60 diff --git a/Devices/cyd-2432s032c/device.properties b/Devices/cyd-2432s032c/device.properties index 7dfa5ed2f..22c3430c6 100644 --- a/Devices/cyd-2432s032c/device.properties +++ b/Devices/cyd-2432s032c/device.properties @@ -4,6 +4,7 @@ general.name=2432S032C hardware.target=ESP32 hardware.flashSize=4MB hardware.spiRam=false +modules.audio=false storage.path=/sdcard diff --git a/Devices/cyd-3248s035c/device.properties b/Devices/cyd-3248s035c/device.properties index 50066c7a1..d3aae0708 100644 --- a/Devices/cyd-3248s035c/device.properties +++ b/Devices/cyd-3248s035c/device.properties @@ -4,6 +4,7 @@ general.name=3248S035C hardware.target=ESP32 hardware.flashSize=4MB hardware.spiRam=false +modules.audio=false storage.path=/sdcard diff --git a/Devices/cyd-8048s043c/device.properties b/Devices/cyd-8048s043c/device.properties index 1fa95c483..e516f5d5b 100644 --- a/Devices/cyd-8048s043c/device.properties +++ b/Devices/cyd-8048s043c/device.properties @@ -15,9 +15,6 @@ storage.path=/sdcard display.size=4.3" display.dpi=217 -cdn.infoMessage= -cdn.warningMessage= - lvgl.theme=DefaultDark lvgl.colorDepth=16 lvgl.fontSize=18 diff --git a/Devices/cyd-e32r28t/device.properties b/Devices/cyd-e32r28t/device.properties index 5f8c66090..5915b1b0d 100644 --- a/Devices/cyd-e32r28t/device.properties +++ b/Devices/cyd-e32r28t/device.properties @@ -4,6 +4,7 @@ general.name=E32R28T hardware.target=ESP32 hardware.flashSize=4MB hardware.spiRam=false +modules.audio=false storage.path=/sdcard diff --git a/Devices/cyd-e32r32p/device.properties b/Devices/cyd-e32r32p/device.properties index 2a44d7458..ad255512c 100644 --- a/Devices/cyd-e32r32p/device.properties +++ b/Devices/cyd-e32r32p/device.properties @@ -4,6 +4,7 @@ general.name=E32R32P hardware.target=ESP32 hardware.flashSize=4MB hardware.spiRam=false +modules.audio=false storage.path=/sdcard diff --git a/Devices/elecrow-crowpanel-advance-35/device.properties b/Devices/elecrow-crowpanel-advance-35/device.properties index ec3b3b013..f20f2c564 100644 --- a/Devices/elecrow-crowpanel-advance-35/device.properties +++ b/Devices/elecrow-crowpanel-advance-35/device.properties @@ -15,8 +15,7 @@ storage.path=/sdcard display.size=3.5" display.dpi=165 -cdn.warningMessage=This device has display driver and memory issues. App Hub doesn't work. - lvgl.colorDepth=16 +lvgl.drawBufferLines=8 lvgl.uiSpacing=40 lvgl.uiSize=80 diff --git a/Devices/elecrow-crowpanel-advance-35/elecrow,crowpanel-advance-35.dts b/Devices/elecrow-crowpanel-advance-35/elecrow,crowpanel-advance-35.dts index 0438c652e..0e5ef925f 100644 --- a/Devices/elecrow-crowpanel-advance-35/elecrow,crowpanel-advance-35.dts +++ b/Devices/elecrow-crowpanel-advance-35/elecrow,crowpanel-advance-35.dts @@ -75,7 +75,7 @@ horizontal-resolution = <320>; vertical-resolution = <480>; invert-color; - color-conversion-buffer-size = <15360>; + color-conversion-buffer-size = <2560>; pixel-clock-hz = <40000000>; pin-dc = <&gpio0 41 GPIO_FLAG_NONE>; backlight = <&display_backlight>; diff --git a/Devices/elecrow-crowpanel-basic-28/device.properties b/Devices/elecrow-crowpanel-basic-28/device.properties index d7c3790b5..2f36dad5e 100644 --- a/Devices/elecrow-crowpanel-basic-28/device.properties +++ b/Devices/elecrow-crowpanel-basic-28/device.properties @@ -4,6 +4,7 @@ general.name=CrowPanel Basic 2.8" hardware.target=ESP32 hardware.flashSize=4MB hardware.spiRam=false +modules.audio=false storage.path=/sdcard diff --git a/Devices/elecrow-crowpanel-basic-35/device.properties b/Devices/elecrow-crowpanel-basic-35/device.properties index 627ec687f..2b9c135bb 100644 --- a/Devices/elecrow-crowpanel-basic-35/device.properties +++ b/Devices/elecrow-crowpanel-basic-35/device.properties @@ -4,6 +4,7 @@ general.name=CrowPanel Basic 3.5" hardware.target=ESP32 hardware.flashSize=4MB hardware.spiRam=false +modules.audio=false storage.path=/sdcard @@ -11,9 +12,7 @@ display.size=3.5" display.dpi=165 touch.calibrationSupported=true -touch.calibrationRequired=false - -cdn.warningMessage=This device has display driver and memory issues. App Hub doesn't work. +touch.calibrationRequired=true lvgl.colorDepth=16 lvgl.uiSpacing=40 diff --git a/Devices/elecrow-crowpanel-basic-35/elecrow,crowpanel-basic-35.dts b/Devices/elecrow-crowpanel-basic-35/elecrow,crowpanel-basic-35.dts index a3f06a14a..8bcc14e3f 100644 --- a/Devices/elecrow-crowpanel-basic-35/elecrow,crowpanel-basic-35.dts +++ b/Devices/elecrow-crowpanel-basic-35/elecrow,crowpanel-basic-35.dts @@ -63,7 +63,7 @@ compatible = "ilitek,ili9488"; horizontal-resolution = <320>; vertical-resolution = <480>; - color-conversion-buffer-size = <15360>; + color-conversion-buffer-size = <2560>; pixel-clock-hz = <40000000>; pin-dc = <&gpio0 2 GPIO_FLAG_NONE>; backlight = <&display_backlight>; diff --git a/Devices/elecrow-crowpanel-basic-50/device.properties b/Devices/elecrow-crowpanel-basic-50/device.properties index 6afff0668..0d833427c 100644 --- a/Devices/elecrow-crowpanel-basic-50/device.properties +++ b/Devices/elecrow-crowpanel-basic-50/device.properties @@ -9,6 +9,7 @@ hardware.spiRamSpeed=120M hardware.tinyUsbMsc=true hardware.esptoolFlashFreq=120M hardware.bluetooth=true +modules.audio=false storage.path=/sdcard diff --git a/Devices/guition-jc2432w328c/device.properties b/Devices/guition-jc2432w328c/device.properties index 4faea6cba..049b22011 100644 --- a/Devices/guition-jc2432w328c/device.properties +++ b/Devices/guition-jc2432w328c/device.properties @@ -4,6 +4,7 @@ general.name=JC2432W328C hardware.target=ESP32 hardware.flashSize=4MB hardware.spiRam=false +modules.audio=false storage.path=/sdcard diff --git a/Devices/lilygo-tdeck-max/device.properties b/Devices/lilygo-tdeck-max/device.properties index 1e18e9cf6..0372c3675 100644 --- a/Devices/lilygo-tdeck-max/device.properties +++ b/Devices/lilygo-tdeck-max/device.properties @@ -21,5 +21,3 @@ display.dpi=128 lvgl.colorDepth=8 lvgl.theme=Mono - -cdn.warningMessage=Display not reliably working. Use at your own risk. diff --git a/Drivers/ili9488-module/bindings/ilitek,ili9488.yaml b/Drivers/ili9488-module/bindings/ilitek,ili9488.yaml index bda157222..bd1b7b019 100644 --- a/Drivers/ili9488-module/bindings/ilitek,ili9488.yaml +++ b/Drivers/ili9488-module/bindings/ilitek,ili9488.yaml @@ -48,7 +48,10 @@ properties: color-conversion-buffer-size: type: int required: true - description: Size (in pixels) of the internal buffer used to convert 16bpp draw data to the panel's 18bpp format + description: | + Size (in pixels) of the internal buffer used to convert 16bpp draw data to the panel's 18bpp format. + It takes 3 bytes per pixel of internal RAM. A larger draw area is sent in strips that fit in it, + so it must be at least the larger of horizontal-resolution and vertical-resolution. pixel-clock-hz: type: int default: 40000000 diff --git a/Drivers/ili9488-module/source/ili9488.cpp b/Drivers/ili9488-module/source/ili9488.cpp index fd8ea4560..2a9900b21 100644 --- a/Drivers/ili9488-module/source/ili9488.cpp +++ b/Drivers/ili9488-module/source/ili9488.cpp @@ -18,6 +18,7 @@ #include +#include #include #define TAG "ILI9488" @@ -63,6 +64,12 @@ static error_t start(Device* device) { return ERROR_RESOURCE; } + // A draw area is sent in strips that fit in the conversion buffer, so a whole row or column has to fit in it + if (config->color_conversion_buffer_size < std::max(config->horizontal_resolution, config->vertical_resolution)) { + LOG_E(TAG, "color-conversion-buffer-size must be at least the larger resolution"); + return ERROR_INVALID_ARGUMENT; + } + auto* internal = static_cast(malloc(sizeof(Ili9488Internal))); if (internal == nullptr) { return ERROR_OUT_OF_MEMORY; @@ -220,21 +227,32 @@ static error_t ili9488_draw_bitmap(Device* device, int32_t x_start, int32_t y_st // satisfied by this draw's own transfer completing. xSemaphoreTake(internal->draw_done_semaphore, 0); + // The panel driver converts a whole area through its conversion buffer and doesn't check bounds, + // so a larger area is sent in strips of rows that fit in that buffer. The conversion buffer is + // reused by the next strip, which is why each strip is waited for. + const int32_t width = x_end - x_start; + const int32_t strip_rows = std::max(1, static_cast(GET_CONFIG(device)->color_conversion_buffer_size) / width); + const auto* pixels = static_cast(color_data); + spi_controller_lock(internal->spi_controller); - esp_err_t ret = esp_lcd_panel_draw_bitmap(internal->panel_handle, x_start, y_start, x_end, y_end, color_data); - if (ret != ESP_OK) { - spi_controller_unlock(internal->spi_controller); - return ERROR_RESOURCE; - } + for (int32_t y = y_start; y < y_end; y += strip_rows) { + const int32_t strip_end = std::min(y + strip_rows, y_end); + esp_err_t ret = esp_lcd_panel_draw_bitmap(internal->panel_handle, x_start, y, x_end, strip_end, pixels); + if (ret != ESP_OK) { + spi_controller_unlock(internal->spi_controller); + return ERROR_RESOURCE; + } - // Block until the SPI transfer physically completes: DisplayApi's draw_bitmap is a synchronous - // contract (see lvgl_display.c), so the caller must be able to safely reuse/overwrite - // color_data as soon as this call returns. esp_lcd_panel_draw_bitmap() only queues the - // transfer and returns once it's handed to the SPI peripheral, not once it's finished. Hold the - // bus lock across the wait too, not just the queueing call: the command/data phases aren't - // wrapped in their own acquire_bus by esp_lcd_panel_io_spi, so another bus user could otherwise - // interleave with this transfer while it's still in flight. - xSemaphoreTake(internal->draw_done_semaphore, portMAX_DELAY); + // Block until the SPI transfer physically completes: DisplayApi's draw_bitmap is a synchronous + // contract (see lvgl_display.c), so the caller must be able to safely reuse/overwrite + // color_data as soon as this call returns. esp_lcd_panel_draw_bitmap() only queues the + // transfer and returns once it's handed to the SPI peripheral, not once it's finished. Hold the + // bus lock across the wait too, not just the queueing call: the command/data phases aren't + // wrapped in their own acquire_bus by esp_lcd_panel_io_spi, so another bus user could otherwise + // interleave with this transfer while it's still in flight. + xSemaphoreTake(internal->draw_done_semaphore, portMAX_DELAY); + pixels += static_cast(strip_end - y) * width; + } spi_controller_unlock(internal->spi_controller); return ERROR_NONE; } diff --git a/Modules/app-module/include/app/manager.h b/Modules/app-module/include/app/manager.h index e75debec4..331a5f77d 100644 --- a/Modules/app-module/include/app/manager.h +++ b/Modules/app-module/include/app/manager.h @@ -77,6 +77,7 @@ error_t app_manager_add_package_listener(AppPackageListenerFn listener, void* co /** * Unregisters a listener added with app_manager_add_package_listener(). Does nothing when it isn't registered. * Waits for a notification that is running, so the listener and its context are no longer used when this returns. + * A listener that is removed by another listener during a notification is not called afterwards either. * Don't call it while holding a lock that the listener needs. */ void app_manager_remove_package_listener(AppPackageListenerFn listener, void* context); diff --git a/Modules/app-module/source/manager.cpp b/Modules/app-module/source/manager.cpp index f8fe8d334..6bad137bb 100644 --- a/Modules/app-module/source/manager.cpp +++ b/Modules/app-module/source/manager.cpp @@ -34,7 +34,16 @@ static void notify_package_listeners() { const auto listeners = ledger.package_listeners; mutex_unlock(&ledger.mutex); for (const auto& listener : listeners) { - listener.function(listener.context); + // A listener that an earlier listener removed during this notification must not be called anymore. + // Other threads can't remove one meanwhile, as they wait for the dispatch mutex. + mutex_lock(&ledger.mutex); + const bool registered = std::ranges::any_of(ledger.package_listeners, [&](const AppPackageListener& existing) { + return existing.function == listener.function && existing.context == listener.context; + }); + mutex_unlock(&ledger.mutex); + if (registered) { + listener.function(listener.context); + } } recursive_mutex_unlock(&ledger.listener_dispatch_mutex); } diff --git a/Modules/app-module/tests/source/manager_test.cpp b/Modules/app-module/tests/source/manager_test.cpp index 7d146b976..335a434e1 100644 --- a/Modules/app-module/tests/source/manager_test.cpp +++ b/Modules/app-module/tests/source/manager_test.cpp @@ -695,3 +695,81 @@ TEST_CASE("removing a package listener waits for a notification that is running" CHECK(state.removed); app_manager_remove_package("test.waitremove.package"); } + +namespace { + +struct RemovedListenerState { + bool contextReleased = false; + bool calledAfterRelease = false; + int callsB = 0; +}; + +RemovedListenerState removedListenerState; + +void removedListenerB(void* context) { + auto* state = static_cast(context); + state->callsB++; + if (state->contextReleased) { + state->calledAfterRelease = true; + } +} + +// Removes listener B before B's turn and then releases its context +void removingListenerA(void* context) { + auto* state = static_cast(context); + app_manager_remove_package_listener(removedListenerB, state); + state->contextReleased = true; +} + +} // namespace + +TEST_CASE("a package listener that another listener removed during a notification is not called") { + removedListenerState = {}; + // Notified in registration order: A runs before B + REQUIRE_EQ(app_manager_add_package_listener(removingListenerA, &removedListenerState), ERROR_NONE); + REQUIRE_EQ(app_manager_add_package_listener(removedListenerB, &removedListenerState), ERROR_NONE); + + PackageManifest package {}; + strcpy(package.id, "test.removedlistener.package"); + const char* const app_ids[] = { "test.removedlistener.app" }; + REQUIRE_EQ(app_manager_add_package(&package, app_ids, 1), ERROR_NONE); + + CHECK_EQ(removedListenerState.callsB, 0); + CHECK_FALSE(removedListenerState.calledAfterRelease); + app_manager_remove_package_listener(removingListenerA, &removedListenerState); + app_manager_remove_package("test.removedlistener.package"); +} + +namespace { + +struct SelfRemovingListenerState { + int calls = 0; +}; + +SelfRemovingListenerState selfRemovingListenerState; + +void selfRemovingListener(void* context) { + static_cast(context)->calls++; + app_manager_remove_package_listener(selfRemovingListener, context); +} + +} // namespace + +TEST_CASE("a package listener that removes itself is not called again") { + selfRemovingListenerState = {}; + REQUIRE_EQ(app_manager_add_package_listener(selfRemovingListener, &selfRemovingListenerState), ERROR_NONE); + + PackageManifest package {}; + strcpy(package.id, "test.selfremoving.package"); + const char* const app_ids[] = { "test.selfremoving.app" }; + REQUIRE_EQ(app_manager_add_package(&package, app_ids, 1), ERROR_NONE); + CHECK_EQ(selfRemovingListenerState.calls, 1); + + // The next notification must not reach the listener + REQUIRE_EQ(app_manager_remove_package("test.selfremoving.package"), ERROR_NONE); + CHECK_EQ(selfRemovingListenerState.calls, 1); + + // It is not registered anymore, so registering it again works + CHECK_EQ(app_manager_add_package_listener(selfRemovingListener, &selfRemovingListenerState), ERROR_NONE); + app_manager_remove_package_listener(selfRemovingListener, &selfRemovingListenerState); +} diff --git a/Modules/binfont-module/source/generator.cpp b/Modules/binfont-module/source/generator.cpp index 7dd2e65db..91629cbcb 100644 --- a/Modules/binfont-module/source/generator.cpp +++ b/Modules/binfont-module/source/generator.cpp @@ -43,6 +43,7 @@ constexpr uint8_t CMAP_FORMAT_SPARSE_TINY = 3; constexpr uint32_t CMAP_MAX_RANGE = 0xFFFF; constexpr MemoryPolicy EXTERNAL_PREFERRED = { .required = 0, .desired = MEMORY_CAPABILITY_EXTERNAL, .alignment = 0 }; +constexpr MemoryPolicy DEFAULT_POLICY = { .required = 0, .desired = 0, .alignment = 0 }; class ByteBuffer { uint8_t* data = nullptr; @@ -287,7 +288,7 @@ class CodepointList { for (uint32_t codepoint = first; codepoint <= last && !failed; codepoint++) { if (count == capacity) { const size_t new_capacity = capacity ? capacity * 2 : 256; - auto* new_data = static_cast(memory_realloc(data, new_capacity * sizeof(uint32_t))); + auto* new_data = static_cast(memory_realloc_with_policy(data, new_capacity * sizeof(uint32_t), &DEFAULT_POLICY)); if (new_data == nullptr) { failed = true; return; @@ -575,7 +576,7 @@ error_t binfont_generate(const BinFontGeneratorConfig* config, uint8_t** out_dat codepoint_count = all_codepoints.getCount(); } - auto* glyphs = static_cast(memory_alloc(codepoint_count * sizeof(GlyphInfo))); + auto* glyphs = static_cast(memory_alloc_with_policy(codepoint_count * sizeof(GlyphInfo), &DEFAULT_POLICY)); if (glyphs == nullptr) { memory_free(owned_ttf); return ERROR_OUT_OF_MEMORY; diff --git a/Modules/cpp-symbols-module/CMakeLists.txt b/Modules/cpp-symbols-module/CMakeLists.txt index efaaa5f1f..4d82dd7c6 100644 --- a/Modules/cpp-symbols-module/CMakeLists.txt +++ b/Modules/cpp-symbols-module/CMakeLists.txt @@ -9,3 +9,8 @@ tactility_add_module(cpp-symbols-module INCLUDE_DIRS include/ REQUIRES TactilityKernel ) + +# The module exports out-of-line template instantiations that it has to emit itself. A size optimized +# build inlines them away and the exports then fail to link, so these two files are built without that. +set_source_files_properties(source/module.cpp PROPERTIES COMPILE_OPTIONS "-Og") +set_source_files_properties(source/function_instantiations.cpp PROPERTIES COMPILE_OPTIONS "-O0") diff --git a/Modules/cpp-symbols-module/source/function_instantiations.cpp b/Modules/cpp-symbols-module/source/function_instantiations.cpp index d3ed17252..22e03780a 100644 --- a/Modules/cpp-symbols-module/source/function_instantiations.cpp +++ b/Modules/cpp-symbols-module/source/function_instantiations.cpp @@ -1,6 +1,10 @@ // SPDX-License-Identifier: Apache-2.0 #include +#include #include +#include +#include +#include #ifdef ESP_PLATFORM @@ -15,4 +19,20 @@ template std::function::function(const std::function&); // when some code in the firmware calls it. Instantiated here, so the module doesn't depend on that. template std::string std::operator+(std::string&&, std::string&&); +// The other string operators and helpers that module.cpp exports, for the same reason +template std::string std::operator+(const std::string&, const char*); +template bool std::operator==(const std::string&, const std::string&); +template std::string std::__str_concat(const char*, std::string::size_type, const char*, std::string::size_type, const std::string::allocator_type&); + +// std::map and the vectors that module.cpp exports. The firmware only emits these +// out of line when its own code happens not to inline them, which depends on the optimization level. +template class std::vector; +template class std::vector; + +using StringPair = std::pair; +using StringMapTree = std::_Rb_tree, std::less, std::allocator>; +template class std::_Rb_tree, std::less, std::allocator>; +template class std::map; +template StringPair::pair(std::piecewise_construct_t, std::tuple, std::tuple<>); + #endif diff --git a/Modules/lvgl-module/source/devices/devices.cpp b/Modules/lvgl-module/source/devices/devices.cpp index a7a040e33..9ebbcc8a9 100644 --- a/Modules/lvgl-module/source/devices/devices.cpp +++ b/Modules/lvgl-module/source/devices/devices.cpp @@ -22,6 +22,17 @@ #include +#ifdef ESP_PLATFORM +#include +#endif + +// Lines per draw buffer from lvgl.drawBufferLines in device.properties, 0 for a tenth of the vertical resolution +#ifdef CONFIG_TT_LVGL_DRAW_BUFFER_LINES +constexpr uint16_t DRAW_BUFFER_LINES = CONFIG_TT_LVGL_DRAW_BUFFER_LINES; +#else +constexpr uint16_t DRAW_BUFFER_LINES = 0; +#endif + #pragma GCC diagnostic ignored "-Wdeprecated-declarations" constexpr auto* TAG = "lvgl"; @@ -253,7 +264,7 @@ void lvgl_devices_attach() { display_has_capability(kernel_display_device, DISPLAY_CAPABILITY_CAP_MIRROR); bool prefer_external_ram_buffer = display_has_capability(kernel_display_device, DISPLAY_CAPABILITY_PREFER_EXTERNAL_RAM); struct LvglDisplayConfig lvgl_display_config = { - .buffer_height = (uint16_t)(vres > 10 ? vres / 10 : vres), + .buffer_height = DRAW_BUFFER_LINES > 0 ? (DRAW_BUFFER_LINES < vres ? DRAW_BUFFER_LINES : vres) : (uint16_t)(vres > 10 ? vres / 10 : vres), .double_buffer = false, .sw_rotate = !can_hw_rotate, .swap_bytes = swap_bytes, diff --git a/Modules/lvgl-module/source/widgets/toolbar.cpp b/Modules/lvgl-module/source/widgets/toolbar.cpp index 895b60dbd..c5becaaaf 100644 --- a/Modules/lvgl-module/source/widgets/toolbar.cpp +++ b/Modules/lvgl-module/source/widgets/toolbar.cpp @@ -110,6 +110,9 @@ lv_obj_t* lvgl_toolbar_create(lv_obj_t* parent, const char* title) { lvgl_grid_navigation_add(obj); toolbar->close_button = create_action_button(obj, size); + // A larger touch area than the visible button. LVGL only looks for a touched child inside the + // toolbar, so the area never exceeds the toolbar's own height. + lv_obj_set_ext_click_area(toolbar->close_button, getActionButtonSize(size) / 2); toolbar->close_button_image = lv_image_create(toolbar->close_button); lv_obj_align(toolbar->close_button_image, LV_ALIGN_CENTER, 0, 0); diff --git a/Platforms/platform-esp32/CMakeLists.txt b/Platforms/platform-esp32/CMakeLists.txt index 052b05e16..40d773f57 100644 --- a/Platforms/platform-esp32/CMakeLists.txt +++ b/Platforms/platform-esp32/CMakeLists.txt @@ -28,7 +28,7 @@ if (DEFINED ENV{ESP_IDF_VERSION}) endif () endif () -idf_component_optional_requires(PRIVATE bt usb espressif__usb_host_hid espressif__usb_host_msc espressif__esp_audio_codec) +idf_component_optional_requires(PRIVATE bt usb espressif__usb_host_hid espressif__usb_host_msc) if ("${IDF_TARGET}" STREQUAL "esp32s3" OR "${IDF_TARGET}" STREQUAL "esp32p4" OR "${IDF_TARGET}" STREQUAL "esp32s31") idf_component_optional_requires(PRIVATE espressif__usb_host_uac) endif () diff --git a/Tactility/CMakeLists.txt b/Tactility/CMakeLists.txt index e411fc825..5429c6ae8 100644 --- a/Tactility/CMakeLists.txt +++ b/Tactility/CMakeLists.txt @@ -30,7 +30,6 @@ list(APPEND REQUIRES_LIST app-module app-hub-module coreutils-module - audio-decoder-module binfont-module lodepng-module c-symbols-module @@ -59,6 +58,23 @@ list(APPEND REQUIRES_LIST minitar ) +# A device can leave out the audio modules to save flash with "modules.audio=false" in device.properties +set(TT_AUDIO_MODULES_ENABLED TRUE) +if (EXISTS "${DEVICETREE_LOCATION}/device.properties") + file(READ "${DEVICETREE_LOCATION}/device.properties" device_properties_audio_content) + if (device_properties_audio_content MATCHES "(^|\n)modules\\.audio=false") + set(TT_AUDIO_MODULES_ENABLED FALSE) + endif () +endif () +if (TT_AUDIO_MODULES_ENABLED) + list(APPEND REQUIRES_LIST audio-decoder-module) +elseif (EXISTS "${DEVICETREE_LOCATION}/module.yaml") + file(READ "${DEVICETREE_LOCATION}/module.yaml" device_module_yaml_content) + if (device_module_yaml_content MATCHES "audio-stream-module") + message(FATAL_ERROR "${TACTILITY_DEVICE_ID} has modules.audio=false but its module.yaml depends on audio-stream-module") + endif () +endif () + # Check if device has Bluetooth enabled # Fixes the sdkconfig bluetooth enable options from getting nuked on non-P4+C6 builds when idf build runs if (DEFINED ENV{ESP_IDF_VERSION}) @@ -122,7 +138,7 @@ execute_process( # so the new component's include dirs never reach the compiler until a fullclean. set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${DEVICETREE_LOCATION}/module.yaml" - "${DEVICETREE_LOCATION}/device.properties" # due to the "hardware.bluetooth = true" search in this file from this CMakeLists.txt + "${DEVICETREE_LOCATION}/device.properties" # due to the "hardware.bluetooth = true" and "modules.audio=false" searches in this file from this CMakeLists.txt ) execute_process( @@ -169,6 +185,10 @@ if (DEFINED ENV{ESP_IDF_VERSION}) idf_component_optional_requires(PRIVATE bt) + if (TT_AUDIO_MODULES_ENABLED) + target_compile_definitions(${COMPONENT_LIB} PRIVATE TT_AUDIO_MODULES_ENABLED) + endif () + if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU") target_compile_options(${COMPONENT_LIB} PUBLIC -Wno-unused-variable) endif () @@ -189,6 +209,9 @@ else () add_executable(Tactility ${SOURCE_FILES}) target_include_directories(Tactility PUBLIC Include/) target_include_directories(Tactility PRIVATE Private/) + if (TT_AUDIO_MODULES_ENABLED) + target_compile_definitions(Tactility PRIVATE TT_AUDIO_MODULES_ENABLED) + endif () target_link_libraries(Tactility PRIVATE ${TACTILITY_REQUIRES_LIST}) # Exports Tactility's own symbols (-rdynamic) so a dlopen()ed app-posix-module app can resolve # calls back into it - the OS-native equivalent of app-esp32-module's custom symbol resolver. diff --git a/Tactility/Include/Tactility/app/touchcalibration/CalibrationMath.h b/Tactility/Include/Tactility/app/touchcalibration/CalibrationMath.h new file mode 100644 index 000000000..c463d00bd --- /dev/null +++ b/Tactility/Include/Tactility/app/touchcalibration/CalibrationMath.h @@ -0,0 +1,42 @@ +#pragma once + +#include +#include + +namespace tt::app::touchcalibration { + +/** The display rotations of LVGL, clockwise */ +enum class Rotation { + None, + Rotate90, + Rotate180, + Rotate270 +}; + +struct Point { + int32_t x; + int32_t y; +}; + +/** + * Maps a point of the rotated display back to the panel's native orientation, which is + * where the pointer applies a calibration, before LVGL rotates the points. + * @param[in] point a point in the coordinates of the rotated display + * @param[in] rotation the rotation of the display + * @param[in] nativeWidth the width of the panel without rotation + * @param[in] nativeHeight the height of the panel without rotation + */ +Point toNativePoint(Point point, Rotation rotation, int32_t nativeWidth, int32_t nativeHeight); + +/** + * Fits the raw values of one axis that were read at known positions, to the raw range that spans the panel. + * The calibration maps [min, max] onto [0, nativeMax]. + * @param[in] targets the positions that were touched, in native pixels + * @param[in] samples the raw values that were read at those positions + * @param[in] count the number of points, at least 2 + * @param[in] nativeMax the last pixel of the axis + * @return false when the points don't give an increasing range + */ +bool computeRange(const int32_t* targets, const int32_t* samples, size_t count, int32_t nativeMax, int32_t& min, int32_t& max); + +} // namespace tt::app::touchcalibration diff --git a/Tactility/Kconfig b/Tactility/Kconfig index f2bab4d8a..2b46543a6 100644 --- a/Tactility/Kconfig +++ b/Tactility/Kconfig @@ -39,6 +39,13 @@ menu "Tactility App" range 0 100 help Default size of widgets, from 0 (compact) to 100 (regular). Users can change it in the Appearance app. + config TT_LVGL_DRAW_BUFFER_LINES + int "Lines per LVGL draw buffer" + default 0 + range 0 4096 + help + Number of display lines in an LVGL draw buffer. 0 uses a tenth of the vertical resolution. + A smaller buffer uses less memory and needs more flushes. config TT_AUTO_START_APP_ID string "Auto Start App ID" default "" diff --git a/Tactility/Private/Tactility/app/TileGrid.h b/Tactility/Private/Tactility/app/TileGrid.h index b713249e1..cc28f38a7 100644 --- a/Tactility/Private/Tactility/app/TileGrid.h +++ b/Tactility/Private/Tactility/app/TileGrid.h @@ -8,6 +8,12 @@ namespace tt::app { +/** + * @return false on devices without PSRAM, where SVG icons take too much memory. + * The tiles then show the icon font glyphs, and the SVG icons are never loaded. + */ +bool areSvgIconsEnabled(); + struct TileGridItem { /** Identifies the item across rebuilds, e.g. to keep it selected */ std::string id; @@ -40,6 +46,8 @@ class TileGrid final { void (*onKey)(const TileGridItem& item, uint32_t key, void* userData); /** Optional: returns the image of an item without an icon or image. Only called for the items on the shown page. */ const lv_image_dsc_t* (*resolveImage)(const TileGridItem& item, void* userData); + /** Optional: returns the icon font glyph of an item without an icon or an image, when resolveImage() gave none. Only called for the items on the shown page. */ + const char* (*resolveIcon)(const TileGridItem& item, void* userData); /** Optional: called after the user went to another page */ void (*onPageChanged)(void* userData); /** Optional: called on every rebuild, after the old tiles were deleted and before collect. Nothing shows the images of earlier items anymore. */ diff --git a/Tactility/Private/Tactility/app/files/View.h b/Tactility/Private/Tactility/app/files/View.h index cc988560f..11a7ce691 100644 --- a/Tactility/Private/Tactility/app/files/View.h +++ b/Tactility/Private/Tactility/app/files/View.h @@ -51,6 +51,7 @@ class View final { static std::vector collectItems(void* userData); static const lv_image_dsc_t* resolveImage(const TileGridItem& item, void* userData); + static const char* resolveIcon(const TileGridItem& item, void* userData); static void onTileClicked(const TileGridItem& item, void* userData); static void onTileLongPressed(const TileGridItem& item, void* userData); static void onTileKey(const TileGridItem& item, uint32_t key, void* userData); diff --git a/Tactility/Private/Tactility/app/launcher/LauncherMode.h b/Tactility/Private/Tactility/app/launcher/LauncherMode.h index 702638790..fde04b9da 100644 --- a/Tactility/Private/Tactility/app/launcher/LauncherMode.h +++ b/Tactility/Private/Tactility/app/launcher/LauncherMode.h @@ -24,12 +24,6 @@ struct LauncherMode { /** Reads the favourites from their file into memory. File operation, see . */ void loadFavourites(void* context); -/** - * @return false on devices without PSRAM, where the SVG icons take too much memory. - * The tiles then show the fallback icon, and the icons are never loaded. - */ -bool areSvgIconsEnabled(); - /** Rasterizes the icon.svg of every installed package into memory. File operation, see . */ void loadPackageIcons(void* context); diff --git a/Tactility/Source/InitModules.cpp b/Tactility/Source/InitModules.cpp index b5db3cc2c..6e0bfb6f2 100644 --- a/Tactility/Source/InitModules.cpp +++ b/Tactility/Source/InitModules.cpp @@ -20,7 +20,9 @@ #endif #include +#ifdef TT_AUDIO_MODULES_ENABLED #include +#endif #include #include #include @@ -69,7 +71,9 @@ void initModules() { check(module_ensure_started(&app_module) == ERROR_NONE); check(module_ensure_started(&coreutils_module) == ERROR_NONE); check(module_ensure_started(&crypt_module) == ERROR_NONE); +#ifdef TT_AUDIO_MODULES_ENABLED check(module_ensure_started(&audio_decoder_module) == ERROR_NONE); +#endif check(module_ensure_started(&mbedtls_module) == ERROR_NONE); check(module_ensure_started(&gps_module) == ERROR_NONE); check(module_ensure_started(&gps_generic_module) == ERROR_NONE); diff --git a/Tactility/Source/app/TileGrid.cpp b/Tactility/Source/app/TileGrid.cpp index e29111cd7..83716550e 100644 --- a/Tactility/Source/app/TileGrid.cpp +++ b/Tactility/Source/app/TileGrid.cpp @@ -9,11 +9,21 @@ #include #include +#include + #include #include namespace tt::app { +bool areSvgIconsEnabled() { +#ifdef ESP_PLATFORM + return memory_external_total() > 0; +#else + return true; +#endif +} + namespace { constexpr int32_t TILE_GAP = 6; @@ -390,8 +400,14 @@ void TileGrid::populate() { lv_obj_set_user_data(tile, const_cast(&item)); const lv_image_dsc_t* image_src = item.image; - if (image_src == nullptr && item.icon == nullptr && callbacks.resolveImage != nullptr) { - image_src = callbacks.resolveImage(item, callbacks.userData); + const char* icon_text = item.icon; + if (image_src == nullptr && icon_text == nullptr) { + if (callbacks.resolveImage != nullptr) { + image_src = callbacks.resolveImage(item, callbacks.userData); + } + if (image_src == nullptr && callbacks.resolveIcon != nullptr) { + icon_text = callbacks.resolveIcon(item, callbacks.userData); + } } if (image_src != nullptr) { lv_obj_t* image = lv_image_create(tile); @@ -412,7 +428,7 @@ void TileGrid::populate() { lv_obj_set_style_text_font(icon, lvgl_get_shared_icon_large_font(), LV_STATE_DEFAULT); lv_obj_set_style_text_align(icon, LV_TEXT_ALIGN_CENTER, LV_STATE_DEFAULT); lv_obj_set_size(icon, layout.iconSize, layout.iconSize); - lv_label_set_text(icon, item.icon != nullptr ? item.icon : ""); + lv_label_set_text(icon, icon_text != nullptr ? icon_text : ""); // A placeholder for an image that isn't loaded yet has the theme's text colour lv_obj_set_style_text_color(icon, lv_obj_get_style_text_color(tile, LV_PART_MAIN), LV_STATE_DEFAULT); } diff --git a/Tactility/Source/app/camera/Camera.cpp b/Tactility/Source/app/camera/Camera.cpp index 22bdad85a..c36853e46 100644 --- a/Tactility/Source/app/camera/Camera.cpp +++ b/Tactility/Source/app/camera/Camera.cpp @@ -138,7 +138,11 @@ void buildTimestampedPath(const char* suffix, char* out, size_t outLen) { static uint32_t sequence = 0; char fname[64]; strftime(fname, sizeof(fname), "/%Y%m%d_%H%M%S", &tm_info); - snprintf(out, outLen, "%s%s_%04u%s", dir, fname, static_cast(sequence++), suffix); + const int written = snprintf(out, outLen, "%s%s_%04u%s", dir, fname, static_cast(sequence++), suffix); + if (written < 0 || static_cast(written) >= outLen) { + LOG_E("Camera", "Path is too long"); + out[0] = '\0'; + } } bool saveJpeg(Context* ctx) { diff --git a/Tactility/Source/app/files/View.cpp b/Tactility/Source/app/files/View.cpp index 122900b4c..e1bc5da9e 100644 --- a/Tactility/Source/app/files/View.cpp +++ b/Tactility/Source/app/files/View.cpp @@ -150,6 +150,19 @@ constexpr FileIconAsset FILE_ICON_ASSETS[] = { FILE_ICON_ASSET(file), }; +// The icon font glyphs shown instead of the SVG icons, indexed by FileIcon +constexpr const char* FILE_ICON_GLYPHS[] = { + LVGL_ICON_SHARED_FOLDER, + LVGL_ICON_SHARED_SD_CARD, + LVGL_ICON_SHARED_USB, + LVGL_ICON_SHARED_LINK, + LVGL_ICON_SHARED_IMAGE, + LVGL_ICON_SHARED_DESCRIPTION, + LVGL_ICON_SHARED_DEPLOYED_CODE, + LVGL_ICON_SHARED_PLAY_ARROW, + LVGL_ICON_SHARED_DRAFT, +}; + // Returns Unknown for the files that View::resolveImage() checks, as that reads the file static FileIcon getIcon(const dirent& entry, bool isRoot) { if (entry.d_type == file::TT_DT_DIR || entry.d_type == file::TT_DT_CHR) { @@ -371,6 +384,7 @@ View::View(const std::shared_ptr& state, TaskEventGroup* eventGroup) : .onLongPressed = onTileLongPressed, .onKey = onTileKey, .resolveImage = resolveImage, + .resolveIcon = resolveIcon, .onPageChanged = onPageChanged, .userData = this }) { @@ -379,6 +393,10 @@ View::View(const std::shared_ptr& state, TaskEventGroup* eventGroup) : } void View::loadIcons() { + if (!areSvgIconsEnabled()) { + return; + } + const auto size = static_cast(lvgl_get_shared_icon_large_font_height()); const bool preferMono = lvgl_theme_is_mono(); for (size_t i = 0; i < std::size(FILE_ICON_ASSETS); i++) { @@ -413,12 +431,19 @@ std::vector View::collectItems(void* userData) { const lv_image_dsc_t* image = icon == FileIcon::Unknown ? nullptr : reinterpret_cast(view->icons[static_cast(icon)]); // Files that are resolved later are shown as an executable or a plain file, which are rasterized from the same set const bool recolor = view->iconRecolor[static_cast(icon == FileIcon::Unknown ? FileIcon::File : icon)]; - items.push_back({ entry.d_name, entry.d_name, nullptr, false, image, recolor }); + // The glyph is shown when there is no image: without PSRAM or when it failed to rasterize + const char* glyph = icon == FileIcon::Unknown ? nullptr : FILE_ICON_GLYPHS[static_cast(icon)]; + items.push_back({ entry.d_name, entry.d_name, glyph, false, image, recolor }); } }); return items; } +const char* View::resolveIcon(const TileGridItem& item, void* userData) { + auto* view = static_cast(userData); + return FILE_ICON_GLYPHS[static_cast(view->state->isExecutable(item.id) ? FileIcon::Executable : FileIcon::File)]; +} + const lv_image_dsc_t* View::resolveImage(const TileGridItem& item, void* userData) { auto* view = static_cast(userData); const auto icon = view->state->isExecutable(item.id) ? FileIcon::Executable : FileIcon::File; diff --git a/Tactility/Source/app/launcher/AppsMode.cpp b/Tactility/Source/app/launcher/AppsMode.cpp index 383ad9539..b873baa65 100644 --- a/Tactility/Source/app/launcher/AppsMode.cpp +++ b/Tactility/Source/app/launcher/AppsMode.cpp @@ -263,14 +263,6 @@ const lv_image_dsc_t* defaultAppIcon(bool* recolor) { return image; } -bool areSvgIconsEnabled() { -#ifdef ESP_PLATFORM - return memory_external_total() > 0; -#else - return true; -#endif -} - void releaseRetiredAppIcons() { auto& state = packageIcons(); mutex_lock(&state.mutex); diff --git a/Tactility/Source/app/launcher/Launcher.cpp b/Tactility/Source/app/launcher/Launcher.cpp index 259e446e8..6d5293e23 100644 --- a/Tactility/Source/app/launcher/Launcher.cpp +++ b/Tactility/Source/app/launcher/Launcher.cpp @@ -24,6 +24,10 @@ #include #include #include +#ifdef CONFIG_TT_TOUCH_CALIBRATION_REQUIRED +#include +#include +#endif #include #include #include @@ -71,6 +75,7 @@ struct Context { .onLongPressed = onAppLongPressed, .onKey = onAppKey, .resolveImage = nullptr, + .resolveIcon = nullptr, .onPageChanged = nullptr, .onTilesCleared = onTilesCleared, .userData = this, @@ -192,32 +197,75 @@ void destroyWidgets(void* userData) { ctx->grid.destroyWidgets(); } -// Reads settings files, so it runs on the file operations task -void runAutoStart(void*) { +#ifdef CONFIG_TT_TOUCH_CALIBRATION_REQUIRED +// Reads the settings file, so it runs on the file operations task +bool isTouchCalibrated() { + settings::touch::TouchCalibrationSettings calibration; + return settings::touch::load(calibration) && calibration.enabled && settings::touch::isValid(calibration); +} +#endif + +struct AutoStartJob { + uint32_t launcherInstanceId; + // The touch calibration finished since the launcher started + bool touchCalibrated; +}; + +// Reads settings files, so it runs on the file operations task, which frees the job. +// The job is not in the context of the app: queued work still runs after the app has closed. +void runAutoStart(void* context) { + const auto job = *static_cast(context); + delete static_cast(context); + + enum class Target { None, App, Setup }; + Target target = Target::None; settings::BootSettings boot_properties; - AppStartContext context; + AppStartContext context_to_start; if ( // Auto-start due to built-in requirement strcmp(CONFIG_TT_AUTO_START_APP_ID, "") != 0 && - app_start_context_from_id(CONFIG_TT_AUTO_START_APP_ID, &context) == ERROR_NONE + app_start_context_from_id(CONFIG_TT_AUTO_START_APP_ID, &context_to_start) == ERROR_NONE ) { LOG_I(TAG, "Starting %s", CONFIG_TT_AUTO_START_APP_ID); - uint32_t app_launch_id; - app_start_with_context(&context, &app_launch_id); + target = Target::App; } else if ( // Auto-start due to user configuration settings::loadBootSettings(boot_properties) && !boot_properties.autoStartAppId.empty() && - app_start_context_from_id(boot_properties.autoStartAppId.c_str(), &context) == ERROR_NONE + app_start_context_from_id(boot_properties.autoStartAppId.c_str(), &context_to_start) == ERROR_NONE ) { LOG_I(TAG, "Starting %s", boot_properties.autoStartAppId.c_str()); - uint32_t app_launch_id; - app_start_with_context(&context, &app_launch_id); - } else { + target = Target::App; + } else if (!setup::isCompleted()) { // No auto-start, consider running system setup - if (!setup::isCompleted()) { - setup::start(); - } + target = Target::Setup; + } + +#ifdef CONFIG_TT_TOUCH_CALIBRATION_REQUIRED + // The device isn't usable without a calibration, so it runs first. The setup always starts with it, also when + // one was saved, so that a calibration that doesn't work can be redone by restarting before the setup is finished. + // The launcher runs this again when the calibration ended. + if (!job.touchCalibrated && (target == Target::Setup || !isTouchCalibrated())) { + LOG_I(TAG, "Starting touch calibration"); + touchcalibration::start(job.launcherInstanceId); + return; + } +#endif + + if (target == Target::App) { + uint32_t app_launch_id; + app_start_with_context(&context_to_start, &app_launch_id); + } else if (target == Target::Setup) { + setup::start(); + } +} + +// Queues the auto start, which needs the launcher's instance id to receive the result of a calibration +void queueAutoStart(uint32_t launcherInstanceId, bool touchCalibrated) { + auto* job = new (::std::nothrow) AutoStartJob { launcherInstanceId, touchCalibrated }; + if (job == nullptr || file_ops_queue(runAutoStart, job, nullptr) != ERROR_NONE) { + LOG_E(TAG, "Failed to queue the auto start"); + delete job; } } @@ -262,6 +310,9 @@ int32_t appMain(int argc, char* argv[]) { WindowId window = 0; bool windowCreated = false; bool iconsReloading = false; +#ifdef CONFIG_TT_TOUCH_CALIBRATION_REQUIRED + bool touchCalibrationFinished = false; +#endif // The window is created once the favourites are loaded, so its first render has the final order check(file_ops_queue(loadLauncherData, nullptr, &file_ops_sub) == ERROR_NONE); @@ -275,7 +326,7 @@ int32_t appMain(int argc, char* argv[]) { window = window_manager_create_ext(appInstanceId, createWidgets, destroyWidgets, &ctx); windowCreated = true; // The file operations run in order: the favourites are available when auto-start runs - check(file_ops_queue(runAutoStart, nullptr, nullptr) == ERROR_NONE); + queueAutoStart(appInstanceId, false); } if (windowCreated && iconsReloading && file_ops_poll(&file_ops_sub) == ERROR_NONE) { @@ -315,6 +366,15 @@ int32_t appMain(int argc, char* argv[]) { shouldClose = true; break; } +#ifdef CONFIG_TT_TOUCH_CALIBRATION_REQUIRED + // The launcher only starts a child for the touch calibration. The auto start runs again to check the result + if (event.type == APP_EVENT_RESULT) { + app_manager_stop(event.result.launch_id); + // A cancelled or failed calibration starts again. The result is 0 when it was applied + touchCalibrationFinished = touchCalibrationFinished || event.result.result == 0; + queueAutoStart(appInstanceId, touchCalibrationFinished); + } +#endif } if (shouldClose) break; } diff --git a/Tactility/Source/app/setup/Setup.cpp b/Tactility/Source/app/setup/Setup.cpp index 0c4e182ce..7ef3139ff 100644 --- a/Tactility/Source/app/setup/Setup.cpp +++ b/Tactility/Source/app/setup/Setup.cpp @@ -37,10 +37,6 @@ #include #endif -#ifdef CONFIG_TT_TOUCH_CALIBRATION_REQUIRED -#include -#endif - namespace tt::app::setup { extern const ::AppManifest manifest; @@ -339,13 +335,6 @@ int32_t appMain(int argc, char* argv[]) { // Whether the location step enabled location services, which is not the case when it was skipped bool locationEnabled = false; ctx.steps = { -#if defined(CONFIG_TT_TOUCH_CALIBRATION_REQUIRED) - { - .title = "Touch Calibration", - .description = "Let's calibrate the touch screen.", - .run = [&ctx] { ctx.pendingStepDialogId = touchcalibration::start(ctx.appInstanceId); } - }, -#endif { .title = "Wi-Fi Setup", .description = "Let's connect to a Wi-Fi access point.", diff --git a/Tactility/Source/app/touchcalibration/CalibrationMath.cpp b/Tactility/Source/app/touchcalibration/CalibrationMath.cpp new file mode 100644 index 000000000..50ee54c0c --- /dev/null +++ b/Tactility/Source/app/touchcalibration/CalibrationMath.cpp @@ -0,0 +1,55 @@ +#include + +#include + +namespace tt::app::touchcalibration { + +Point toNativePoint(Point point, Rotation rotation, int32_t nativeWidth, int32_t nativeHeight) { + switch (rotation) { + case Rotation::Rotate90: + return { .x = point.y, .y = nativeHeight - 1 - point.x }; + case Rotation::Rotate180: + return { .x = nativeWidth - 1 - point.x, .y = nativeHeight - 1 - point.y }; + case Rotation::Rotate270: + return { .x = nativeWidth - 1 - point.y, .y = point.x }; + default: + return point; + } +} + +bool computeRange(const int32_t* targets, const int32_t* samples, size_t count, int32_t nativeMax, int32_t& min, int32_t& max) { + if (count < 2) { + return false; + } + + double targetMean = 0.0; + double sampleMean = 0.0; + for (size_t i = 0; i < count; i++) { + targetMean += targets[i]; + sampleMean += samples[i]; + } + targetMean /= static_cast(count); + sampleMean /= static_cast(count); + + // Least squares fit of sample = offset + scale * target + double covariance = 0.0; + double variance = 0.0; + for (size_t i = 0; i < count; i++) { + covariance += (targets[i] - targetMean) * (samples[i] - sampleMean); + variance += (targets[i] - targetMean) * (targets[i] - targetMean); + } + if (variance <= 0.0) { + return false; + } + + const double scale = covariance / variance; + if (scale <= 0.0) { + return false; + } + const double offset = sampleMean - scale * targetMean; + min = static_cast(std::lround(offset)); + max = static_cast(std::lround(offset + scale * nativeMax)); + return true; +} + +} // namespace tt::app::touchcalibration diff --git a/Tactility/Source/app/touchcalibration/TouchCalibration.cpp b/Tactility/Source/app/touchcalibration/TouchCalibration.cpp index 74e54de9f..45065e5e2 100644 --- a/Tactility/Source/app/touchcalibration/TouchCalibration.cpp +++ b/Tactility/Source/app/touchcalibration/TouchCalibration.cpp @@ -3,6 +3,8 @@ #if defined(CONFIG_TT_TOUCH_CALIBRATION_SUPPORTED) #include +#include +#include #include #include @@ -17,6 +19,7 @@ #include #include #include +#include #include #include @@ -39,7 +42,9 @@ struct Sample { struct Context { uint32_t appInstanceId; + // The taps, and the centers of the targets that were shown, in the coordinates of the display Sample samples[4] = {}; + lv_point_t targets[4] = {}; uint8_t sampleCount = 0; bool calibrationApplied = false; @@ -82,33 +87,33 @@ void updateUi(Context* ctx) { // Drives the on-screen outcome text/state; the actual result (Ok/Error) is reported to the // caller from onPress() below, via ctx->calibrationApplied, once the user taps to dismiss. void finishCalibration(Context* ctx) { - const int32_t xLow = (static_cast(ctx->samples[0].x) + static_cast(ctx->samples[3].x)) / 2; - const int32_t xHigh = (static_cast(ctx->samples[1].x) + static_cast(ctx->samples[2].x)) / 2; - const int32_t yLow = (static_cast(ctx->samples[0].y) + static_cast(ctx->samples[1].y)) / 2; - const int32_t yHigh = (static_cast(ctx->samples[2].y) + static_cast(ctx->samples[3].y)) / 2; - - // Targets sit TARGET_MARGIN in from each edge (see getTargetPoint()), not at the screen - // edges themselves - xLow/xHigh/yLow/yHigh are raw samples at those inset positions, not - // at 0/width or 0/height. Extrapolate them out to the true edges so the saved range (which - // lvgl_pointer.h maps onto the full [0, resolution) display range) lines up correctly - // across the whole screen instead of being off by a margin's worth of scale and offset. - const auto width = lv_obj_get_content_width(ctx->root); - const auto height = lv_obj_get_content_height(ctx->root); - const int32_t xSpan = static_cast(width) - 2 * TARGET_MARGIN; - const int32_t ySpan = static_cast(height) - 2 * TARGET_MARGIN; + // The calibration is applied in the native orientation of the panel, before LVGL rotates the points. + // The targets are shown, and the taps are reported, in the rotated display, so both go back to native first. + auto* display = lv_display_get_default(); + const int32_t nativeWidth = lv_display_get_original_horizontal_resolution(display); + const int32_t nativeHeight = lv_display_get_original_vertical_resolution(display); + const auto rotation = static_cast(lv_display_get_rotation(display)); + + int32_t targetX[4], targetY[4], sampleX[4], sampleY[4]; + for (int i = 0; i < 4; i++) { + const auto target = toNativePoint({ ctx->targets[i].x, ctx->targets[i].y }, rotation, nativeWidth, nativeHeight); + const auto sample = toNativePoint({ ctx->samples[i].x, ctx->samples[i].y }, rotation, nativeWidth, nativeHeight); + targetX[i] = target.x; + targetY[i] = target.y; + sampleX[i] = sample.x; + sampleY[i] = sample.y; + } - if (xSpan <= 0 || ySpan <= 0) { + // The targets are inset from the edges, so the fit extrapolates the raw range out to the true edges of the panel + int32_t xMin, xMax, yMin, yMax; + if (!computeRange(targetX, sampleX, 4, nativeWidth - 1, xMin, xMax) || + !computeRange(targetY, sampleY, 4, nativeHeight - 1, yMin, yMax)) { lv_label_set_text(ctx->titleLabel, "Calibration Failed"); - lv_label_set_text(ctx->hintLabel, "Screen too small. Tap to close."); + lv_label_set_text(ctx->hintLabel, "Range invalid. Tap to close."); lv_obj_set_hidden(ctx->target, true); return; } - const int32_t xMin = xLow - (xHigh - xLow) * TARGET_MARGIN / xSpan; - const int32_t xMax = xHigh + (xHigh - xLow) * TARGET_MARGIN / xSpan; - const int32_t yMin = yLow - (yHigh - yLow) * TARGET_MARGIN / ySpan; - const int32_t yMax = yHigh + (yHigh - yLow) * TARGET_MARGIN / ySpan; - settings::touch::TouchCalibrationSettings settings = settings::touch::getDefault(); settings.enabled = true; settings.xMin = xMin; @@ -161,6 +166,9 @@ void onPress(lv_event_t* event) { lv_indev_get_point(indev, &point); if (ctx->sampleCount < 4) { + lv_area_t targetArea; + lv_obj_get_coords(ctx->target, &targetArea); + ctx->targets[ctx->sampleCount] = { .x = (targetArea.x1 + targetArea.x2) / 2, .y = (targetArea.y1 + targetArea.y2) / 2 }; ctx->samples[ctx->sampleCount] = { .x = static_cast(std::max(static_cast(0), point.x)), .y = static_cast(std::max(static_cast(0), point.y)), @@ -180,6 +188,7 @@ void onPress(lv_event_t* event) { void createWidgets(lv_obj_t* parent, void* userData) { auto* ctx = static_cast(userData); + lvgl::systemBarsSetStatusbarVisible(false); lv_obj_set_style_bg_color(parent, lv_color_black(), LV_STATE_DEFAULT); lv_obj_set_style_bg_opa(parent, LV_OPA_COVER, LV_STATE_DEFAULT); @@ -205,7 +214,8 @@ void createWidgets(lv_obj_t* parent, void* userData) { ctx->target = lv_button_create(ctx->root); lv_obj_set_size(ctx->target, 28, 28); lv_obj_set_style_radius(ctx->target, LV_RADIUS_CIRCLE, LV_STATE_DEFAULT); - lv_obj_set_style_bg_color(ctx->target, lv_palette_main(LV_PALETTE_RED), LV_STATE_DEFAULT); + // The monochrome theme's primary color is black, which can't be seen on the black background + lv_obj_set_style_bg_color(ctx->target, lvgl_theme_is_mono() ? lv_color_white() : lv_theme_get_color_primary(ctx->target), LV_STATE_DEFAULT); // Ensure root receives all presses for sampling. lv_obj_set_clickable(ctx->target, false); @@ -219,6 +229,15 @@ void createWidgets(lv_obj_t* parent, void* userData) { updateUi(ctx); } +void destroyWidgets(void* userData) { + auto* ctx = static_cast(userData); + lvgl::systemBarsSetStatusbarVisible(true); + ctx->root = nullptr; + ctx->target = nullptr; + ctx->titleLabel = nullptr; + ctx->hintLabel = nullptr; +} + int32_t appMain(int argc, char* argv[]) { uint32_t appInstanceId = app_scheduler_current_app_id(); Context ctx {}; @@ -238,7 +257,7 @@ int32_t appMain(int argc, char* argv[]) { AppEventSubscription sub {}; check(app_event_subscribe(&sub, &event_group) == ERROR_NONE); - WindowId window = window_manager_create(appInstanceId, createWidgets, &ctx); + WindowId window = window_manager_create_ext(appInstanceId, createWidgets, destroyWidgets, &ctx); bool shouldClose = false; while (!shouldClose) { diff --git a/Tactility/Tests/CMakeLists.txt b/Tactility/Tests/CMakeLists.txt index 02b2a5e34..a5443806f 100644 --- a/Tactility/Tests/CMakeLists.txt +++ b/Tactility/Tests/CMakeLists.txt @@ -41,6 +41,7 @@ target_include_directories(TactilityTests PRIVATE ${CMAKE_CURRENT_LIST_DIR}/../P # the POSIX simulator (see Tests/tests.md), so it just hardcodes that same file's own POSIX default # rather than reimplementing the sdkconfig lookup here too. target_compile_definitions(TactilityTests PRIVATE + "-DTT_AUDIO_MODULES_ENABLED" "-DTT_FONT_DEFAULT_SIZE=14" "-DTACTILITY_TEST_DATA_DIR=\"${CMAKE_CURRENT_LIST_DIR}/../../Data\"" "-DTACTILITY_TEST_FONTS_DIR=\"${CMAKE_CURRENT_LIST_DIR}/../Fonts\"" diff --git a/Tactility/Tests/Source/TouchCalibrationMathTest.cpp b/Tactility/Tests/Source/TouchCalibrationMathTest.cpp new file mode 100644 index 000000000..9e287ef02 --- /dev/null +++ b/Tactility/Tests/Source/TouchCalibrationMathTest.cpp @@ -0,0 +1,114 @@ +#include "doctest.h" + +#include + +#include + +using namespace tt::app::touchcalibration; + +// The point transform of LVGL (lv_display_rotate_point) for a panel of width x height without rotation +static Point rotateLikeLvgl(Point point, Rotation rotation, int32_t width, int32_t height) { + switch (rotation) { + case Rotation::Rotate90: + return { .x = height - point.y - 1, .y = point.x }; + case Rotation::Rotate180: + return { .x = width - point.x - 1, .y = height - point.y - 1 }; + case Rotation::Rotate270: + return { .x = point.y, .y = width - point.x - 1 }; + default: + return point; + } +} + +TEST_CASE("toNativePoint undoes the rotation of the display") { + constexpr int32_t width = 320; + constexpr int32_t height = 480; + for (auto rotation : { Rotation::None, Rotation::Rotate90, Rotation::Rotate180, Rotation::Rotate270 }) { + for (auto native : { Point { 0, 0 }, Point { 319, 0 }, Point { 0, 479 }, Point { 319, 479 }, Point { 100, 250 } }) { + const auto rotated = rotateLikeLvgl(native, rotation, width, height); + const auto restored = toNativePoint(rotated, rotation, width, height); + CHECK_EQ(restored.x, native.x); + CHECK_EQ(restored.y, native.y); + } + } +} + +TEST_CASE("computeRange recovers the range of a sensor with an offset and a scale") { + // Raw = 100 + 2 * position, so the panel from 0 to 319 spans 100 to 738 + const int32_t targets[] = { 24, 296, 296, 24 }; + int32_t samples[4]; + for (int i = 0; i < 4; i++) { + samples[i] = 100 + 2 * targets[i]; + } + int32_t min = 0; + int32_t max = 0; + REQUIRE(computeRange(targets, samples, 4, 319, min, max)); + CHECK_EQ(min, 100); + CHECK_EQ(max, 738); +} + +TEST_CASE("computeRange gives the same range when the targets are in another order of the axes") { + // The first two targets are on the left and the other two on the right, or the other way around + const int32_t targets[] = { 296, 24, 24, 296 }; + int32_t samples[4]; + for (int i = 0; i < 4; i++) { + samples[i] = 50 + 3 * targets[i]; + } + int32_t min = 0; + int32_t max = 0; + REQUIRE(computeRange(targets, samples, 4, 319, min, max)); + CHECK_EQ(min, 50); + CHECK_EQ(max, 50 + 3 * 319); +} + +TEST_CASE("computeRange rejects an inverted axis and identical positions") { + int32_t min = 0; + int32_t max = 0; + const int32_t targets[] = { 24, 296 }; + const int32_t inverted[] = { 900, 100 }; + CHECK_FALSE(computeRange(targets, inverted, 2, 319, min, max)); + const int32_t samePosition[] = { 24, 24 }; + const int32_t samples[] = { 100, 120 }; + CHECK_FALSE(computeRange(samePosition, samples, 2, 319, min, max)); + CHECK_FALSE(computeRange(targets, samples, 1, 319, min, max)); +} + +TEST_CASE("a calibration taken on a rotated display is the same as one on the native display") { + constexpr int32_t width = 320; + constexpr int32_t height = 480; + // The sensor: raw x = 40 + 2.5 * x, raw y = 25 + 1.8 * y, in native pixels + auto sense = [](Point native) { return Point { 40 + native.x * 5 / 2, 25 + native.y * 9 / 5 }; }; + + int32_t expectedXMin = 0, expectedXMax = 0, expectedYMin = 0, expectedYMax = 0; + { + const Point natives[] = { { 24, 24 }, { 296, 24 }, { 296, 456 }, { 24, 456 } }; + int32_t tx[4], ty[4], sx[4], sy[4]; + for (int i = 0; i < 4; i++) { + tx[i] = natives[i].x; ty[i] = natives[i].y; + sx[i] = sense(natives[i]).x; sy[i] = sense(natives[i]).y; + } + REQUIRE(computeRange(tx, sx, 4, width - 1, expectedXMin, expectedXMax)); + REQUIRE(computeRange(ty, sy, 4, height - 1, expectedYMin, expectedYMax)); + } + + for (auto rotation : { Rotation::Rotate90, Rotation::Rotate180, Rotation::Rotate270 }) { + // The targets are drawn in the rotated display, and the raw sensor values are rotated by LVGL like any point + const Point nativeTargets[] = { { 24, 24 }, { 296, 24 }, { 296, 456 }, { 24, 456 } }; + int32_t tx[4], ty[4], sx[4], sy[4]; + for (int i = 0; i < 4; i++) { + const auto shownTarget = rotateLikeLvgl(nativeTargets[i], rotation, width, height); + const auto shownSample = rotateLikeLvgl(sense(nativeTargets[i]), rotation, width, height); + // The raw values exceed the display, so they are rotated with the same formula + const auto target = toNativePoint(shownTarget, rotation, width, height); + const auto sample = toNativePoint(shownSample, rotation, width, height); + tx[i] = target.x; ty[i] = target.y; sx[i] = sample.x; sy[i] = sample.y; + } + int32_t xMin = 0, xMax = 0, yMin = 0, yMax = 0; + REQUIRE(computeRange(tx, sx, 4, width - 1, xMin, xMax)); + REQUIRE(computeRange(ty, sy, 4, height - 1, yMin, yMax)); + CHECK_EQ(xMin, expectedXMin); + CHECK_EQ(xMax, expectedXMax); + CHECK_EQ(yMin, expectedYMin); + CHECK_EQ(yMax, expectedYMax); + } +} diff --git a/TactilityKernel/include/tactility/memory.h b/TactilityKernel/include/tactility/memory.h index d388cebab..4002aba14 100644 --- a/TactilityKernel/include/tactility/memory.h +++ b/TactilityKernel/include/tactility/memory.h @@ -103,9 +103,7 @@ void* memory_calloc_with_policy(size_t count, size_t size, const struct MemoryPo * @param[in] size number of bytes to allocate * @return the allocated memory, or NULL on failure */ -inline void* memory_alloc(size_t size) { - return memory_alloc_with_policy(size, &MEMORY_POLICY_DEFAULT); -} +void* memory_alloc(size_t size); /** * @brief Allocates zero-initialized memory using MEMORY_POLICY_DEFAULT. @@ -113,9 +111,7 @@ inline void* memory_alloc(size_t size) { * @param[in] size size of each element in bytes * @return the allocated memory, or NULL on failure */ -inline void* memory_calloc(size_t count, size_t size) { - return memory_calloc_with_policy(count, size, &MEMORY_POLICY_DEFAULT); -} +void* memory_calloc(size_t count, size_t size); /** * @brief Resizes a previous allocation using MEMORY_POLICY_DEFAULT. See memory_realloc_with_policy(). @@ -123,9 +119,7 @@ inline void* memory_calloc(size_t count, size_t size) { * @param[in] size new memory size in bytes * @return the (possibly moved) allocated memory, or NULL on failure - in which case ptr is left untouched */ -inline void* memory_realloc(void* ptr, size_t size) { - return memory_realloc_with_policy(ptr, size, &MEMORY_POLICY_DEFAULT); -} +void* memory_realloc(void* ptr, size_t size); /** * @brief Frees memory previously returned by one of the memory_* allocation functions. diff --git a/TactilityKernel/source/memory.cpp b/TactilityKernel/source/memory.cpp index 2afb71c1c..340ba7de9 100644 --- a/TactilityKernel/source/memory.cpp +++ b/TactilityKernel/source/memory.cpp @@ -24,6 +24,18 @@ const struct MemoryPolicy MEMORY_POLICY_DEFAULT = { .alignment = 0, }; +void* memory_alloc(size_t size) { + return memory_alloc_with_policy(size, &MEMORY_POLICY_DEFAULT); +} + +void* memory_calloc(size_t count, size_t size) { + return memory_calloc_with_policy(count, size, &MEMORY_POLICY_DEFAULT); +} + +void* memory_realloc(void* ptr, size_t size) { + return memory_realloc_with_policy(ptr, size, &MEMORY_POLICY_DEFAULT); +} + size_t memory_heap_total() { #ifdef ESP_PLATFORM return heap_caps_get_total_size(MALLOC_CAP_INTERNAL); diff --git a/device.py b/device.py index 0651b3e86..3a421e496 100755 --- a/device.py +++ b/device.py @@ -213,6 +213,9 @@ def write_flash_variables(output_file, device_properties: dict): output_file.write("# Flash\n") flash_size_number = flash_size[:-2] output_file.write(f"CONFIG_ESPTOOLPY_FLASHSIZE_{flash_size_number}MB=y\n") + if flash_size_number == "4": + output_file.write("# The firmware doesn't fit in 4MB of flash when it is optimized for debugging\n") + output_file.write("CONFIG_COMPILER_OPTIMIZATION_SIZE=y\n") flash_mode = get_property_or_default(device_properties, "hardware.flashMode", 'QIO') output_file.write(f"CONFIG_FLASHMODE_{flash_mode}=y\n") esptool_flash_freq = get_property_or_none(device_properties, "hardware.esptoolFlashFreq") @@ -337,6 +340,12 @@ def write_lvgl_variables(output_file, device_properties: dict): if not 0 <= percent <= 100: exit_with_error(f"{key} must be between 0 and 100, but was: {percent}") output_file.write(f"{config}={percent}\n") + draw_buffer_lines_text = get_property_or_none(device_properties, "lvgl.drawBufferLines") + if draw_buffer_lines_text is not None: + draw_buffer_lines = safe_int(draw_buffer_lines_text, f"lvgl.drawBufferLines must be an integer, but was: '{draw_buffer_lines_text}'") + if not 0 <= draw_buffer_lines <= 4096: + exit_with_error(f"lvgl.drawBufferLines must be between 0 and 4096, but was: {draw_buffer_lines}") + output_file.write(f"CONFIG_TT_LVGL_DRAW_BUFFER_LINES={draw_buffer_lines}\n") font_size_text = get_property_or_none(device_properties, "font.defaultSize") if font_size_text is None: font_size_text = get_property_or_default(device_properties, "lvgl.fontSize", "14") From bf3b07f77261096f4d52dd12aa704393d0baef94 Mon Sep 17 00:00:00 2001 From: Ken Van Hoeylandt Date: Sat, 14 Nov 2026 11:31:34 +0100 Subject: [PATCH 06/12] Fixes --- .../elecrow,crowpanel-advance-35.dts | 2 + .../bindings/ilitek,ili9488.yaml | 4 ++ .../ili9488-module/include/drivers/ili9488.h | 2 + Drivers/ili9488-module/source/ili9488.cpp | 2 +- .../lvgl-module/source/devices/display.cpp | 5 ++ Tactility/CMakeLists.txt | 3 +- .../app/touchcalibration/TouchCalibration.cpp | 70 +++++++++++++------ TactilityKernel/source/symbols.c | 3 + 8 files changed, 67 insertions(+), 24 deletions(-) diff --git a/Devices/elecrow-crowpanel-advance-35/elecrow,crowpanel-advance-35.dts b/Devices/elecrow-crowpanel-advance-35/elecrow,crowpanel-advance-35.dts index 0e5ef925f..7fc36595c 100644 --- a/Devices/elecrow-crowpanel-advance-35/elecrow,crowpanel-advance-35.dts +++ b/Devices/elecrow-crowpanel-advance-35/elecrow,crowpanel-advance-35.dts @@ -75,6 +75,8 @@ horizontal-resolution = <320>; vertical-resolution = <480>; invert-color; + ips; + mirror-x; color-conversion-buffer-size = <2560>; pixel-clock-hz = <40000000>; pin-dc = <&gpio0 41 GPIO_FLAG_NONE>; diff --git a/Drivers/ili9488-module/bindings/ilitek,ili9488.yaml b/Drivers/ili9488-module/bindings/ilitek,ili9488.yaml index bd1b7b019..2df73b2de 100644 --- a/Drivers/ili9488-module/bindings/ilitek,ili9488.yaml +++ b/Drivers/ili9488-module/bindings/ilitek,ili9488.yaml @@ -41,6 +41,10 @@ properties: type: boolean default: true description: Use BGR element order instead of RGB + ips: + type: boolean + default: false + description: Use the initialization for IPS panels, with their own power, VCOM and gamma settings, instead of the one for TN panels. A wrong one can leave a ghost image on the screen. bits-per-pixel: type: int default: 18 diff --git a/Drivers/ili9488-module/include/drivers/ili9488.h b/Drivers/ili9488-module/include/drivers/ili9488.h index 1f060078a..ad4c21c6f 100644 --- a/Drivers/ili9488-module/include/drivers/ili9488.h +++ b/Drivers/ili9488-module/include/drivers/ili9488.h @@ -21,6 +21,8 @@ struct Ili9488Config { bool mirror_y; bool invert_color; bool bgr_order; + // Initialize the panel with the settings for IPS panels instead of TN panels + bool ips; uint32_t bits_per_pixel; // Size (in pixels) of the internal buffer the panel driver uses to convert // 16bpp draw data to the panel's native 18bpp format. diff --git a/Drivers/ili9488-module/source/ili9488.cpp b/Drivers/ili9488-module/source/ili9488.cpp index 2a9900b21..6094b317b 100644 --- a/Drivers/ili9488-module/source/ili9488.cpp +++ b/Drivers/ili9488-module/source/ili9488.cpp @@ -128,7 +128,7 @@ static error_t start(Device* device) { // Unlike st7789/ili9341, ili9488 needs an internal conversion buffer: over SPI the // panel only accepts its native 18bpp format, so the driver repacks each transfer through // this buffer. - ret = esp_lcd_new_panel_ili9488(internal->io_handle, &panel_config, config->color_conversion_buffer_size, &internal->panel_handle); + ret = (config->ips ? esp_lcd_new_panel_ili9488_ips : esp_lcd_new_panel_ili9488)(internal->io_handle, &panel_config, config->color_conversion_buffer_size, &internal->panel_handle); if (ret != ESP_OK) { LOG_E(TAG, "Failed to create panel: %s", esp_err_to_name(ret)); esp_lcd_panel_io_del(internal->io_handle); diff --git a/Modules/lvgl-module/source/devices/display.cpp b/Modules/lvgl-module/source/devices/display.cpp index 1e64bebeb..b85ff1ca0 100644 --- a/Modules/lvgl-module/source/devices/display.cpp +++ b/Modules/lvgl-module/source/devices/display.cpp @@ -437,6 +437,11 @@ error_t lvgl_display_add(struct Device* device, const struct LvglDisplayConfig* } else { uint16_t buf_height = config->force_full_frame || config->buffer_height == 0 ? vres : config->buffer_height; + // A 90 or 270 degree rotation makes one logical row vres pixels wide, and the buffer must hold at least one such row + const uint16_t min_lines = (uint16_t)((vres + hres - 1) / hres); + if (buf_height < min_lines) { + buf_height = min_lines; + } // LVGL rounds the size it needs for an area up to LV_DRAW_BUF_ALIGN buf_size_bytes = LV_ROUND_UP((size_t)hres * buf_height * bpp, LV_DRAW_BUF_ALIGN); diff --git a/Tactility/CMakeLists.txt b/Tactility/CMakeLists.txt index 5429c6ae8..2579e52db 100644 --- a/Tactility/CMakeLists.txt +++ b/Tactility/CMakeLists.txt @@ -62,7 +62,8 @@ list(APPEND REQUIRES_LIST set(TT_AUDIO_MODULES_ENABLED TRUE) if (EXISTS "${DEVICETREE_LOCATION}/device.properties") file(READ "${DEVICETREE_LOCATION}/device.properties" device_properties_audio_content) - if (device_properties_audio_content MATCHES "(^|\n)modules\\.audio=false") + # The properties parser accepts spaces around the key and the value + if (device_properties_audio_content MATCHES "(^|\n)[ \t]*modules\\.audio[ \t]*=[ \t]*false[ \t]*(\r|\n|$)") set(TT_AUDIO_MODULES_ENABLED FALSE) endif () endif () diff --git a/Tactility/Source/app/touchcalibration/TouchCalibration.cpp b/Tactility/Source/app/touchcalibration/TouchCalibration.cpp index 45065e5e2..854d8d0ef 100644 --- a/Tactility/Source/app/touchcalibration/TouchCalibration.cpp +++ b/Tactility/Source/app/touchcalibration/TouchCalibration.cpp @@ -48,6 +48,12 @@ struct Context { uint8_t sampleCount = 0; bool calibrationApplied = false; + // Signalled by the last tap, so the app task fits and saves the calibration instead of the LVGL task + TaskEventGroup* eventGroup = nullptr; + uint32_t finishBit = 0; + // Set with the LVGL lock held, when the outcome is shown: taps before that don't close the app + bool finished = false; + lv_obj_t* root = nullptr; lv_obj_t* target = nullptr; lv_obj_t* titleLabel = nullptr; @@ -84,15 +90,30 @@ void updateUi(Context* ctx) { } } -// Drives the on-screen outcome text/state; the actual result (Ok/Error) is reported to the -// caller from onPress() below, via ctx->calibrationApplied, once the user taps to dismiss. +// Shows the outcome. The result (Ok/Error) is reported to the caller by appMain, via ctx->calibrationApplied, +// once the user taps to dismiss. +// Takes the LVGL lock, as it runs on the app task. +void showOutcome(Context* ctx, const char* title, const char* hint) { + lvgl_lock(); + if (ctx->titleLabel != nullptr && ctx->hintLabel != nullptr && ctx->target != nullptr) { + lv_label_set_text(ctx->titleLabel, title); + lv_label_set_text(ctx->hintLabel, hint); + lv_obj_set_hidden(ctx->target, true); + } + ctx->finished = true; + lvgl_unlock(); +} + +// Fits the calibration to the taps and saves it, which reads and writes files, so it runs on the app task. void finishCalibration(Context* ctx) { // The calibration is applied in the native orientation of the panel, before LVGL rotates the points. // The targets are shown, and the taps are reported, in the rotated display, so both go back to native first. + lvgl_lock(); auto* display = lv_display_get_default(); const int32_t nativeWidth = lv_display_get_original_horizontal_resolution(display); const int32_t nativeHeight = lv_display_get_original_vertical_resolution(display); const auto rotation = static_cast(lv_display_get_rotation(display)); + lvgl_unlock(); int32_t targetX[4], targetY[4], sampleX[4], sampleY[4]; for (int i = 0; i < 4; i++) { @@ -108,9 +129,7 @@ void finishCalibration(Context* ctx) { int32_t xMin, xMax, yMin, yMax; if (!computeRange(targetX, sampleX, 4, nativeWidth - 1, xMin, xMax) || !computeRange(targetY, sampleY, 4, nativeHeight - 1, yMin, yMax)) { - lv_label_set_text(ctx->titleLabel, "Calibration Failed"); - lv_label_set_text(ctx->hintLabel, "Range invalid. Tap to close."); - lv_obj_set_hidden(ctx->target, true); + showOutcome(ctx, "Calibration Failed", "Range invalid. Tap to close."); return; } @@ -122,16 +141,12 @@ void finishCalibration(Context* ctx) { settings.yMax = yMax; if (!settings::touch::isValid(settings)) { - lv_label_set_text(ctx->titleLabel, "Calibration Failed"); - lv_label_set_text(ctx->hintLabel, "Range invalid. Tap to close."); - lv_obj_set_hidden(ctx->target, true); + showOutcome(ctx, "Calibration Failed", "Range invalid. Tap to close."); return; } if (!settings::touch::save(settings)) { - lv_label_set_text(ctx->titleLabel, "Calibration Failed"); - lv_label_set_text(ctx->hintLabel, "Unable to save settings. Tap to close."); - lv_obj_set_hidden(ctx->target, true); + showOutcome(ctx, "Calibration Failed", "Unable to save settings. Tap to close."); return; } @@ -150,9 +165,7 @@ void finishCalibration(Context* ctx) { ctx->calibrationApplied = true; LOG_I(TAG, "Saved calibration x=[%d, %d] y=[%d, %d]", xMin, xMax, yMin, yMax); - lv_label_set_text(ctx->titleLabel, "Calibration Complete"); - lv_label_set_text(ctx->hintLabel, "Touch anywhere to continue."); - lv_obj_set_hidden(ctx->target, true); + showOutcome(ctx, "Calibration Complete", "Touch anywhere to continue."); } void onPress(lv_event_t* event) { @@ -178,12 +191,15 @@ void onPress(lv_event_t* event) { if (ctx->sampleCount < 4) { updateUi(ctx); } else { - finishCalibration(ctx); + task_event_group_signal(ctx->eventGroup, ctx->finishBit); } return; } - app_event_emit_close(ctx->appInstanceId); + // Taps while the calibration is being saved are ignored + if (ctx->finished) { + app_event_emit_close(ctx->appInstanceId); + } } void createWidgets(lv_obj_t* parent, void* userData) { @@ -253,6 +269,8 @@ int32_t appMain(int argc, char* argv[]) { TaskEventGroup event_group {}; task_event_group_construct(&event_group); + ctx.eventGroup = &event_group; + check(task_event_group_claim_bit(&event_group, &ctx.finishBit) == ERROR_NONE); AppEventSubscription sub {}; check(app_event_subscribe(&sub, &event_group) == ERROR_NONE); @@ -261,7 +279,12 @@ int32_t appMain(int argc, char* argv[]) { bool shouldClose = false; while (!shouldClose) { - task_event_group_wait_any(&event_group, nullptr, portMAX_DELAY); + uint32_t flags = 0; + task_event_group_wait_any(&event_group, &flags, portMAX_DELAY); + + if (flags & ctx.finishBit) { + finishCalibration(&ctx); + } AppEvent event {}; while (app_event_poll(&sub, &event) == ERROR_NONE) { @@ -278,24 +301,27 @@ int32_t appMain(int argc, char* argv[]) { window_manager_remove(window); check(app_event_unsubscribe(&sub) == ERROR_NONE); + task_event_group_release_bit(&event_group, ctx.finishBit); task_event_group_destruct(&event_group); // finishCalibration() already applied a new calibration on success. On cancel/failure, // restore whatever calibration was on disk before the block above cleared it. if (!ctx.calibrationApplied) { settings::touch::TouchCalibrationSettings settings; - lvgl_lock(); - auto* endIndev = lvgl_pointer_get_default(); - if (endIndev != nullptr && settings::touch::load(settings) && settings.enabled && settings::touch::isValid(settings)) { + if (settings::touch::load(settings) && settings.enabled && settings::touch::isValid(settings)) { LvglPointerCalibration calibration = { .x_min = settings.xMin, .x_max = settings.xMax, .y_min = settings.yMin, .y_max = settings.yMax, }; - lvgl_pointer_set_calibration(endIndev, &calibration); + lvgl_lock(); + auto* endIndev = lvgl_pointer_get_default(); + if (endIndev != nullptr) { + lvgl_pointer_set_calibration(endIndev, &calibration); + } + lvgl_unlock(); } - lvgl_unlock(); } return ctx.calibrationApplied ? 0 : 2; // Ok : Error diff --git a/TactilityKernel/source/symbols.c b/TactilityKernel/source/symbols.c index bdb4b6467..f4e53b65d 100644 --- a/TactilityKernel/source/symbols.c +++ b/TactilityKernel/source/symbols.c @@ -220,6 +220,9 @@ const struct ModuleSymbol KERNEL_SYMBOLS[] = { DEFINE_MODULE_SYMBOL(memory_alloc_with_policy), DEFINE_MODULE_SYMBOL(memory_realloc_with_policy), DEFINE_MODULE_SYMBOL(memory_calloc_with_policy), + DEFINE_MODULE_SYMBOL(memory_alloc), + DEFINE_MODULE_SYMBOL(memory_calloc), + DEFINE_MODULE_SYMBOL(memory_realloc), DEFINE_MODULE_SYMBOL(memory_free), DEFINE_MODULE_SYMBOL(memory_heap_free), DEFINE_MODULE_SYMBOL(memory_heap_total), From 28240e8bcb58b490e6dfdb0d7559c272c83566bc Mon Sep 17 00:00:00 2001 From: Ken Van Hoeylandt Date: Sat, 14 Nov 2026 12:02:02 +0100 Subject: [PATCH 07/12] Fixes --- Drivers/ili9488-module/source/ili9488.cpp | 19 ++- .../lvgl-module/source/devices/keyboard.cpp | 114 ++++++++++++++++-- .../lvgl-module/source/widgets/toolbar.cpp | 8 +- 3 files changed, 123 insertions(+), 18 deletions(-) diff --git a/Drivers/ili9488-module/source/ili9488.cpp b/Drivers/ili9488-module/source/ili9488.cpp index 6094b317b..819795528 100644 --- a/Drivers/ili9488-module/source/ili9488.cpp +++ b/Drivers/ili9488-module/source/ili9488.cpp @@ -219,14 +219,11 @@ static error_t ili9488_init(Device* device) { return result; } +static constexpr uint32_t DRAW_TIMEOUT_MS = 500; + static error_t ili9488_draw_bitmap(Device* device, int32_t x_start, int32_t y_start, int32_t x_end, int32_t y_end, const void* color_data) { auto* internal = static_cast(device_get_driver_data(device)); - // Drain any stale signal left over from a prior non-draw transaction (bring-up commands like - // reset/gap also complete through on_color_trans_done), so the take() below can only be - // satisfied by this draw's own transfer completing. - xSemaphoreTake(internal->draw_done_semaphore, 0); - // The panel driver converts a whole area through its conversion buffer and doesn't check bounds, // so a larger area is sent in strips of rows that fit in that buffer. The conversion buffer is // reused by the next strip, which is why each strip is waited for. @@ -235,6 +232,11 @@ static error_t ili9488_draw_bitmap(Device* device, int32_t x_start, int32_t y_st const auto* pixels = static_cast(color_data); spi_controller_lock(internal->spi_controller); + // Drain under the bus lock so that no other draw can consume this draw's completion signal. + // This also clears stale signals from non-draw transactions (bring-up commands like reset/gap + // also complete through on_color_trans_done), so the take() below can only be satisfied by this + // draw's own transfer completing. + xSemaphoreTake(internal->draw_done_semaphore, 0); for (int32_t y = y_start; y < y_end; y += strip_rows) { const int32_t strip_end = std::min(y + strip_rows, y_end); esp_err_t ret = esp_lcd_panel_draw_bitmap(internal->panel_handle, x_start, y, x_end, strip_end, pixels); @@ -250,7 +252,12 @@ static error_t ili9488_draw_bitmap(Device* device, int32_t x_start, int32_t y_st // bus lock across the wait too, not just the queueing call: the command/data phases aren't // wrapped in their own acquire_bus by esp_lcd_panel_io_spi, so another bus user could otherwise // interleave with this transfer while it's still in flight. - xSemaphoreTake(internal->draw_done_semaphore, portMAX_DELAY); + // The panel component ignores a failed color submission and returns ESP_OK, so no completion + // signal would ever arrive. A bounded wait keeps the bus lock from being held forever. + if (xSemaphoreTake(internal->draw_done_semaphore, pdMS_TO_TICKS(DRAW_TIMEOUT_MS)) != pdTRUE) { + spi_controller_unlock(internal->spi_controller); + return ERROR_TIMEOUT; + } pixels += static_cast(strip_end - y) * width; } spi_controller_unlock(internal->spi_controller); diff --git a/Modules/lvgl-module/source/devices/keyboard.cpp b/Modules/lvgl-module/source/devices/keyboard.cpp index 4fcbf38be..6d014ec80 100644 --- a/Modules/lvgl-module/source/devices/keyboard.cpp +++ b/Modules/lvgl-module/source/devices/keyboard.cpp @@ -16,8 +16,13 @@ static LvglSoftwareKeyboard last_software_keyboard = { .object = nullptr }; -// The top-level object that is moved up to keep the textarea above the software keyboard +// The top-level object that is made shorter to keep the textarea above the software keyboard, and its height before that +static lv_obj_t* resized_object; +static int32_t resized_original_height; +// The top-level object that is moved up when making it shorter wasn't enough to show the textarea static lv_obj_t* panned_object; +// The top-level object of the textarea that the keyboard is shown for +static lv_obj_t* active_top_object; static lv_group_t* keyboard_group; // The group that keypad indevs are attached to: keyboard_group, or the group of an overlay @@ -244,6 +249,8 @@ void lvgl_hardware_keyboard_remove_custom(lv_indev_t* indev) { } static void lvgl_software_keyboard_unpan(); +static void lvgl_software_keyboard_pan(LvglSoftwareKeyboard* keyboard, lv_obj_t* textarea); +static void lvgl_software_keyboard_follow_cursor(LvglSoftwareKeyboard* keyboard, lv_obj_t* textarea); static void textarea_show_keyboard(lv_event_t* event) { // Re-checked here rather than gated once at lvgl_keyboard_add_textarea() time, so a hardware @@ -258,6 +265,18 @@ static void textarea_show_keyboard(lv_event_t* event) { } } +// A multi-line textarea can be as high as the screen, so it is the line with the cursor that has to stay above the keyboard +static void textarea_cursor_moved(lv_event_t* event) { + if (last_software_keyboard.object == nullptr || lv_obj_is_hidden(last_software_keyboard.object)) { + return; + } + lv_obj_t* target = lv_event_get_current_target_obj(event); + if (lv_keyboard_get_textarea(last_software_keyboard.object) != target) { + return; + } + lvgl_software_keyboard_follow_cursor(&last_software_keyboard, target); +} + static void textarea_hide_keyboard(lv_event_t* event) { if (last_software_keyboard.object == nullptr) { return; @@ -270,6 +289,19 @@ static void textarea_hide_keyboard(lv_event_t* event) { lvgl_software_keyboard_hide(&last_software_keyboard); } +// The keyboard outlives the textarea, and LVGL keeps the pointer to it +static void textarea_deleted(lv_event_t* event) { + if (last_software_keyboard.object == nullptr) { + return; + } + lv_obj_t* target = lv_event_get_current_target_obj(event); + if (lv_keyboard_get_textarea(last_software_keyboard.object) != target) { + return; + } + lvgl_software_keyboard_hide(&last_software_keyboard); + lv_keyboard_set_textarea(last_software_keyboard.object, nullptr); +} + void lvgl_software_keyboard_construct(LvglSoftwareKeyboard* keyboard, lv_obj_t* parent) { keyboard->object = lv_keyboard_create(parent); lv_obj_set_hidden(keyboard->object, true); @@ -282,14 +314,31 @@ void lvgl_software_keyboard_destruct(LvglSoftwareKeyboard* keyboard) { lv_obj_delete(keyboard->object); keyboard->object = nullptr; panned_object = nullptr; + resized_object = nullptr; + active_top_object = nullptr; last_software_keyboard = *keyboard; } -void lvgl_software_keyboard_show(LvglSoftwareKeyboard* keyboard, lv_obj_t* textarea) { - assert(keyboard->object != nullptr); - lv_obj_set_hidden(keyboard->object, false); - lv_keyboard_set_textarea(keyboard->object, textarea); +// The bottom of the area of the textarea that has to be visible: the line with the cursor, or the whole textarea when it is smaller +static int32_t textarea_visible_bottom(lv_obj_t* textarea) { + lv_area_t textarea_area; + lv_obj_get_coords(textarea, &textarea_area); + lv_obj_t* label = lv_textarea_get_label(textarea); + if (label == nullptr) { + return textarea_area.y2; + } + + lv_point_t cursor_position; + lv_label_get_letter_pos(label, lv_textarea_get_cursor_pos(textarea), &cursor_position); + lv_area_t label_area; + lv_obj_get_coords(label, &label_area); + const lv_font_t* font = lv_obj_get_style_text_font(label, LV_PART_MAIN); + const int32_t line_bottom = label_area.y1 + cursor_position.y + lv_font_get_line_height(font) + lv_obj_get_style_pad_bottom(textarea, LV_PART_MAIN); + return LV_MIN(textarea_area.y2, line_bottom); +} + +static void lvgl_software_keyboard_pan(LvglSoftwareKeyboard* keyboard, lv_obj_t* textarea) { lvgl_software_keyboard_unpan(); lv_obj_t* keyboard_parent = lv_obj_get_parent(keyboard->object); @@ -303,21 +352,63 @@ void lvgl_software_keyboard_show(LvglSoftwareKeyboard* keyboard, lv_obj_t* texta lv_obj_update_layout(keyboard->object); lv_area_t keyboard_area; - lv_area_t textarea_area; lv_obj_get_coords(keyboard->object, &keyboard_area); - lv_obj_get_coords(textarea, &textarea_area); - const int32_t overlap = textarea_area.y2 + LV_DPX(4) - keyboard_area.y1; + + // The app gets shorter, so it keeps its layout and the statusbar stays in view + lv_area_t top_area; + lv_obj_get_coords(top, &top_area); + const int32_t shorter_height = keyboard_area.y1 - top_area.y1; + if (shorter_height > 0 && shorter_height < lv_obj_get_height(top)) { + resized_original_height = lv_obj_get_style_height(top, LV_PART_MAIN); + resized_object = top; + lv_obj_set_height(top, shorter_height); + lv_obj_update_layout(top); + // A scrollable parent of the textarea shows it again, in the shorter space + lv_obj_scroll_to_view_recursive(textarea, LV_ANIM_OFF); + } + + active_top_object = top; + lvgl_software_keyboard_follow_cursor(keyboard, textarea); +} + +// An app with a fixed layout can still have the cursor below the keyboard, so then the app is moved up. +// The height is not changed again while typing, as that lays out the app and scrolls the textarea. +static void lvgl_software_keyboard_follow_cursor(LvglSoftwareKeyboard* keyboard, lv_obj_t* textarea) { + if (active_top_object == nullptr) { + return; + } + if (panned_object != nullptr) { + lv_obj_set_style_translate_y(panned_object, 0, LV_STATE_DEFAULT); + panned_object = nullptr; + } + + lv_obj_update_layout(keyboard->object); + lv_area_t keyboard_area; + lv_obj_get_coords(keyboard->object, &keyboard_area); + const int32_t overlap = textarea_visible_bottom(textarea) + LV_DPX(4) - keyboard_area.y1; if (overlap > 0) { - lv_obj_set_style_translate_y(top, -overlap, LV_STATE_DEFAULT); - panned_object = top; + lv_obj_set_style_translate_y(active_top_object, -overlap, LV_STATE_DEFAULT); + panned_object = active_top_object; } } +void lvgl_software_keyboard_show(LvglSoftwareKeyboard* keyboard, lv_obj_t* textarea) { + assert(keyboard->object != nullptr); + lv_obj_set_hidden(keyboard->object, false); + lv_keyboard_set_textarea(keyboard->object, textarea); + lvgl_software_keyboard_pan(keyboard, textarea); +} + static void lvgl_software_keyboard_unpan() { if (panned_object != nullptr) { lv_obj_set_style_translate_y(panned_object, 0, LV_STATE_DEFAULT); panned_object = nullptr; } + if (resized_object != nullptr) { + lv_obj_set_height(resized_object, resized_original_height); + resized_object = nullptr; + } + active_top_object = nullptr; } void lvgl_software_keyboard_hide(LvglSoftwareKeyboard* keyboard) { @@ -336,8 +427,11 @@ LvglSoftwareKeyboard* lvgl_software_keyboard_get_last() { void lvgl_keyboard_add_textarea(LvglSoftwareKeyboard* keyboard, lv_obj_t* textarea) { lv_obj_add_event_cb(textarea, textarea_show_keyboard, LV_EVENT_FOCUSED, nullptr); + lv_obj_add_event_cb(textarea, textarea_cursor_moved, LV_EVENT_VALUE_CHANGED, nullptr); + lv_obj_add_event_cb(textarea, textarea_cursor_moved, LV_EVENT_KEY, nullptr); lv_obj_add_event_cb(textarea, textarea_hide_keyboard, LV_EVENT_DEFOCUSED, nullptr); lv_obj_add_event_cb(textarea, textarea_hide_keyboard, LV_EVENT_READY, nullptr); + lv_obj_add_event_cb(textarea, textarea_deleted, LV_EVENT_DELETE, nullptr); lv_obj_add_event_cb(textarea, textarea_hide_keyboard, LV_EVENT_DELETE, nullptr); // lv_obj_t auto-remove themselves from the group when they are destroyed (last checked in LVGL 8.3) diff --git a/Modules/lvgl-module/source/widgets/toolbar.cpp b/Modules/lvgl-module/source/widgets/toolbar.cpp index c5becaaaf..7dd73c3a4 100644 --- a/Modules/lvgl-module/source/widgets/toolbar.cpp +++ b/Modules/lvgl-module/source/widgets/toolbar.cpp @@ -114,7 +114,7 @@ lv_obj_t* lvgl_toolbar_create(lv_obj_t* parent, const char* title) { // toolbar, so the area never exceeds the toolbar's own height. lv_obj_set_ext_click_area(toolbar->close_button, getActionButtonSize(size) / 2); toolbar->close_button_image = lv_image_create(toolbar->close_button); - lv_obj_align(toolbar->close_button_image, LV_ALIGN_CENTER, 0, 0); + lv_obj_align(toolbar->close_button_image, LV_ALIGN_CENTER, 1, 1); toolbar->title_label = lv_label_create(obj); lv_obj_set_style_text_font(toolbar->title_label, getToolbarFont(size), LV_STATE_DEFAULT); @@ -161,14 +161,18 @@ static lv_obj_t* toolbar_add_button_action(lv_obj_t* obj, const char* imageOrBut lv_obj_t* action_button = create_action_button(obj, lvgl_theme_get_size()); lv_obj_add_event_cb(action_button, callback, LV_EVENT_SHORT_CLICKED, user_data); lv_obj_t* button_content; + bool is_symbol = false; if (isImage) { button_content = lv_image_create(action_button); lv_image_set_src(button_content, imageOrButton); + is_symbol = lv_image_src_get_type(imageOrButton) == LV_IMAGE_SRC_SYMBOL; } else { button_content = lv_label_create(action_button); lv_label_set_text(button_content, imageOrButton); } - lv_obj_align(button_content, LV_ALIGN_CENTER, 0, 0); + // Symbol glyphs sit one pixel up and left of the button centre + int32_t symbol_offset = is_symbol ? 1 : 0; + lv_obj_align(button_content, LV_ALIGN_CENTER, symbol_offset, symbol_offset); return action_button; } From 50b87f7b8a0f4fea6ffded9bf0de5bcec7268bb3 Mon Sep 17 00:00:00 2001 From: Ken Van Hoeylandt Date: Sat, 14 Nov 2026 12:09:06 +0100 Subject: [PATCH 08/12] Set heltec spacing to 0 --- Devices/heltec-wifi-lora-32-v3/device.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Devices/heltec-wifi-lora-32-v3/device.properties b/Devices/heltec-wifi-lora-32-v3/device.properties index 026e749b6..3d04e898c 100644 --- a/Devices/heltec-wifi-lora-32-v3/device.properties +++ b/Devices/heltec-wifi-lora-32-v3/device.properties @@ -18,5 +18,5 @@ cdn.infoMessage=Due to the small size of the screen, the icons don't render prop lvgl.theme=Mono lvgl.colorDepth=16 -lvgl.uiSpacing=40 +lvgl.uiSpacing=0 lvgl.uiSize=0 From 223769768359aeb9364e5dcdd949969212f9d84f Mon Sep 17 00:00:00 2001 From: Ken Van Hoeylandt Date: Sat, 14 Nov 2026 12:24:49 +0100 Subject: [PATCH 09/12] Follow cursor --- Modules/lvgl-module/source/devices/keyboard.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/Modules/lvgl-module/source/devices/keyboard.cpp b/Modules/lvgl-module/source/devices/keyboard.cpp index 6d014ec80..80db67784 100644 --- a/Modules/lvgl-module/source/devices/keyboard.cpp +++ b/Modules/lvgl-module/source/devices/keyboard.cpp @@ -302,8 +302,18 @@ static void textarea_deleted(lv_event_t* event) { lv_keyboard_set_textarea(last_software_keyboard.object, nullptr); } +// Registered after the keyboard's own handler, so it runs once the arrow buttons moved the cursor +static void keyboard_key_pressed(lv_event_t* event) { + lv_obj_t* keyboard = lv_event_get_current_target_obj(event); + lv_obj_t* textarea = lv_keyboard_get_textarea(keyboard); + if (textarea != nullptr && !lv_obj_is_hidden(keyboard)) { + lvgl_software_keyboard_follow_cursor(&last_software_keyboard, textarea); + } +} + void lvgl_software_keyboard_construct(LvglSoftwareKeyboard* keyboard, lv_obj_t* parent) { keyboard->object = lv_keyboard_create(parent); + lv_obj_add_event_cb(keyboard->object, keyboard_key_pressed, LV_EVENT_VALUE_CHANGED, nullptr); lv_obj_set_hidden(keyboard->object, true); last_software_keyboard = *keyboard; } From e96f0b8d717c858ee1f5622269115cfca64e17f1 Mon Sep 17 00:00:00 2001 From: Ken Van Hoeylandt Date: Sat, 14 Nov 2026 12:54:40 +0100 Subject: [PATCH 10/12] Improvements and fixes --- Data/system/app_icon/default.svg | 2 +- Data/system/app_icon/tactility.appearance.svg | 2 +- Data/system/app_icon/tactility.apphub.svg | 2 +- .../app_icon/tactility.audiosettings.svg | 2 +- Data/system/app_icon/tactility.btmanage.svg | 2 +- Data/system/app_icon/tactility.camera.svg | 2 +- Data/system/app_icon/tactility.chat.svg | 2 +- .../system/app_icon/tactility.development.svg | 2 +- Data/system/app_icon/tactility.display.svg | 2 +- Data/system/app_icon/tactility.files.svg | 2 +- .../app_icon/tactility.grovesettings.svg | 2 +- Data/system/app_icon/tactility.i2cscanner.svg | 2 +- .../app_icon/tactility.keyboardsettings.svg | 2 +- .../app_icon/tactility.ledstripsettings.svg | 2 +- .../app_icon/tactility.locationsettings.svg | 2 +- Data/system/app_icon/tactility.maps.svg | 2 +- .../app_icon/tactility.meshchannels.svg | 2 +- .../app_icon/tactility.meshcontacts.svg | 2 +- .../app_icon/tactility.meshsettings.svg | 2 +- Data/system/app_icon/tactility.notes.svg | 2 +- Data/system/app_icon/tactility.power.svg | 2 +- Data/system/app_icon/tactility.systeminfo.svg | 2 +- Data/system/app_icon/tactility.terminal.svg | 2 +- .../app_icon/tactility.timedatesettings.svg | 2 +- .../app_icon/tactility.touchcalibration.svg | 2 +- .../app_icon/tactility.trackballsettings.svg | 2 +- .../system/app_icon/tactility.usbsettings.svg | 2 +- .../app_icon/tactility.vibrationsettings.svg | 2 +- Data/system/app_icon/tactility.wifimanage.svg | 2 +- Modules/lvgl-module/include/lvgl/svg.h | 8 +++ Modules/lvgl-module/source/svg.c | 32 ++++++++++ Modules/lvgl-module/source/symbols.c | 1 + Modules/lvgl-module/tests/source/svg_test.cpp | 38 ++++++++++++ Tactility/Private/Tactility/app/TileGrid.h | 1 + Tactility/Source/app/TileGrid.cpp | 59 ++++++++++++++----- Tactility/Source/app/launcher/AppsMode.cpp | 10 ++++ .../Source/app/launcher/SettingsMode.cpp | 3 + 37 files changed, 165 insertions(+), 45 deletions(-) diff --git a/Data/system/app_icon/default.svg b/Data/system/app_icon/default.svg index 8aa3538a3..8c86b7eab 100644 --- a/Data/system/app_icon/default.svg +++ b/Data/system/app_icon/default.svg @@ -1 +1 @@ - + diff --git a/Data/system/app_icon/tactility.appearance.svg b/Data/system/app_icon/tactility.appearance.svg index 7e27acc98..a75e7025b 100644 --- a/Data/system/app_icon/tactility.appearance.svg +++ b/Data/system/app_icon/tactility.appearance.svg @@ -1 +1 @@ - + diff --git a/Data/system/app_icon/tactility.apphub.svg b/Data/system/app_icon/tactility.apphub.svg index b3e1912e5..462619be6 100644 --- a/Data/system/app_icon/tactility.apphub.svg +++ b/Data/system/app_icon/tactility.apphub.svg @@ -1 +1 @@ - + diff --git a/Data/system/app_icon/tactility.audiosettings.svg b/Data/system/app_icon/tactility.audiosettings.svg index bd44fff75..6886bd1bb 100644 --- a/Data/system/app_icon/tactility.audiosettings.svg +++ b/Data/system/app_icon/tactility.audiosettings.svg @@ -1 +1 @@ - + diff --git a/Data/system/app_icon/tactility.btmanage.svg b/Data/system/app_icon/tactility.btmanage.svg index 99a51de51..f0ea5fd63 100644 --- a/Data/system/app_icon/tactility.btmanage.svg +++ b/Data/system/app_icon/tactility.btmanage.svg @@ -1 +1 @@ - + diff --git a/Data/system/app_icon/tactility.camera.svg b/Data/system/app_icon/tactility.camera.svg index 0cf101bd8..08f9d55eb 100644 --- a/Data/system/app_icon/tactility.camera.svg +++ b/Data/system/app_icon/tactility.camera.svg @@ -1 +1 @@ - + diff --git a/Data/system/app_icon/tactility.chat.svg b/Data/system/app_icon/tactility.chat.svg index efe07371c..467afbf71 100644 --- a/Data/system/app_icon/tactility.chat.svg +++ b/Data/system/app_icon/tactility.chat.svg @@ -1 +1 @@ - + diff --git a/Data/system/app_icon/tactility.development.svg b/Data/system/app_icon/tactility.development.svg index 959cf8599..c7733bad1 100644 --- a/Data/system/app_icon/tactility.development.svg +++ b/Data/system/app_icon/tactility.development.svg @@ -1 +1 @@ - + diff --git a/Data/system/app_icon/tactility.display.svg b/Data/system/app_icon/tactility.display.svg index 4bc6c41b5..65c8ecea9 100644 --- a/Data/system/app_icon/tactility.display.svg +++ b/Data/system/app_icon/tactility.display.svg @@ -1 +1 @@ - + diff --git a/Data/system/app_icon/tactility.files.svg b/Data/system/app_icon/tactility.files.svg index d66244542..730c08f97 100644 --- a/Data/system/app_icon/tactility.files.svg +++ b/Data/system/app_icon/tactility.files.svg @@ -1 +1 @@ - + diff --git a/Data/system/app_icon/tactility.grovesettings.svg b/Data/system/app_icon/tactility.grovesettings.svg index b1cc8c629..2eacf7261 100644 --- a/Data/system/app_icon/tactility.grovesettings.svg +++ b/Data/system/app_icon/tactility.grovesettings.svg @@ -1 +1 @@ - + diff --git a/Data/system/app_icon/tactility.i2cscanner.svg b/Data/system/app_icon/tactility.i2cscanner.svg index 6ebffc915..566c0eff8 100644 --- a/Data/system/app_icon/tactility.i2cscanner.svg +++ b/Data/system/app_icon/tactility.i2cscanner.svg @@ -1 +1 @@ - + diff --git a/Data/system/app_icon/tactility.keyboardsettings.svg b/Data/system/app_icon/tactility.keyboardsettings.svg index 5685bc685..299c8dbdb 100644 --- a/Data/system/app_icon/tactility.keyboardsettings.svg +++ b/Data/system/app_icon/tactility.keyboardsettings.svg @@ -1 +1 @@ - + diff --git a/Data/system/app_icon/tactility.ledstripsettings.svg b/Data/system/app_icon/tactility.ledstripsettings.svg index 73be715a7..0cafc3e6d 100644 --- a/Data/system/app_icon/tactility.ledstripsettings.svg +++ b/Data/system/app_icon/tactility.ledstripsettings.svg @@ -1 +1 @@ - + diff --git a/Data/system/app_icon/tactility.locationsettings.svg b/Data/system/app_icon/tactility.locationsettings.svg index df27a934e..cea36a0bb 100644 --- a/Data/system/app_icon/tactility.locationsettings.svg +++ b/Data/system/app_icon/tactility.locationsettings.svg @@ -1 +1 @@ - + diff --git a/Data/system/app_icon/tactility.maps.svg b/Data/system/app_icon/tactility.maps.svg index 8517674c8..2830323f3 100644 --- a/Data/system/app_icon/tactility.maps.svg +++ b/Data/system/app_icon/tactility.maps.svg @@ -1 +1 @@ - + diff --git a/Data/system/app_icon/tactility.meshchannels.svg b/Data/system/app_icon/tactility.meshchannels.svg index 762133368..a1dfae25e 100644 --- a/Data/system/app_icon/tactility.meshchannels.svg +++ b/Data/system/app_icon/tactility.meshchannels.svg @@ -1 +1 @@ - + diff --git a/Data/system/app_icon/tactility.meshcontacts.svg b/Data/system/app_icon/tactility.meshcontacts.svg index 7afbfcf97..c0d9e7598 100644 --- a/Data/system/app_icon/tactility.meshcontacts.svg +++ b/Data/system/app_icon/tactility.meshcontacts.svg @@ -1 +1 @@ - + diff --git a/Data/system/app_icon/tactility.meshsettings.svg b/Data/system/app_icon/tactility.meshsettings.svg index 1ab624ea3..9600a188f 100644 --- a/Data/system/app_icon/tactility.meshsettings.svg +++ b/Data/system/app_icon/tactility.meshsettings.svg @@ -1 +1 @@ - + diff --git a/Data/system/app_icon/tactility.notes.svg b/Data/system/app_icon/tactility.notes.svg index d92292569..298b8216b 100644 --- a/Data/system/app_icon/tactility.notes.svg +++ b/Data/system/app_icon/tactility.notes.svg @@ -1 +1 @@ - + diff --git a/Data/system/app_icon/tactility.power.svg b/Data/system/app_icon/tactility.power.svg index 6e67c5cf3..df150830d 100644 --- a/Data/system/app_icon/tactility.power.svg +++ b/Data/system/app_icon/tactility.power.svg @@ -1 +1 @@ - + diff --git a/Data/system/app_icon/tactility.systeminfo.svg b/Data/system/app_icon/tactility.systeminfo.svg index f3f01d7b9..63483adbe 100644 --- a/Data/system/app_icon/tactility.systeminfo.svg +++ b/Data/system/app_icon/tactility.systeminfo.svg @@ -1 +1 @@ - + diff --git a/Data/system/app_icon/tactility.terminal.svg b/Data/system/app_icon/tactility.terminal.svg index 274461e03..570a5be27 100644 --- a/Data/system/app_icon/tactility.terminal.svg +++ b/Data/system/app_icon/tactility.terminal.svg @@ -1 +1 @@ - + diff --git a/Data/system/app_icon/tactility.timedatesettings.svg b/Data/system/app_icon/tactility.timedatesettings.svg index 9e8142253..2f5207713 100644 --- a/Data/system/app_icon/tactility.timedatesettings.svg +++ b/Data/system/app_icon/tactility.timedatesettings.svg @@ -1 +1 @@ - + diff --git a/Data/system/app_icon/tactility.touchcalibration.svg b/Data/system/app_icon/tactility.touchcalibration.svg index 247c2709c..ced17a5ca 100644 --- a/Data/system/app_icon/tactility.touchcalibration.svg +++ b/Data/system/app_icon/tactility.touchcalibration.svg @@ -1 +1 @@ - + diff --git a/Data/system/app_icon/tactility.trackballsettings.svg b/Data/system/app_icon/tactility.trackballsettings.svg index 5363eeca3..bb1138669 100644 --- a/Data/system/app_icon/tactility.trackballsettings.svg +++ b/Data/system/app_icon/tactility.trackballsettings.svg @@ -1 +1 @@ - + diff --git a/Data/system/app_icon/tactility.usbsettings.svg b/Data/system/app_icon/tactility.usbsettings.svg index 6e7763e6f..e6e7e77cd 100644 --- a/Data/system/app_icon/tactility.usbsettings.svg +++ b/Data/system/app_icon/tactility.usbsettings.svg @@ -1 +1 @@ - + diff --git a/Data/system/app_icon/tactility.vibrationsettings.svg b/Data/system/app_icon/tactility.vibrationsettings.svg index bfb0dcb03..7449a82ac 100644 --- a/Data/system/app_icon/tactility.vibrationsettings.svg +++ b/Data/system/app_icon/tactility.vibrationsettings.svg @@ -1 +1 @@ - + diff --git a/Data/system/app_icon/tactility.wifimanage.svg b/Data/system/app_icon/tactility.wifimanage.svg index 158146dcf..1e469f085 100644 --- a/Data/system/app_icon/tactility.wifimanage.svg +++ b/Data/system/app_icon/tactility.wifimanage.svg @@ -1 +1 @@ - + diff --git a/Modules/lvgl-module/include/lvgl/svg.h b/Modules/lvgl-module/include/lvgl/svg.h index 6f945fdf1..e9d4c055c 100644 --- a/Modules/lvgl-module/include/lvgl/svg.h +++ b/Modules/lvgl-module/include/lvgl/svg.h @@ -54,6 +54,14 @@ lv_draw_buf_t* lvgl_svg_rasterize_file_variants( bool prefer_mono, uint32_t size, bool* out_is_mono ); +/** + * Rounds the corners of an ARGB8888 draw buffer by lowering the alpha of the pixels outside the corner arcs. + * Does nothing when the radius is 0. + * @param[in] draw_buf a square or rectangular ARGB8888 draw buffer + * @param[in] radius the corner radius in pixels + */ +void lvgl_svg_round_corners(lv_draw_buf_t* draw_buf, uint32_t radius); + #ifdef __cplusplus } #endif diff --git a/Modules/lvgl-module/source/svg.c b/Modules/lvgl-module/source/svg.c index 36079532d..ab8165f24 100644 --- a/Modules/lvgl-module/source/svg.c +++ b/Modules/lvgl-module/source/svg.c @@ -1,6 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 #include +#include #include #include #include @@ -125,3 +126,34 @@ lv_draw_buf_t* lvgl_svg_rasterize_file_variants( } return NULL; } + +void lvgl_svg_round_corners(lv_draw_buf_t* draw_buf, uint32_t radius) { + const uint32_t width = draw_buf->header.w; + const uint32_t height = draw_buf->header.h; + if (radius == 0) return; + if (radius > width / 2) radius = width / 2; + if (radius > height / 2) radius = height / 2; + + const float r = (float)radius; + for (uint32_t dy = 0; dy < radius; dy++) { + for (uint32_t dx = 0; dx < radius; dx++) { + // Pixel centre relative to the centre of the corner circle + const float px = r - (float)dx - 0.5f; + const float py = r - (float)dy - 0.5f; + const float distance = sqrtf(px * px + py * py); + // One pixel wide linear edge + float coverage = r - distance + 0.5f; + if (coverage >= 1.0f) continue; + if (coverage < 0.0f) coverage = 0.0f; + + const uint32_t xs[2] = { dx, width - 1 - dx }; + const uint32_t ys[2] = { dy, height - 1 - dy }; + for (int i = 0; i < 2; i++) { + for (int j = 0; j < 2; j++) { + lv_color32_t* row = (lv_color32_t*)(draw_buf->data + (size_t)ys[j] * draw_buf->header.stride); + row[xs[i]].alpha = (uint8_t)((float)row[xs[i]].alpha * coverage + 0.5f); + } + } + } + } +} diff --git a/Modules/lvgl-module/source/symbols.c b/Modules/lvgl-module/source/symbols.c index 443e7168a..4915c9780 100644 --- a/Modules/lvgl-module/source/symbols.c +++ b/Modules/lvgl-module/source/symbols.c @@ -125,6 +125,7 @@ const struct ModuleSymbol lvgl_module_symbols[] = { DEFINE_MODULE_SYMBOL(lvgl_svg_rasterize_file), DEFINE_MODULE_SYMBOL(lvgl_svg_rasterize_variants), DEFINE_MODULE_SYMBOL(lvgl_svg_rasterize_file_variants), + DEFINE_MODULE_SYMBOL(lvgl_svg_round_corners), // lvgl_badge DEFINE_MODULE_SYMBOL(lvgl_badge_create), // lvgl_focus_container diff --git a/Modules/lvgl-module/tests/source/svg_test.cpp b/Modules/lvgl-module/tests/source/svg_test.cpp index e93c30070..924354d64 100644 --- a/Modules/lvgl-module/tests/source/svg_test.cpp +++ b/Modules/lvgl-module/tests/source/svg_test.cpp @@ -179,3 +179,41 @@ TEST_CASE("lvgl_svg_rasterize_data rejects sizes whose pixel buffer would overfl CHECK_EQ(lvgl_svg_rasterize_data(SQUARE, length, UINT32_MAX), nullptr); lv_deinit(); } + +TEST_CASE("lvgl_svg_round_corners clears the corners and keeps the rest") { + lv_init(); + auto path = writeSvg("tt_svg_test_round.svg", + "" + ""); + + lv_draw_buf_t* buf = lvgl_svg_rasterize_file(path.c_str(), 32); + REQUIRE_NE(buf, nullptr); + lvgl_svg_round_corners(buf, 8); + CHECK_EQ(pixelAt(buf, 0, 0).alpha, 0); + CHECK_EQ(pixelAt(buf, 31, 0).alpha, 0); + CHECK_EQ(pixelAt(buf, 0, 31).alpha, 0); + CHECK_EQ(pixelAt(buf, 31, 31).alpha, 0); + CHECK_EQ(pixelAt(buf, 16, 0).alpha, 255); + CHECK_EQ(pixelAt(buf, 0, 16).alpha, 255); + CHECK_EQ(pixelAt(buf, 16, 16).alpha, 255); + CHECK_GT(pixelAt(buf, 2, 2).alpha, 0); + CHECK_LT(pixelAt(buf, 2, 2).alpha, 255); + lv_draw_buf_destroy(buf); + remove(path.c_str()); + lv_deinit(); +} + +TEST_CASE("lvgl_svg_round_corners with radius 0 changes nothing") { + lv_init(); + auto path = writeSvg("tt_svg_test_round0.svg", + "" + ""); + + lv_draw_buf_t* buf = lvgl_svg_rasterize_file(path.c_str(), 32); + REQUIRE_NE(buf, nullptr); + lvgl_svg_round_corners(buf, 0); + CHECK_EQ(pixelAt(buf, 0, 0).alpha, 255); + lv_draw_buf_destroy(buf); + remove(path.c_str()); + lv_deinit(); +} diff --git a/Tactility/Private/Tactility/app/TileGrid.h b/Tactility/Private/Tactility/app/TileGrid.h index cc28f38a7..cc5c22b32 100644 --- a/Tactility/Private/Tactility/app/TileGrid.h +++ b/Tactility/Private/Tactility/app/TileGrid.h @@ -185,6 +185,7 @@ class TileGrid final { static void onNextPressed(lv_event_t* e); static void onGridGesture(lv_event_t* e); static void onBottomBarFocused(lv_event_t* e); + static void onTileStateChanged(lv_event_t* e); static void onTileClicked(lv_event_t* e); static void onTileLongPressed(lv_event_t* e); static void onTileKey(lv_event_t* e); diff --git a/Tactility/Source/app/TileGrid.cpp b/Tactility/Source/app/TileGrid.cpp index 83716550e..7d584491a 100644 --- a/Tactility/Source/app/TileGrid.cpp +++ b/Tactility/Source/app/TileGrid.cpp @@ -5,7 +5,6 @@ #include #include #include -#include #include #include @@ -33,6 +32,8 @@ constexpr uint32_t MIN_LABEL_WIDTH_IN_FONT_SIZES = 6; struct PageLayout { int32_t iconSize; int32_t pad; + int32_t framePad; + int32_t labelGap; int32_t tileWidth; int32_t tileHeight; int32_t leftOffset; @@ -43,12 +44,15 @@ struct PageLayout { PageLayout computePageLayout(lv_obj_t* grid) { const auto icon_size = static_cast(lvgl_get_shared_icon_large_font_height()); const auto pad = icon_size / 16; + // The focus ring is drawn inside the frame, at most 2dp wide, and leaves 1dp to the icon + const auto frame_pad = LV_DPX(2) + LV_DPX(1); + const auto label_gap = LV_DPX(2); const auto gap = TILE_GAP; const auto text_height = lv_font_get_line_height(lvgl_get_text_font(FONT_SIZE_SMALL)); // The label needs room for a few characters, also when the icon font is smaller (e.g. a fallback) const auto text_min_width = static_cast(MIN_LABEL_WIDTH_IN_FONT_SIZES * lvgl_get_text_font_height(FONT_SIZE_SMALL)); const auto tile_min_width = std::max(2 * icon_size, text_min_width) + 2 * pad; - const auto tile_height = 2 * pad + icon_size + pad / 2 + text_height; + const auto tile_height = 2 * frame_pad + icon_size + label_gap + text_height + pad; const auto available_width = lv_obj_get_content_width(grid); const auto available_height = lv_obj_get_content_height(grid); const auto columns = std::max(1, (available_width + gap) / (tile_min_width + gap)); @@ -57,6 +61,8 @@ PageLayout computePageLayout(lv_obj_t* grid) { return { .iconSize = icon_size, .pad = pad, + .framePad = frame_pad, + .labelGap = label_gap, .tileWidth = tile_width, .tileHeight = tile_height, // The pixels that don't divide over the columns are split over both sides @@ -272,6 +278,15 @@ void TileGrid::onGridGesture(lv_event_t* e) { lv_async_call(direction == LV_DIR_LEFT ? onDeferredNextPage : onDeferredPreviousPage, self); } +void TileGrid::onTileStateChanged(lv_event_t* e) { + constexpr auto MIRRORED = static_cast(LV_STATE_FOCUSED | LV_STATE_FOCUS_KEY | LV_STATE_PRESSED | LV_STATE_CHECKED); + lv_obj_t* tile = lv_event_get_target_obj(e); + auto* frame = static_cast(lv_event_get_user_data(e)); + const lv_state_t state = lv_obj_get_state(tile); + lv_obj_remove_state(frame, static_cast(MIRRORED & ~state)); + lv_obj_add_state(frame, static_cast(MIRRORED & state)); +} + void TileGrid::onTileClicked(lv_event_t* e) { const auto* self = static_cast(lv_event_get_user_data(e)); self->callbacks.onClicked(*getTileItem(e), self->callbacks.userData); @@ -390,15 +405,31 @@ void TileGrid::populate() { for (uint32_t i = first; i < last; i++) { const auto& item = items[i]; - // The theme styles the tile as an icon button, including its focus and pressed states - lv_obj_t* tile = lvgl_icon_button_create(grid); + // The tile receives the input, its icon frame shows the focus, pressed and checked states of the theme's icon button + lv_obj_t* tile = lv_obj_create(grid); + lv_obj_remove_style_all(tile); lv_obj_set_size(tile, layout.tileWidth, layout.tileHeight); - lv_obj_set_style_pad_all(tile, layout.pad, LV_STATE_DEFAULT); - lv_obj_set_style_pad_row(tile, layout.pad / 2, LV_STATE_DEFAULT); + lv_obj_set_style_pad_bottom(tile, layout.pad, LV_STATE_DEFAULT); + lv_obj_set_style_pad_row(tile, layout.labelGap, LV_STATE_DEFAULT); lv_obj_set_flex_flow(tile, LV_FLEX_FLOW_COLUMN); lv_obj_set_flex_align(tile, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER); + lv_obj_set_clickable(tile, true); + lv_obj_set_click_focusable(tile, true); + lv_obj_set_scrollable(tile, false); lv_obj_set_user_data(tile, const_cast(&item)); + lv_obj_t* frame = lvgl_icon_button_create(tile); + lv_obj_set_size(frame, LV_SIZE_CONTENT, LV_SIZE_CONTENT); + lv_obj_set_style_pad_all(frame, layout.framePad, LV_STATE_DEFAULT); + // Concentric with the rounded corners of the icon, which have a radius of 22 in 96 + lv_obj_set_style_radius(frame, layout.iconSize * 22 / 96 + layout.framePad, LV_STATE_DEFAULT); + // Grid navigation only removes direct children from the input group, and the tile is the focus target + lv_group_remove_obj(frame); + lv_obj_set_clickable(frame, false); + lv_obj_set_click_focusable(frame, false); + lv_obj_set_scrollable(frame, false); + lv_obj_add_event_cb(tile, onTileStateChanged, LV_EVENT_STATE_CHANGED, frame); + const lv_image_dsc_t* image_src = item.image; const char* icon_text = item.icon; if (image_src == nullptr && icon_text == nullptr) { @@ -410,11 +441,11 @@ void TileGrid::populate() { } } if (image_src != nullptr) { - lv_obj_t* image = lv_image_create(tile); + lv_obj_t* image = lv_image_create(frame); lv_image_set_src(image, image_src); lv_obj_set_size(image, layout.iconSize, layout.iconSize); if (item.imageRecolor) { - lv_color_t color = lv_obj_get_style_text_color(tile, LV_PART_MAIN); + lv_color_t color = lv_obj_get_style_text_color(frame, LV_PART_MAIN); if (iconColor == IconColor::Primary) { color = lv_theme_get_color_primary(image); } else if (iconColor == IconColor::Secondary) { @@ -424,16 +455,18 @@ void TileGrid::populate() { lv_obj_set_style_image_recolor_opa(image, LV_OPA_COVER, LV_STATE_DEFAULT); } } else { - lv_obj_t* icon = lv_label_create(tile); + lv_obj_t* icon = lv_label_create(frame); lv_obj_set_style_text_font(icon, lvgl_get_shared_icon_large_font(), LV_STATE_DEFAULT); lv_obj_set_style_text_align(icon, LV_TEXT_ALIGN_CENTER, LV_STATE_DEFAULT); lv_obj_set_size(icon, layout.iconSize, layout.iconSize); lv_label_set_text(icon, icon_text != nullptr ? icon_text : ""); // A placeholder for an image that isn't loaded yet has the theme's text colour - lv_obj_set_style_text_color(icon, lv_obj_get_style_text_color(tile, LV_PART_MAIN), LV_STATE_DEFAULT); + lv_obj_set_style_text_color(icon, lv_obj_get_style_text_color(frame, LV_PART_MAIN), LV_STATE_DEFAULT); } lv_obj_t* label = lv_label_create(tile); + // Favourites have a label in the theme's secondary colour + lv_obj_set_style_text_color(label, item.highlighted ? lv_theme_get_color_secondary(label) : lv_obj_get_style_text_color(frame, LV_PART_MAIN), LV_STATE_DEFAULT); lv_obj_set_style_text_font(label, lvgl_get_text_font(FONT_SIZE_SMALL), LV_STATE_DEFAULT); lv_obj_set_style_text_align(label, LV_TEXT_ALIGN_CENTER, LV_STATE_DEFAULT); // Dots mode needs a fixed height, otherwise the label wraps instead of truncating @@ -441,12 +474,6 @@ void TileGrid::populate() { lv_label_set_long_mode(label, LV_LABEL_LONG_MODE_DOTS); lv_label_set_text(label, item.name.c_str()); - // A badge marks favourites, as it doesn't look like the focus indicator - if (item.highlighted) { - auto* badge = lvgl_badge_create(tile); - lv_obj_align(badge, LV_ALIGN_TOP_RIGHT, 0, 0); - } - lv_obj_add_event_cb(tile, onTileClicked, LV_EVENT_SHORT_CLICKED, this); if (callbacks.onLongPressed != nullptr) { lv_obj_add_event_cb(tile, onTileLongPressed, LV_EVENT_LONG_PRESSED, this); diff --git a/Tactility/Source/app/launcher/AppsMode.cpp b/Tactility/Source/app/launcher/AppsMode.cpp index b873baa65..bf659702f 100644 --- a/Tactility/Source/app/launcher/AppsMode.cpp +++ b/Tactility/Source/app/launcher/AppsMode.cpp @@ -302,6 +302,11 @@ void collectPackageApps(const AppPackage* package, void* context) { packages->push_back(::std::move(entry)); } +// Icons are square, the corner radius is the one of a 96 px icon with a 22 px radius +void roundIconCorners(lv_draw_buf_t* image, uint32_t size) { + lvgl_svg_round_corners(image, size * 22 / 96); +} + PackageIcon rasterizeBuiltIn(const BuiltInIconAsset& asset, uint32_t size, bool preferMono) { bool mono = false; auto* image = lvgl_svg_rasterize_variants( @@ -311,6 +316,8 @@ PackageIcon rasterizeBuiltIn(const BuiltInIconAsset& asset, uint32_t size, bool ); if (image == nullptr) { LOG_W(TAG, "Failed to rasterize the icon of %s", asset.id); + } else if (!mono) { + roundIconCorners(image, size); } return { asset.id, {}, {}, {}, image, mono, preferMono }; } @@ -400,6 +407,9 @@ void loadPackageIcons(void*) { LOG_W(TAG, "Failed to load the icon of %s", package.packageId.c_str()); continue; } + if (!mono) { + roundIconCorners(image, size); + } loaded.push_back({ package.packageId, ::std::move(package.appIds), colour_file, mono_file, image, mono, preferMono }); } diff --git a/Tactility/Source/app/launcher/SettingsMode.cpp b/Tactility/Source/app/launcher/SettingsMode.cpp index 96e74b665..03308a573 100644 --- a/Tactility/Source/app/launcher/SettingsMode.cpp +++ b/Tactility/Source/app/launcher/SettingsMode.cpp @@ -144,6 +144,9 @@ void loadSettingsIcons(void*) { reinterpret_cast(asset.mono), asset.monoSize, preferMono, size, &recolor[i] ); + if (images[i] != nullptr && !recolor[i]) { + lvgl_svg_round_corners(images[i], size * 22 / 96); + } } mutex_lock(&state.mutex); From b1a7c719269bb280d0feef463c20bae225a608e9 Mon Sep 17 00:00:00 2001 From: Ken Van Hoeylandt Date: Sat, 14 Nov 2026 13:48:15 +0100 Subject: [PATCH 11/12] Pre-load icons --- Tactility/Source/lvgl/Lvgl.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Tactility/Source/lvgl/Lvgl.cpp b/Tactility/Source/lvgl/Lvgl.cpp index 003a5cd25..318ae1b18 100644 --- a/Tactility/Source/lvgl/Lvgl.cpp +++ b/Tactility/Source/lvgl/Lvgl.cpp @@ -1,3 +1,4 @@ +#include #include #include @@ -166,6 +167,10 @@ static void onLvglStarted() { lv_obj_set_style_text_font(lv_layer_top(), text_font, LV_STATE_DEFAULT); lvgl_unlock(); + // The launcher shows the icons right away. Icons that are still current are kept. + app::launcher::loadPackageIcons(nullptr); + app::launcher::loadSettingsIcons(nullptr); + window_manager_configure(windowManagerScreenInit); check(module_ensure_started(&lvgl_window_manager_module) == ERROR_NONE); From bf72d0ab3267b2384b705d6c06e5e03374bfc379 Mon Sep 17 00:00:00 2001 From: Ken Van Hoeylandt Date: Sat, 14 Nov 2026 13:48:23 +0100 Subject: [PATCH 12/12] Undo offset --- Modules/lvgl-module/source/widgets/toolbar.cpp | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/Modules/lvgl-module/source/widgets/toolbar.cpp b/Modules/lvgl-module/source/widgets/toolbar.cpp index 7dd73c3a4..c5becaaaf 100644 --- a/Modules/lvgl-module/source/widgets/toolbar.cpp +++ b/Modules/lvgl-module/source/widgets/toolbar.cpp @@ -114,7 +114,7 @@ lv_obj_t* lvgl_toolbar_create(lv_obj_t* parent, const char* title) { // toolbar, so the area never exceeds the toolbar's own height. lv_obj_set_ext_click_area(toolbar->close_button, getActionButtonSize(size) / 2); toolbar->close_button_image = lv_image_create(toolbar->close_button); - lv_obj_align(toolbar->close_button_image, LV_ALIGN_CENTER, 1, 1); + lv_obj_align(toolbar->close_button_image, LV_ALIGN_CENTER, 0, 0); toolbar->title_label = lv_label_create(obj); lv_obj_set_style_text_font(toolbar->title_label, getToolbarFont(size), LV_STATE_DEFAULT); @@ -161,18 +161,14 @@ static lv_obj_t* toolbar_add_button_action(lv_obj_t* obj, const char* imageOrBut lv_obj_t* action_button = create_action_button(obj, lvgl_theme_get_size()); lv_obj_add_event_cb(action_button, callback, LV_EVENT_SHORT_CLICKED, user_data); lv_obj_t* button_content; - bool is_symbol = false; if (isImage) { button_content = lv_image_create(action_button); lv_image_set_src(button_content, imageOrButton); - is_symbol = lv_image_src_get_type(imageOrButton) == LV_IMAGE_SRC_SYMBOL; } else { button_content = lv_label_create(action_button); lv_label_set_text(button_content, imageOrButton); } - // Symbol glyphs sit one pixel up and left of the button centre - int32_t symbol_offset = is_symbol ? 1 : 0; - lv_obj_align(button_content, LV_ALIGN_CENTER, symbol_offset, symbol_offset); + lv_obj_align(button_content, LV_ALIGN_CENTER, 0, 0); return action_button; }