From c914383a9951992453f06e64d84ee643fde2f74e Mon Sep 17 00:00:00 2001 From: Waozi Date: Sun, 18 Oct 2026 14:38:12 -0300 Subject: [PATCH] Add device launcher shortcuts for installed apps --- docs/cells.md | 25 ++ .../java/xyz/waozi/inbe/AppShortcuts.java | 108 +++++++++ .../java/xyz/waozi/inbe/MainActivity.java | 16 ++ locales/cs.txt | 12 + locales/de.txt | 12 + locales/en.txt | 12 + locales/es.txt | 12 + locales/fr.txt | 12 + locales/id.txt | 12 + locales/it.txt | 12 + locales/ja.txt | 12 + locales/ko.txt | 12 + locales/pt.txt | 12 + locales/ru.txt | 12 + locales/zh.txt | 12 + mk/tests-app.mk | 4 + mk/tests-suite.mk | 2 +- mk/tests-ui.mk | 7 + src/app/app_launcher.zi | 27 ++- src/app/app_launcher_pins.zi | 90 ++++++++ src/platform/android/android_shortcuts.zi | 67 ++++++ src/platform/app_host.zi | 28 +++ src/platform/launcher_entry.zi | 72 ++++++ src/platform/launcher_icon.zi | 60 +++++ src/platform/launcher_shortcut.zi | 121 ++++++++++ src/platform/launcher_windows.zi | 134 +++++++++++ .../AppShortcutsTest.java | 76 +++++++ tests/android-text-selection/build.gradle | 2 +- tests/launcher_entry_behavior.zi | 28 +++ tests/launcher_entry_zi_test.sh | 23 ++ tests/launcher_shortcut_ui_test.py | 215 ++++++++++++++++++ tests/launcher_ui_test.py | 2 +- 32 files changed, 1247 insertions(+), 4 deletions(-) create mode 100644 droid/app/src/main/java/xyz/waozi/inbe/AppShortcuts.java create mode 100644 src/app/app_launcher_pins.zi create mode 100644 src/platform/android/android_shortcuts.zi create mode 100644 src/platform/launcher_entry.zi create mode 100644 src/platform/launcher_icon.zi create mode 100644 src/platform/launcher_shortcut.zi create mode 100644 src/platform/launcher_windows.zi create mode 100644 tests/android-text-selection/AppShortcutsTest.java create mode 100644 tests/launcher_entry_behavior.zi create mode 100644 tests/launcher_entry_zi_test.sh create mode 100644 tests/launcher_shortcut_ui_test.py diff --git a/docs/cells.md b/docs/cells.md index e88d722a0..5a13a0be5 100644 --- a/docs/cells.md +++ b/docs/cells.md @@ -635,6 +635,31 @@ compositions; moving those compositions into their bundles is required to finish the entirely portable architecture. Changes to their compiled UI or to native host capabilities still require a wrapper release. +## Device launcher entries + +Installed apps in Apps offer **Pin to launcher** on Android 8 and later when +its launcher supports pinned shortcuts, on Windows, and in native Linux and +AppImage builds. Android asks for confirmation on the home screen. Windows +adds a per-user Start menu shortcut; Linux adds a per-user application entry. +Each uses the app's name and mark and opens it without Inbe's surrounding +navigation. Repeating the action updates the same entry. + +These entries use the existing Inbe executable, packages, account and data; +Inbe must stay installed. They do not install another APK or a separate copy +of the data. Downloaded apps are addressed by their package name, so changing +their device-local slot does not change a saved shortcut. An app removed from +the account must be added again in Inbe before its shortcut can open it. + +Desktop entries invoke `--app NAME`; the older `--feature` option remains +available. Native Linux entries respect `XDG_DATA_HOME` and preserve an +explicit `APP_DATA_ROOT`. The action is hidden on the web, in Snap and in +Flatpak, where installing launchers needs a separate portal integration. +`make launcher-entry-test` checks identifier and desktop escaping rules; +`make launcher-shortcut-ui-test` checks pinning, icons, repeated pinning, +the desktop's actual entry parser, profile selection, bundled app launches and +a node app after its slot changes, on a private display. Android shortcut behavior is covered by +`make android-text-selection-test`. + ## Verification A new app version is published only with a passing phone check of its exact diff --git a/droid/app/src/main/java/xyz/waozi/inbe/AppShortcuts.java b/droid/app/src/main/java/xyz/waozi/inbe/AppShortcuts.java new file mode 100644 index 000000000..e4a63609a --- /dev/null +++ b/droid/app/src/main/java/xyz/waozi/inbe/AppShortcuts.java @@ -0,0 +1,108 @@ +package xyz.waozi.inbe; + +import android.app.Activity; +import android.content.ComponentName; +import android.content.Intent; +import android.content.pm.ShortcutInfo; +import android.content.pm.ShortcutManager; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.graphics.drawable.Icon; +import android.net.Uri; +import android.os.Build; +import android.util.Log; +import java.util.Collections; +import java.io.File; + +/** OS launch entries only; app selection stays on the native frame thread. */ +public final class AppShortcuts { + public static final String ACTION_OPEN_APP = "xyz.waozi.inbe.action.OPEN_APP"; + public static final String EXTRA_APP = "app_name"; + private final Activity activity; + private String pendingApp; + + public AppShortcuts(Activity activity) { + this.activity = activity; + } + + static boolean validName(String name) { + return name != null && name.matches("[a-z0-9_-]{1,24}"); + } + + public boolean supported() { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { + return false; + } + try { + ShortcutManager manager = activity.getSystemService(ShortcutManager.class); + return manager != null && manager.isRequestPinShortcutSupported(); + } catch (IllegalStateException | SecurityException error) { + return false; + } + } + + Intent intent(String name) { + return new Intent(ACTION_OPEN_APP) + .setComponent(new ComponentName(activity, activity.getClass())) + .setData(new Uri.Builder().scheme("inbe-app").authority("launch") + .appendPath(name).build()) + .putExtra(EXTRA_APP, name) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); + } + + /** 1 = confirmation requested, 2 = already pinned, 0 = unavailable/failed. */ + public int pin(String name, String label, String iconPath) { + if (!validName(name) || label == null || label.trim().isEmpty() || !supported()) { + return 0; + } + if (iconPath == null || !new File(iconPath).isFile()) { + return 0; + } + Bitmap bitmap = BitmapFactory.decodeFile(iconPath); + if (bitmap == null) { + return 0; + } + try { + ShortcutManager manager = activity.getSystemService(ShortcutManager.class); + String id = "inbe.app." + name; + ShortcutInfo shortcut = new ShortcutInfo.Builder(activity, id) + .setShortLabel(label) + .setLongLabel(label) + .setIcon(Icon.createWithBitmap(bitmap)) + .setIntent(intent(name)) + .build(); + for (ShortcutInfo existing : manager.getPinnedShortcuts()) { + if (id.equals(existing.getId())) { + return manager.updateShortcuts(Collections.singletonList(shortcut)) ? 2 : 0; + } + } + return manager.requestPinShortcut(shortcut, null) ? 1 : 0; + } catch (IllegalArgumentException | IllegalStateException | SecurityException error) { + Log.w("AppShortcuts", "Launcher pin request failed", error); + return 0; + } finally { + bitmap.recycle(); + } + } + + public synchronized void accept(Intent intent) { + if (intent == null) { + return; + } + if (ACTION_OPEN_APP.equals(intent.getAction())) { + String name = intent.getStringExtra(EXTRA_APP); + if (validName(name)) { + pendingApp = name; + } + } else if (Intent.ACTION_MAIN.equals(intent.getAction()) && + intent.hasCategory(Intent.CATEGORY_LAUNCHER)) { + pendingApp = "inbe"; + } + } + + public synchronized String take() { + String name = pendingApp; + pendingApp = null; + return name; + } +} diff --git a/droid/app/src/main/java/xyz/waozi/inbe/MainActivity.java b/droid/app/src/main/java/xyz/waozi/inbe/MainActivity.java index 8bd2f282b..70bc1fdda 100644 --- a/droid/app/src/main/java/xyz/waozi/inbe/MainActivity.java +++ b/droid/app/src/main/java/xyz/waozi/inbe/MainActivity.java @@ -324,6 +324,20 @@ public class MainActivity extends NativeActivity { private static final int MEDIA_IMPORT_KIND = 6; private int pendingQrScanKind = 5; String lastHealthConnectPath = null; + private final AppShortcuts appShortcuts = new AppShortcuts(this); + + public boolean launcherPinSupported() { + return appShortcuts.supported(); + } + + public int pinLauncherApp(String name, String label, String iconPath) { + return appShortcuts.pin(name, label, iconPath); + } + + public String takeLauncherApp() { + return appShortcuts.take(); + } + private boolean pendingStartPractice = false; private int pendingStartPracticeId = -1; private final Handler mainHandler = new Handler(Looper.getMainLooper()); @@ -1121,6 +1135,7 @@ public class MainActivity extends NativeActivity { nativeWakeLockReady(); // Widget/tile/shortcut launch: the intent that started this activity. + appShortcuts.accept(getIntent()); handleStartPracticeIntent(getIntent()); AppUpdate.onStart(this, getIntent() != null && ACTION_START_PRACTICE.equals(getIntent().getAction())); handleAudioE2EIntent(getIntent()); @@ -1401,6 +1416,7 @@ public class MainActivity extends NativeActivity { protected void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent); + appShortcuts.accept(intent); configureSystemBars(); requestInsetRefresh(); syncLifecycleState("onNewIntent"); diff --git a/locales/cs.txt b/locales/cs.txt index fca9e115c..cad05c7bf 100644 --- a/locales/cs.txt +++ b/locales/cs.txt @@ -5784,3 +5784,15 @@ Zkusit stahování znovu [optional_audio_skip] Prozatím přeskočit --- +--- +[launcher_pin_system] +Připnout do spouštěče +--- +[launcher_pin_requested] +Potvrď zástupce na domovské obrazovce. +--- +[launcher_pin_added] +Přidáno do spouštěče. +--- +[launcher_pin_failed] +Zástupce se nepodařilo přidat. Zkus to znovu. diff --git a/locales/de.txt b/locales/de.txt index 38b451fb4..8a0e4323c 100644 --- a/locales/de.txt +++ b/locales/de.txt @@ -5778,3 +5778,15 @@ Downloads erneut versuchen [optional_audio_skip] Vorerst überspringen --- +--- +[launcher_pin_system] +Im Starter anheften +--- +[launcher_pin_requested] +Bestätige die Verknüpfung auf deinem Startbildschirm. +--- +[launcher_pin_added] +Zum Starter hinzugefügt. +--- +[launcher_pin_failed] +Die Verknüpfung konnte nicht hinzugefügt werden. Bitte versuche es erneut. diff --git a/locales/en.txt b/locales/en.txt index 99ed2e4e3..4ca603880 100644 --- a/locales/en.txt +++ b/locales/en.txt @@ -5802,3 +5802,15 @@ Retry downloads [optional_audio_skip] Skip for now --- +--- +[launcher_pin_system] +Pin to launcher +--- +[launcher_pin_requested] +Confirm the shortcut on your home screen. +--- +[launcher_pin_added] +Added to your launcher. +--- +[launcher_pin_failed] +Could not add the shortcut. Please try again. diff --git a/locales/es.txt b/locales/es.txt index b83914dc6..e40aa6051 100644 --- a/locales/es.txt +++ b/locales/es.txt @@ -5778,3 +5778,15 @@ Reintentar descargas [optional_audio_skip] Omitir por ahora --- +--- +[launcher_pin_system] +Fijar al lanzador +--- +[launcher_pin_requested] +Confirma el acceso directo en tu pantalla de inicio. +--- +[launcher_pin_added] +Añadido al lanzador. +--- +[launcher_pin_failed] +No se pudo añadir el acceso directo. Inténtalo de nuevo. diff --git a/locales/fr.txt b/locales/fr.txt index 0658e559e..990a1d59d 100644 --- a/locales/fr.txt +++ b/locales/fr.txt @@ -5766,3 +5766,15 @@ Réessayer les téléchargements [optional_audio_skip] Passer pour le moment --- +--- +[launcher_pin_system] +Épingler au lanceur +--- +[launcher_pin_requested] +Confirme le raccourci sur ton écran d’accueil. +--- +[launcher_pin_added] +Ajouté au lanceur. +--- +[launcher_pin_failed] +Impossible d’ajouter le raccourci. Réessaie. diff --git a/locales/id.txt b/locales/id.txt index 948bc3a6b..21251b76e 100644 --- a/locales/id.txt +++ b/locales/id.txt @@ -5767,3 +5767,15 @@ Coba unduh lagi [optional_audio_skip] Lewati untuk sekarang --- +--- +[launcher_pin_system] +Sematkan ke peluncur +--- +[launcher_pin_requested] +Konfirmasikan pintasan di layar utama. +--- +[launcher_pin_added] +Ditambahkan ke peluncur. +--- +[launcher_pin_failed] +Tidak dapat menambahkan pintasan. Silakan coba lagi. diff --git a/locales/it.txt b/locales/it.txt index 0593d64d5..e2abccd7e 100644 --- a/locales/it.txt +++ b/locales/it.txt @@ -5767,3 +5767,15 @@ Riprova i download [optional_audio_skip] Salta per ora --- +--- +[launcher_pin_system] +Aggiungi al launcher +--- +[launcher_pin_requested] +Conferma il collegamento nella schermata iniziale. +--- +[launcher_pin_added] +Aggiunto al launcher. +--- +[launcher_pin_failed] +Impossibile aggiungere il collegamento. Riprova. diff --git a/locales/ja.txt b/locales/ja.txt index 55d93ea2e..18a2cc1c0 100644 --- a/locales/ja.txt +++ b/locales/ja.txt @@ -5763,3 +5763,15 @@ Dewが不足しています。プロフィールでDewを追加してくださ [optional_audio_skip] 今はスキップ --- +--- +[launcher_pin_system] +ランチャーに追加 +--- +[launcher_pin_requested] +ホーム画面でショートカットを確認してください。 +--- +[launcher_pin_added] +ランチャーに追加しました。 +--- +[launcher_pin_failed] +ショートカットを追加できませんでした。もう一度お試しください。 diff --git a/locales/ko.txt b/locales/ko.txt index 22f5ada11..5dfa1b6c9 100644 --- a/locales/ko.txt +++ b/locales/ko.txt @@ -5773,3 +5773,15 @@ Dew가 부족합니다. 프로필에서 Dew를 추가하세요. [optional_audio_skip] 지금은 건너뛰기 --- +--- +[launcher_pin_system] +런처에 고정 +--- +[launcher_pin_requested] +홈 화면에서 바로가기를 확인해 주세요. +--- +[launcher_pin_added] +런처에 추가했어요. +--- +[launcher_pin_failed] +바로가기를 추가할 수 없어요. 다시 시도해 주세요. diff --git a/locales/pt.txt b/locales/pt.txt index 1b76b5d67..81811a739 100644 --- a/locales/pt.txt +++ b/locales/pt.txt @@ -5776,3 +5776,15 @@ Tentar baixar novamente [optional_audio_skip] Pular por enquanto --- +--- +[launcher_pin_system] +Fixar no lançador +--- +[launcher_pin_requested] +Confirme o atalho na sua tela inicial. +--- +[launcher_pin_added] +Adicionado ao lançador. +--- +[launcher_pin_failed] +Não foi possível adicionar o atalho. Tente novamente. diff --git a/locales/ru.txt b/locales/ru.txt index 197c76770..4e35d673e 100644 --- a/locales/ru.txt +++ b/locales/ru.txt @@ -5772,3 +5772,15 @@ Lumi остаётся без сети, пока вы не примете её у [optional_audio_skip] Пока пропустить --- +--- +[launcher_pin_system] +Закрепить в меню +--- +[launcher_pin_requested] +Подтверди ярлык на главном экране. +--- +[launcher_pin_added] +Добавлено в меню приложений. +--- +[launcher_pin_failed] +Не удалось добавить ярлык. Попробуй ещё раз. diff --git a/locales/zh.txt b/locales/zh.txt index 32a86ff69..0f6a439aa 100644 --- a/locales/zh.txt +++ b/locales/zh.txt @@ -5778,3 +5778,15 @@ Dew不足,请在个人资料中添加Dew。 [optional_audio_skip] 暂时跳过 --- +--- +[launcher_pin_system] +固定到启动器 +--- +[launcher_pin_requested] +请在主屏幕上确认添加应用图标。 +--- +[launcher_pin_added] +已添加到启动器。 +--- +[launcher_pin_failed] +无法添加应用图标,请重试。 diff --git a/mk/tests-app.mk b/mk/tests-app.mk index 7d59e2433..a6d2c99ee 100644 --- a/mk/tests-app.mk +++ b/mk/tests-app.mk @@ -173,3 +173,7 @@ diary-history-test: $(ZI2C_BIN) diary-markdown-test: $(ZI2C_BIN) $(ZIRAN_BIN) @sh tests/diary_markdown_test.sh $(ZIRAN_BUILD_DIR)/bin + +.PHONY: launcher-entry-test +launcher-entry-test: $(ZI2C_BIN) + sh tests/launcher_entry_zi_test.sh $(ZIRAN_BUILD_DIR)/bin diff --git a/mk/tests-suite.mk b/mk/tests-suite.mk index 1b105f640..de62dc74f 100644 --- a/mk/tests-suite.mk +++ b/mk/tests-suite.mk @@ -17,7 +17,7 @@ test: lumi-narration-test test: ziran-behavior-tests asset-text-tests test: route-host-test test: profile-host-test -test: launcher-policy-test +test: launcher-policy-test launcher-entry-test android-text-selection-test test: button-api-check test: version-check version-test test: habit-merge-sql-test sync-restore-sql-test diff --git a/mk/tests-ui.mk b/mk/tests-ui.mk index 237d6d150..17d9f6e98 100644 --- a/mk/tests-ui.mk +++ b/mk/tests-ui.mk @@ -208,3 +208,10 @@ audio-setup-ui-test: $(TARGET) $(INBE_FULL_BUNDLE) YUE_DESKTOP_RECOVERY=0 LIBGL_ALWAYS_SOFTWARE=1 \ xvfb-run -a -n 300 -s '-screen 0 1280x1000x24' \ python3 tests/audio_setup_ui_test.py $(abspath $(TARGET)) + +.PHONY: launcher-shortcut-ui-test +launcher-shortcut-ui-test: $(TARGET) node-apps + env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY -u DBUS_SESSION_BUS_ADDRESS YUE_DESKTOP_RECOVERY=0 \ + python3 tests/launcher_shortcut_ui_test.py $(abspath $(TARGET)) + +VISUAL_TEST_TARGETS += launcher-shortcut-ui-test diff --git a/src/app/app_launcher.zi b/src/app/app_launcher.zi index 138c5dfb6..cb3c1beb5 100644 --- a/src/app/app_launcher.zi +++ b/src/app/app_launcher.zi @@ -4,6 +4,8 @@ #import, file "app_route_state.zi"; #import, file "app_modal_state.zi"; #import, file "app_launcher_state.zi"; +#import, file "app_launcher_pins.zi"; +#import, file "../platform/launcher_shortcut.zi"; #import, file "app_settings.zi"; #import, file "launcher_policy.zi"; #import, file "app_nav_state.zi"; @@ -99,6 +101,8 @@ app_launcher_drag_card :: (app: *InnerBreeze, card: ButtonProps, // Every app card has the same click and drag behavior in both sections. app_launcher_draw_card :: (app: *InnerBreeze, route: s32, bounds: Rectangle, vertical: bool) { + full_bounds := bounds + if LauncherShortcutSupported() { bounds.height -= cast(float32)AppScale(44) } blocked := app.blocked_input_frame == app.breathing.frame card: ButtonProps card.id = 6900 + route @@ -155,6 +159,19 @@ app_launcher_draw_card :: (app: *InnerBreeze, route: s32, if activated && !app.launcher_drag_moving { app_launcher_activate(app, route) } + if installed && LauncherShortcutSupported() { + pin: ButtonProps + pin.id = 7600 + route + pin.bounds = Rectangle.{full_bounds.x, full_bounds.y + bounds.height + cast(float32)AppScale(4), + full_bounds.width, cast(float32)AppScale(40)} + pin.label = LocaleText("launcher_pin_system") + pin.fit_content = true + pin.emphasis = cast(ButtonEmphasis)ButtonEmphasisSoft + pin.disabled = blocked + if Button(app.ui.session, pin) != 0 { + app_launcher_pin(app, route) + } + } // The install or remove symbol sits inside the card's top-right corner. // It is submitted after the card, so a tap on it reaches only the action. action_size := AppScale(36) @@ -352,7 +369,7 @@ app_draw_launcher :: (app: *InnerBreeze) { offer_count += 1 } } - tile_height := AppScale(88) + tile_height := AppScale(ifx LauncherShortcutSupported() then 132 else 88) gap := AppScale(12) // The tiles reflow into as many columns as the panel's width allows. columns := MeasureGrid(GridProps.{.bounds = Rectangle.{cast(float32)x, 0.0, cast(float32)width, 0.0}, @@ -369,6 +386,14 @@ app_draw_launcher :: (app: *InnerBreeze) { bottom_dock := app_content_bottom_reserved(app) footer_y := app.ui.view_height - bottom_dock - AppScale(72) body_y := search_y + AppScale(68) + if launcher_pin_status >= 0 { + status_key := ifx launcher_pin_status == 2 then "launcher_pin_added" else "launcher_pin_requested" + if launcher_pin_status == 0 { status_key = "launcher_pin_failed" } + Text(app.ui.session, TextProps.{.text = LocaleText(status_key), + .bounds = Rectangle.{cast(float32)x, cast(float32)body_y, + cast(float32)width, cast(float32)AppScale(44)}, .font = AppSmallFontSize()}) + body_y += AppScale(48) + } scroll: ScrollProps scroll.key = KeyHash("inbe/apps/library") scroll.bounds = Rectangle.{cast(float32)x, cast(float32)body_y, diff --git a/src/app/app_launcher_pins.zi b/src/app/app_launcher_pins.zi new file mode 100644 index 000000000..c158af51a --- /dev/null +++ b/src/app/app_launcher_pins.zi @@ -0,0 +1,90 @@ +#import, file "app_types.zi"; +#import, file "app_nav_state.zi"; +#import, file "app_launcher_state.zi"; +#import, file "launcher_policy.zi"; +#import, file "app_route_state.zi"; +#import, file "../cells/package_files.zi"; +#import, file "../platform/launcher_shortcut.zi"; +#import, file "../platform/launcher_icon.zi"; +#import, file "../platform/environment.zi"; +#import, file "../widgets/bottom_nav.zi"; +#import, file "../core/types.zi"; +#import, file "../storage/paths.zi"; +#import "c_string" +#import, file "text_buffers.zi"; +#import, file "route_types.zi"; +#import, file "../platform/launcher_entry.zi"; +#if !#defined(ANDROID_BUILD) && !#defined(PLATFORM_WEB) { + raylib :: #system_library "raylib"; + LauncherWindowTitle :: (title: *u8) #foreign raylib "SetWindowTitle"; +} + +launcher_pin_status: s32 = -1; +launcher_pending_name: [25]u8; +launcher_request_attempted: bool; + +app_launcher_pin :: (app: *InnerBreeze, route: s32) { + launcher_pin_status = 0 + name := LauncherRouteName(route) + if !LauncherAppNameValid(name) || !app_nav_route_available(app, route) { return } + packages := PackageDirectory() + defer { PackageFree(packages) } + directory := PackageText(packages, "/launcher") + defer { PackageFree(directory) } + if storage_ensure_dir(directory) == 0 { return } + stem := PackageText("/", name) + defer { PackageFree(stem) } + path := PackageText(directory, stem) + defer { PackageFree(path) } + icon := PackageText(path, ifx WindowsPlatform() != 0 then ".ico" else ".png") + defer { PackageFree(icon) } + if LauncherIconWrite(icon, app_nav_route_shape(route), WindowsPlatform() != 0) { + launcher_pin_status = LauncherShortcutInstall(name, app_nav_route_label(route), icon) + } +} + +// Keep an unresolved cold launch while its already installed package loads. +// A launcher never silently reinstalls an app removed from this account. +app_launcher_request_app :: (name: string) { + if LauncherAppNameValid(name) { + unused CopyCString(name, launcher_pending_name[:]) + launcher_request_attempted = false + } +} + +app_launcher_pump_request :: (app: *InnerBreeze) { + incoming := LauncherShortcutTakeApp() + if incoming.count > 0 { app_launcher_request_app(incoming) } + name := AppTextFromCString(*launcher_pending_name[0], 25) + if name.count == 0 { return } + if name == "inbe" { + app.host_feature = 0 + launcher_pending_name[0] = 0 + return + } + if app.language_selected == 0 || app.apps_selected == 0 { return } + route := LauncherRouteForName(name) + if route == cast(s32)AppNavRoute.APP_NAV_ROUTE_NONE || !app_nav_route_available(app, route) { return } + if app.modal.active != 0 { return } + if !launcher_request_attempted { + app_launcher_close(app) + app_apply_nav_route(app, route) + launcher_request_attempted = true + } else if app_current_nav_route(app) != route { + // The person dismissed an unsaved-changes dialog and stayed here. + launcher_pending_name[0] = 0 + return + } + if app_current_nav_route(app) == route { + // The host uses a nonzero feature to hide surrounding harness navigation. + bit := app_nav_route_bit(route) + app.host_feature = ifx bit != 0 then bit else route + #if !#defined(ANDROID_BUILD) && !#defined(PLATFORM_WEB) { + title: [256]u8 + if CopyCString(app_nav_route_label(route), title[:]) { + LauncherWindowTitle(*title[0]) + } + } + launcher_pending_name[0] = 0 + } +} diff --git a/src/platform/android/android_shortcuts.zi b/src/platform/android/android_shortcuts.zi new file mode 100644 index 000000000..ecd73ed29 --- /dev/null +++ b/src/platform/android/android_shortcuts.zi @@ -0,0 +1,67 @@ +#import "android_jni" +#import "c_string" +#import "text_buffer" +#import "byte_text_linux" + +#if #defined(ANDROID_BUILD) { + pending_app: [25]u8; + + AndroidLauncherSupported :: () -> bool { + session: AndroidJniSession + if AndroidJniAttachCurrent(*session) == 0 { return false } + defer { AndroidJniDetachCurrent(*session) } + method := AndroidJniMethod(*session, "launcherPinSupported", "()Z") + if method == null { return false } + env := session.env + result := env.functions.CallBooleanMethodA(env, session.activity, method, null) + return env.functions.ExceptionCheck(env) == 0 && result != 0 + } + + AndroidLauncherPin :: (name: string, label: string, icon: string) -> s32 { + session: AndroidJniSession + if AndroidJniAttachCurrent(*session) == 0 { return 0 } + defer { AndroidJniDetachCurrent(*session) } + method := AndroidJniMethod(*session, "pinLauncherApp", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)I") + if method == null { return 0 } + name_bytes: [25]u8 + label_bytes: [256]u8 + icon_bytes: [4096]u8 + if !CopyCString(name, name_bytes[:]) || !CopyCString(label, label_bytes[:]) || + !CopyCString(icon, icon_bytes[:]) { return 0 } + env := session.env + arguments: [3]JniValue + arguments[0].reference = AndroidJniString(env, *name_bytes[0]) + arguments[1].reference = AndroidJniString(env, *label_bytes[0]) + arguments[2].reference = AndroidJniString(env, *icon_bytes[0]) + for argument: arguments { + if argument.reference == null { return 0 } + } + result := env.functions.CallIntMethodA(env, session.activity, method, *arguments[0]) + if env.functions.ExceptionCheck(env) != 0 { return 0 } + return result + } + + // Called on the native frame thread after the host is initialized, so cold + // and warm launch intents never touch app state from Android's UI thread. + AndroidLauncherTakeApp :: () -> string { + session: AndroidJniSession + if AndroidJniAttachCurrent(*session) == 0 { return "" } + defer { AndroidJniDetachCurrent(*session) } + method := AndroidJniMethod(*session, "takeLauncherApp", "()Ljava/lang/String;") + if method == null { return "" } + env := session.env + value := env.functions.CallObjectMethodA(env, session.activity, method, null) + if value == null || env.functions.ExceptionCheck(env) != 0 { return "" } + bytes := env.functions.GetStringUTFChars(env, value, null) + if bytes == null { return "" } + defer { env.functions.ReleaseStringUTFChars(env, value, bytes) } + count: s32 = 0 + while count < 24 && bytes[count] != 0 { + pending_app[count] = bytes[count] + count += 1 + } + if bytes[count] != 0 { return "" } + pending_app[count] = 0 + return TextUntilNul(pending_app[:]) + } +} diff --git a/src/platform/app_host.zi b/src/platform/app_host.zi index fd762bc94..05e1921b9 100644 --- a/src/platform/app_host.zi +++ b/src/platform/app_host.zi @@ -79,6 +79,9 @@ SetTargetFPS :: (fps: s32) #foreign raylib; #import, file "../app/screenshot_arguments.zi"; #import, file "../app/mini_mode.zi"; #import, file "feature_request.zi"; +#import, file "../app/app_launcher_pins.zi"; +#import, file "launcher_entry.zi"; +#import, file "../cells/package_files.zi"; #import, file "host_actions.zi"; #import, file "../app/exercise_types.zi"; #import, file "../app/route_types.zi"; @@ -186,6 +189,23 @@ Prepare :: (argc: s32, argv: **u8) { override_root := HostEnv("APP_DATA_ROOT") debug_profile := override_root != null && override_root[0] != cast(u8)0 identity := DesktopIdentity(debug_profile) + // Match a desktop entry before SDL creates its window. + launch_name: string + argument: s32 = 1 + while argument + 1 < arg_count { + if args[argument] == "--app" && LauncherAppNameValid(args[argument + 1]) { + launch_name = args[argument + 1] + break + } + argument += 1 + } + launch_id: string + if launch_name.count > 0 { + launch_id = PackageText("xyz.waozi.inbe.", launch_name) + identity.app_id = launch_id + config.title_custom = 1 + } + defer { PackageFree(launch_id) } AppCopyText(identity.display_name, config.title[:]) if debug_profile { config.title_custom = 1 @@ -310,6 +330,7 @@ app_frame :: (app: *InnerBreeze) { app.host_feature = requested_feature } } + app_launcher_pump_request(app) PollHostActions(app) ReportHostState(app) first_frame := app_frame_probe_count == 0 @@ -681,6 +702,11 @@ native_after_app_init :: (app: *InnerBreeze, argc: s32, argv: **u8) { argi: s32 = 1 while argi < argc { option := AppTextFromCString(argv[argi], 16) + if option == "--app" && argi + 1 < argc { + app_launcher_request_app(AppTextFromCString(argv[argi + 1], 25)) + argi += 2 + continue + } if (option == "--cell" || option == "--feature") && argi + 1 < argc { name := AppTextFromCString(argv[argi + 1], 16) feature: s32 = -1 @@ -693,6 +719,8 @@ native_after_app_init :: (app: *InnerBreeze, argc: s32, argv: **u8) { } else if name == "diary" { feature = 8 + } else if name == "leaderboard" { + feature = 32 } else if name == "lumi" { feature = 16 } diff --git a/src/platform/launcher_entry.zi b/src/platform/launcher_entry.zi new file mode 100644 index 000000000..79da16d15 --- /dev/null +++ b/src/platform/launcher_entry.zi @@ -0,0 +1,72 @@ +// Desktop entry encoding is independent of the platform and never invokes a shell. +#import "text" +#import "vec" +#import "byte_text_linux" +c :: #system_library "c"; +LauncherFree :: (memory: *u8) #foreign c "free"; + +LauncherAppNameValid :: (name: string) -> bool { + if name.count == 0 || name.count > 24 { return false } + for byte: name { + if !((byte >= 97 && byte <= 122) || (byte >= 48 && byte <= 57) || byte == 45 || byte == 95) { + return false + } + } + return true +} + +LauncherEntryValue :: (out: *Vec(u8), value: string) { + for byte: value { + if byte == 10 { BuilderPrint(out, "\\n") } + else if byte == 13 { BuilderPrint(out, "\\r") } + else if byte == 9 { BuilderPrint(out, "\\t") } + else if byte == 92 { BuilderPrint(out, "\\\\") } + else if byte == 0 { continue } + else { unused VecPush(out.*, byte) } + } +} + +// Exec quoting is decoded after desktop-string escaping. Percent is a field +// code even inside quotes, so literal percentages must be doubled too. +LauncherExecArgument :: (out: *Vec(u8), value: string) { + BuilderPrint(out, "\"") + for byte: value { + if byte == 37 { + unused VecPush(out.*, cast(u8)37) + unused VecPush(out.*, cast(u8)37) + } + else if byte == 92 { BuilderPrint(out, "\\\\\\\\") } + else if byte == 34 || byte == 36 || byte == 96 { + BuilderPrint(out, "\\\\") + unused VecPush(out.*, byte) + } else if byte == 10 { BuilderPrint(out, "\\n") } + else if byte == 13 { BuilderPrint(out, "\\r") } + else if byte == 9 { BuilderPrint(out, "\\t") } + else { unused VecPush(out.*, byte) } + } + BuilderPrint(out, "\"") +} + +LauncherDesktopEntry :: (executable: string, name: string, label: string, + icon: string, profile: string) -> string { + if executable.count == 0 || !LauncherAppNameValid(name) { return "" } + out: Vec(u8) + BuilderPrint(*out, "[Desktop Entry]\nType=Application\nVersion=1.0\nName=") + LauncherEntryValue(*out, label) + BuilderPrint(*out, "\nExec=") + if profile.count > 0 { + BuilderPrint(*out, "env ") + environment: Vec(u8) + BuilderPrint(*environment, "APP_DATA_ROOT=%", profile) + value := BuilderFinish(environment) + LauncherExecArgument(*out, value) + descriptor := cast(*TextDescriptor)(*value) + LauncherFree(descriptor.data) + BuilderPrint(*out, " ") + } + LauncherExecArgument(*out, executable) + BuilderPrint(*out, " --app %\nIcon=", name) + LauncherEntryValue(*out, icon) + BuilderPrint(*out, "\nTerminal=false\nCategories=Utility;\nStartupWMClass=xyz.waozi.inbe.%\n", name) + return BuilderFinish(out) +} diff --git a/src/platform/launcher_icon.zi b/src/platform/launcher_icon.zi new file mode 100644 index 000000000..614a038c8 --- /dev/null +++ b/src/platform/launcher_icon.zi @@ -0,0 +1,60 @@ +// Rasterize the same app mark as Apps, without a window or graphics context. +#import "svg_shape" +#import "file_linux" +#import "c_string" +#import "byte_text_linux" +#import, file "raylib_host.zi"; +#import, file "../cells/package_files.zi"; + +#if !#defined(PLATFORM_WEB) { + raylib :: #system_library "raylib"; + IconPng :: (image: RaylibImage, extension: *u8, size: *s32) -> *u8 #foreign raylib "ExportImageToMemory"; + IconFree :: (memory: *void) #foreign raylib "MemFree"; +} + +LauncherIconWrite :: (path: string, shape: string, windows: bool) -> bool { + #if !#defined(PLATFORM_WEB) { + coverage: [9216]u8 + if !ShapeRaster(shape, 96, coverage[:]) { return false } + pixels: [65536]u8 + for y: cast(s32)0..127 { + for x: cast(s32)0..127 { + alpha: s32 = 0 + if x >= 16 && x < 112 && y >= 16 && y < 112 { + alpha = cast(s32)coverage[(y - 16) * 96 + x - 16] + } + at := (y * 128 + x) * 4 + pixels[at] = cast(u8)(226 + (40 - 226) * alpha / 255) + pixels[at + 1] = cast(u8)(240 + (91 - 240) * alpha / 255) + pixels[at + 2] = cast(u8)(234 + (83 - 234) * alpha / 255) + pixels[at + 3] = 255 + } + } + image: RaylibImage = .{cast(*void)*pixels[0], 128, 128, 1, 7} + extension: [8]u8 + unused CopyCString(".png", extension[:]) + size: s32 + png := IconPng(image, *extension[0], *size) + if png == null || size <= 0 { return false } + defer { IconFree(cast(*void)png) } + file := OpenReplace(path) + if !file.valid { return false } + offset: s64 = 0 + ok := true + if windows { + // One PNG-backed ICO entry, supported by the Windows Shell. + header: [22]u8 = .[0, 0, 1, 0, 1, 0, 128, 128, 0, 0, 1, 0, 32, 0, 0, 0, 0, 0, 22, 0, 0, 0] + index: s32 = 0 + while index < 4 { + header[14 + index] = cast(u8)((cast(u32)size >> cast(u32)(index * 8)) & 255) + index += 1 + } + ok = WriteAt(file, header[:], 0) == 22 + offset = 22 + } + ok = ok && WriteAt(file, BytesFromPointer(png, cast(u64)size), offset) == size && SyncFile(file) + closed := CloseFile(file) + return ok && closed + } + return false +} diff --git a/src/platform/launcher_shortcut.zi b/src/platform/launcher_shortcut.zi new file mode 100644 index 000000000..390bc6417 --- /dev/null +++ b/src/platform/launcher_shortcut.zi @@ -0,0 +1,121 @@ +// Native launch entries share Inbe's executable, packages and account data. +#import "c_string" +#import "text_buffer" +#import "file_linux" +#import "byte_text_linux" +#import, file "launcher_entry.zi"; +#import, file "../cells/package_files.zi"; +#import, file "../storage/paths.zi"; +#if #defined(_WIN32) { + #import, file "launcher_windows.zi"; +} +#if #defined(ANDROID_BUILD) { + #import, file "android/android_shortcuts.zi"; +} + +#scope_file +libc :: #system_library "c"; +Environment :: (name: *u8) -> *u8 #foreign libc "getenv"; +launcher_android_supported: s32 = -1; +#if !#defined(_WIN32) && !#defined(ANDROID_BUILD) && !#defined(PLATFORM_WEB) { + ExecutableLink :: (path: *u8, output: *u8, size: usize) -> isize #foreign libc "readlink"; +} +#scope_export + +LauncherEnvironment :: (name: string) -> string { + bytes: [64]u8 + if !CopyCString(name, bytes[:]) { return "" } + value := Environment(*bytes[0]) + if value == null { return "" } + return TextFromCString(value) +} + +LauncherShortcutSupported :: () -> bool { + #if #defined(PLATFORM_WEB) || #defined(__APPLE__) || #defined(__FreeBSD__) { + return false + } + #if !#defined(_WIN32) && !#defined(ANDROID_BUILD) && !#defined(PLATFORM_WEB) { + if LauncherEnvironment("FLATPAK_ID").count > 0 || LauncherEnvironment("SNAP").count > 0 { + return false + } + } + #if #defined(ANDROID_BUILD) { + if launcher_android_supported < 0 { + launcher_android_supported = cast(s32)AndroidLauncherSupported() + } + return launcher_android_supported != 0 + } + return true +} + +LauncherExecutable :: (output: []u8) -> string { + #if #defined(_WIN32) { + return WindowsLauncherExecutable(output) + } + #if !#defined(_WIN32) && !#defined(ANDROID_BUILD) && !#defined(PLATFORM_WEB) { + appimage := LauncherEnvironment("APPIMAGE") + if appimage.count > 0 && appimage[0] == 47 { + if CopyCString(appimage, output) { return TextUntilNul(output) } + return "" + } + path: [32]u8 + unused CopyCString("/proc/self/exe", path[:]) + length := ExecutableLink(*path[0], *output[0], cast(usize)(output.count - 1)) + if length > 0 && cast(s64)length < output.count - 1 { + output[length] = 0 + return TextUntilNul(output) + } + } + return "" +} + +// 1 means Android's confirmation was requested; 2 means the entry exists. +// No Android request is reported as a completed installation. +LauncherShortcutInstall :: (name: string, label: string, icon: string) -> s32 { + if !LauncherAppNameValid(name) || label.count == 0 { return 0 } + #if #defined(ANDROID_BUILD) { + return AndroidLauncherPin(name, label, icon) + } + #if #defined(_WIN32) { + return WindowsLauncherInstall(name, label, icon) + } + #if !#defined(ANDROID_BUILD) && !#defined(_WIN32) && !#defined(PLATFORM_WEB) { + // Sandboxed distributions need a portal rather than a path into their + // private mount. Do not create a launcher that cannot be executed. + if LauncherEnvironment("FLATPAK_ID").count > 0 || LauncherEnvironment("SNAP").count > 0 { + return 0 + } + executable_bytes: [4096]u8 + executable := LauncherExecutable(executable_bytes[:]) + directory := LauncherEnvironment("XDG_DATA_HOME") + owned: string + if directory.count == 0 || directory[0] != 47 { + home := LauncherEnvironment("HOME") + if home.count == 0 || home[0] != 47 { return 0 } + owned = PackageText(home, "/.local/share") + directory = owned + } + defer { PackageFree(owned) } + applications := PackageText(directory, "/applications") + defer { PackageFree(applications) } + if storage_ensure_dir(applications) == 0 { return 0 } + filename := PackageText("/xyz.waozi.inbe.", name) + defer { PackageFree(filename) } + stem := PackageText(applications, filename) + defer { PackageFree(stem) } + path := PackageText(stem, ".desktop") + defer { PackageFree(path) } + entry := LauncherDesktopEntry(executable, name, label, icon, LauncherEnvironment("APP_DATA_ROOT")) + defer { PackageFree(entry) } + if entry.count == 0 || !PackageWrite(path, entry) { return 0 } + return 2 + } + return 0 +} + +LauncherShortcutTakeApp :: () -> string { + #if #defined(ANDROID_BUILD) { + return AndroidLauncherTakeApp() + } + return "" +} diff --git a/src/platform/launcher_windows.zi b/src/platform/launcher_windows.zi new file mode 100644 index 000000000..416c35758 --- /dev/null +++ b/src/platform/launcher_windows.zi @@ -0,0 +1,134 @@ +// Create a real per-user Start menu shortcut through the Windows Shell. +#import "c_string" +#import "text_buffer" +#import "byte_text_linux" +#import, file "../cells/package_files.zi"; +#import, file "../storage/paths.zi"; + +#if #defined(_WIN32) { + kernel :: #system_library "kernel32"; + shell :: #system_library "shell32"; + ole :: #system_library "ole32"; + ModulePath :: (module: *void, path: *u16, size: u32) -> u32 #foreign kernel "GetModuleFileNameW"; + ToWide :: (page: u32, flags: u32, text: *u8, count: s32, output: *u16, size: s32) -> s32 #foreign kernel "MultiByteToWideChar"; + FromWide :: (page: u32, flags: u32, text: *u16, count: s32, output: *u8, size: s32, fallback: *u8, used: *s32) -> s32 #foreign kernel "WideCharToMultiByte"; + SpecialFolder :: (window: *void, folder: s32, token: *void, flags: u32, output: *u16) -> s32 #foreign shell "SHGetFolderPathW"; + ComInit :: (reserved: *void, flags: u32) -> s32 #foreign ole "CoInitializeEx"; + ComEnd :: () #foreign ole "CoUninitialize"; + ComCreate :: (class: *Guid, outer: *void, context: u32, iid: *Guid, output: **ShellLink) -> s32 #foreign ole "CoCreateInstance"; + Guid :: struct { + first: u32 + second: u16 + third: u16 + bytes: [8]u8 + } + QueryFn :: #type (*ShellLink, *Guid, **PersistFile) -> s32 #c_call; + ReleaseFn :: #type (*void) -> u32 #c_call; + SetTextFn :: #type (*ShellLink, *u16) -> s32 #c_call; + SetIconFn :: #type (*ShellLink, *u16, s32) -> s32 #c_call; + SaveFn :: #type (*PersistFile, *u16, s32) -> s32 #c_call; + ShellTable :: struct { + query: QueryFn + add_ref: *void + release: ReleaseFn + getters: [4]*void + description: SetTextFn + get_directory: *void + directory: SetTextFn + get_arguments: *void + arguments: SetTextFn + middle: [5]*void + icon: SetIconFn + relative_path: *void + resolve: *void + path: SetTextFn + } + ShellLink :: struct { table: *ShellTable } + PersistTable :: struct { + query: *void + add_ref: *void + release: ReleaseFn + class_id: *void + dirty: *void + load: *void + save: SaveFn + } + PersistFile :: struct { table: *PersistTable } + + WindowsGuid :: (first: u32) -> Guid { + value: Guid + value.first = first + value.bytes[0] = 0xC0 + value.bytes[7] = 0x46 + return value + } + + WindowsWide :: (text: string, output: []u16) -> bool { + input: [4096]u8 + return CopyCString(text, input[:]) && + ToWide(65001, 8, *input[0], -1, *output[0], cast(s32)output.count) > 0 + } + + WindowsLauncherExecutable :: (output: []u8) -> string { + wide: [4096]u16 + count := ModulePath(null, *wide[0], cast(u32)wide.count) + if count == 0 || count >= cast(u32)wide.count { return "" } + if FromWide(65001, 0, *wide[0], -1, *output[0], cast(s32)output.count, null, null) <= 0 { + return "" + } + return TextUntilNul(output) + } + + WindowsLauncherInstall :: (name: string, label: string, icon: string) -> s32 { + executable_bytes: [4096]u8 + executable := WindowsLauncherExecutable(executable_bytes[:]) + if executable.count == 0 { return 0 } + programs: [260]u16 + // CSIDL_PROGRAMS | CSIDL_FLAG_CREATE, resolved by Windows even when relocated. + if SpecialFolder(null, 0x8002, null, 0, *programs[0]) < 0 { return 0 } + folder: [4096]u8 + if FromWide(65001, 0, *programs[0], -1, *folder[0], 4096, null, null) <= 0 { return 0 } + stem := PackageText(TextUntilNul(folder[:]), "/Inner Breeze") + defer { PackageFree(stem) } + if storage_ensure_dir(stem) == 0 { return 0 } + display: [25]u8 + unused CopyCString(name, display[:]) + if display[0] >= 97 && display[0] <= 122 { display[0] -= cast(u8)32 } + if name == "practices" { unused CopyCString("Practice", display[:]) } + suffix := PackageText("/", TextUntilNul(display[:])) + defer { PackageFree(suffix) } + base := PackageText(stem, suffix) + defer { PackageFree(base) } + filename := PackageText(base, ".lnk") + defer { PackageFree(filename) } + argument := PackageText("--app ", name) + defer { PackageFree(argument) } + path_wide: [4096]u16 + exe_wide: [4096]u16 + argument_wide: [256]u16 + icon_wide: [4096]u16 + label_wide: [256]u16 + if !WindowsWide(filename, path_wide[:]) || !WindowsWide(executable, exe_wide[:]) || + !WindowsWide(argument, argument_wide[:]) || !WindowsWide(icon, icon_wide[:]) || + !WindowsWide(label, label_wide[:]) { return 0 } + initialized := ComInit(null, 2) + // RPC_E_CHANGED_MODE: COM was already initialized in another apartment. + if initialized < 0 && initialized != -2147417850 { return 0 } + defer { if initialized >= 0 { ComEnd() } } + class := WindowsGuid(0x00021401) + iid := WindowsGuid(0x000214F9) + persist_iid := WindowsGuid(0x0000010B) + link: *ShellLink + if ComCreate(*class, null, 1, *iid, *link) < 0 || link == null { return 0 } + defer { unused link.table.release(cast(*void)link) } + if link.table.path(link, *exe_wide[0]) < 0 || + link.table.arguments(link, *argument_wide[0]) < 0 || + link.table.description(link, *label_wide[0]) < 0 || + link.table.icon(link, *icon_wide[0], 0) < 0 { return 0 } + persist: *PersistFile + if link.table.query(link, *persist_iid, *persist) < 0 || persist == null { return 0 } + defer { unused persist.table.release(cast(*void)persist) } + if persist.table.save(persist, *path_wide[0], 1) < 0 { return 0 } + return 2 + } +} diff --git a/tests/android-text-selection/AppShortcutsTest.java b/tests/android-text-selection/AppShortcutsTest.java new file mode 100644 index 000000000..764d6ac68 --- /dev/null +++ b/tests/android-text-selection/AppShortcutsTest.java @@ -0,0 +1,76 @@ +import static org.junit.Assert.*; + +import android.app.Activity; +import android.content.ComponentName; +import android.content.Intent; +import android.content.pm.ShortcutManager; +import android.graphics.Bitmap; +import java.io.File; +import java.io.FileOutputStream; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.Robolectric; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.annotation.Config; +import org.robolectric.Shadows; +import xyz.waozi.inbe.AppShortcuts; + +@RunWith(RobolectricTestRunner.class) +@Config(sdk = {28, 36}, manifest = Config.NONE) +public class AppShortcutsTest { + private AppShortcuts shortcuts(Activity activity) { + return new AppShortcuts(activity); + } + + @Test public void constructionDoesNotRequireAnAttachedActivity() { + AppShortcuts shortcuts = new AppShortcuts(new Activity()); + shortcuts.accept(new Intent(AppShortcuts.ACTION_OPEN_APP) + .putExtra(AppShortcuts.EXTRA_APP, "diary")); + assertEquals("diary", shortcuts.take()); + } + + @Test public void launchIntentsAreConsumedOnceAndValidateAppNames() { + Activity activity = Robolectric.buildActivity(Activity.class).setup().get(); + AppShortcuts shortcuts = shortcuts(activity); + shortcuts.accept(new Intent(AppShortcuts.ACTION_OPEN_APP) + .putExtra(AppShortcuts.EXTRA_APP, "diary")); + assertEquals("diary", shortcuts.take()); + assertNull(shortcuts.take()); + shortcuts.accept(new Intent(AppShortcuts.ACTION_OPEN_APP) + .putExtra(AppShortcuts.EXTRA_APP, "../../anything")); + assertNull(shortcuts.take()); + shortcuts.accept(new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)); + assertEquals("inbe", shortcuts.take()); + shortcuts.accept(new Intent("unrelated").putExtra(AppShortcuts.EXTRA_APP, "habits")); + assertNull(shortcuts.take()); + } + + @Test public void pinUsesStableAppIdentityAndDoesNotDuplicateExistingPin() throws Exception { + Activity activity = Robolectric.buildActivity(Activity.class).setup().get(); + ShortcutManager manager = activity.getSystemService(ShortcutManager.class); + Shadows.shadowOf(manager).setIsRequestPinShortcutSupported(true); + AppShortcuts shortcuts = shortcuts(activity); + File icon = new File(activity.getCacheDir(), "launcher.png"); + Bitmap bitmap = Bitmap.createBitmap(128, 128, Bitmap.Config.ARGB_8888); + try (FileOutputStream output = new FileOutputStream(icon)) { + assertTrue(bitmap.compress(Bitmap.CompressFormat.PNG, 100, output)); + } + assertTrue(shortcuts.supported()); + assertEquals(1, shortcuts.pin("diary", "日記", icon.getAbsolutePath())); + assertEquals(1, manager.getPinnedShortcuts().size()); + assertEquals("inbe.app.diary", manager.getPinnedShortcuts().get(0).getId()); + Intent intent = manager.getPinnedShortcuts().get(0).getIntent(); + assertEquals(AppShortcuts.ACTION_OPEN_APP, intent.getAction()); + assertEquals("diary", intent.getStringExtra(AppShortcuts.EXTRA_APP)); + assertEquals("inbe-app://launch/diary", intent.getDataString()); + assertEquals(new ComponentName(activity, Activity.class), intent.getComponent()); + assertEquals(2, shortcuts.pin("diary", "Diary", icon.getAbsolutePath())); + assertEquals(1, manager.getPinnedShortcuts().size()); + assertEquals("Diary", manager.getPinnedShortcuts().get(0).getShortLabel()); + assertEquals(0, shortcuts.pin("../diary", "Diary", icon.getAbsolutePath())); + assertEquals(0, shortcuts.pin("lists", "Lists", "/missing.png")); + Shadows.shadowOf(manager).setIsRequestPinShortcutSupported(false); + assertFalse(shortcuts.supported()); + assertEquals(0, shortcuts.pin("lists", "Lists", icon.getAbsolutePath())); + } +} diff --git a/tests/android-text-selection/build.gradle b/tests/android-text-selection/build.gradle index b32629726..328e21914 100644 --- a/tests/android-text-selection/build.gradle +++ b/tests/android-text-selection/build.gradle @@ -20,7 +20,7 @@ if (!sdk) { sourceSets { main.java { srcDir '../../droid/app/src/main/java' - include '**/TextSelectionMenu.java', '**/TextInputView.java', '**/TextClipboard.java' + include '**/TextSelectionMenu.java', '**/TextInputView.java', '**/TextClipboard.java', '**/AppShortcuts.java' } test.java.srcDir '.' } diff --git a/tests/launcher_entry_behavior.zi b/tests/launcher_entry_behavior.zi new file mode 100644 index 000000000..d90a5bb7d --- /dev/null +++ b/tests/launcher_entry_behavior.zi @@ -0,0 +1,28 @@ +#import, file "../src/platform/launcher_entry.zi"; +#import "c_string" +#import "text_buffer" +#import "text" +#import "vec" +#import "byte_text_linux" +c :: #system_library "c"; +Free :: (memory: *u8) #foreign c "free"; + +#program_export +LauncherEntryBehavior :: () -> s32 { + if !LauncherAppNameValid("diary") || !LauncherAppNameValid("photos-2") || + LauncherAppNameValid("../diary") || LauncherAppNameValid("lumi\nExec=bad") || + LauncherAppNameValid("") || LauncherAppNameValid("UPPER") { return 1 } + out: Vec(u8) + LauncherExecArgument(*out, "/a b/50%/$`\"\\file") + quoted := BuilderFinish(out) + if quoted != "\"/a b/50%%/\\\\$\\\\`\\\\\"\\\\\\\\file\"" { return 2 } + descriptor := cast(*TextDescriptor)(*quoted) + Free(descriptor.data) + entry := LauncherDesktopEntry("/opt/My Apps/inbe", "diary", "日記\nExec=bad", + "/icons/a\\b.png", "/profiles/one two") + if !ContainsFoldASCII(entry, "Name=日記\\nExec=bad\nExec=env \"APP_DATA_ROOT=/profiles/one two\"") || + !ContainsFoldASCII(entry, "\"/opt/My Apps/inbe\" --app diary\n") || + !ContainsFoldASCII(entry, "Icon=/icons/a\\\\b.png\n") || + !ContainsFoldASCII(entry, "StartupWMClass=xyz.waozi.inbe.diary") { return 3 } + return 0 +} diff --git a/tests/launcher_entry_zi_test.sh b/tests/launcher_entry_zi_test.sh new file mode 100644 index 000000000..49c740e26 --- /dev/null +++ b/tests/launcher_entry_zi_test.sh @@ -0,0 +1,23 @@ +#!/bin/sh +set -eu +root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +bin=${1:-"$root/build/ziran-toolchain/bin"} +work="$root/build/launcher-entry-test" +mkdir -p "$work/generated" +"$bin/zi2c" --no-main --root "$root/tests" \ + --module-path "$root/build/packages/ziran/std" \ + -o "$work/generated" "$root/tests/launcher_entry_behavior.zi" +cat > "$work/generated/main.c" <<'C' +#include "launcher_entry_behavior.h" +#include +int main(void) { + int result = LauncherEntryBehavior(); + if (result) fprintf(stderr, "launcher entry check %d failed\n", result); + return result; +} +C +"${CC:-cc}" -std=c11 -DZIRAN_BOUNDS_CHECK \ + -I"$root/build/packages/ziran/include" -I"$work/generated" \ + "$work/generated"/*.c -o "$work/test" +env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY -u DBUS_SESSION_BUS_ADDRESS "$work/test" +echo 'Launcher entry quoting and stable app identity passed' diff --git a/tests/launcher_shortcut_ui_test.py b/tests/launcher_shortcut_ui_test.py new file mode 100644 index 000000000..ebd0514be --- /dev/null +++ b/tests/launcher_shortcut_ui_test.py @@ -0,0 +1,215 @@ +"""Pin a real app and launch its desktop entry, using only a private display.""" +import contextlib +import os +from pathlib import Path +import sqlite3 +import signal +import subprocess +import sys +import tempfile +import time + +from PIL import Image +from ui_driver import UiDriver + +ROOT = Path(__file__).resolve().parents[1] +OUTPUT = ROOT / "build/launcher-shortcut-ui-test" +OUTPUT.mkdir(parents=True, exist_ok=True) +BINARY = Path(sys.argv[1]).resolve() +DESKTOP_ENV = ("DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY", "DBUS_SESSION_BUS_ADDRESS") +assert all(not os.environ.get(key) for key in DESKTOP_ENV), "Inherited desktop environment" + + +def stop(process): + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=5) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=5) + + +def wait(predicate, description, timeout=30): + end = time.monotonic() + timeout + while time.monotonic() < end: + value = predicate() + if value: + return value + time.sleep(.05) + raise AssertionError(description) + + +with contextlib.ExitStack() as stack: + temporary = Path(stack.enter_context(tempfile.TemporaryDirectory(prefix="inbe pin % "))) + profile = temporary / "profile" + profile.mkdir() + data = temporary / "share" + data.mkdir() + env = {key: value for key, value in os.environ.items() if key not in DESKTOP_ENV} + env.pop("HARMONY_DATA_ROOT", None) + env.pop("INBE_DIARY_IMPORT", None) + env.pop("INBE_NODE_APP_FILE", None) + env.update(YUE_DESKTOP_RECOVERY="0", APP_NO_TRAY="1", SDL_AUDIODRIVER="dummy", + APP_DATA_ROOT=str(profile), XDG_DATA_HOME=str(data), INBE_DEBUG_ROUTE="1") + display_log = stack.enter_context((OUTPUT / "display.log").open("w")) + display = subprocess.Popen(["Xvfb", "-displayfd", "1", "-screen", "0", "1200x1000x24", + "-nolisten", "tcp"], env=env, stdout=subprocess.PIPE, stderr=display_log) + stack.callback(stop, display) + number = display.stdout.readline().decode().strip() + display.stdout.close() + assert number.isdecimal(), "Private display did not start" + env["DISPLAY"] = ":" + number + driver = UiDriver(OUTPUT / "driver") + env.update(driver.environment()) + + @contextlib.contextmanager + def application(name, *arguments): + log_path = OUTPUT / (name + ".log") + with log_path.open("w") as log: + app = subprocess.Popen([str(BINARY), *arguments], cwd=ROOT, env=env, + stdout=log, stderr=subprocess.STDOUT) + driver.attach(app, log_path) + try: + def window(): + assert app.poll() is None, log_path.read_text()[-4000:] + result = subprocess.run(["xdotool", "search", "--onlyvisible", "--pid", str(app.pid)], + env=env, capture_output=True, text=True, timeout=5) + return result.stdout.splitlines()[0] if result.returncode == 0 else None + owned_window = wait(window, "App did not map a window") + subprocess.run(["xdotool", "windowsize", owned_window, "1100", "900"], + env=env, check=True, capture_output=True) + wait(lambda: (profile / "inbe.db").exists(), "Database was not created") + wait(lambda: driver.tree(), "App did not draw") + yield owned_window + assert app.poll() is None, log_path.read_text()[-4000:] + finally: + stop(app) + + with application("initialize"): + pass + with sqlite3.connect(profile / "inbe.db") as db: + user = db.execute("SELECT id FROM users WHERE kind='local' LIMIT 1").fetchone()[0] + settings = dict(language="en", language_system=0, language_setup_done=1, + apps_setup_done=1, enabled_apps=63, lumi_introduced=1, + tutorial_seen=1, habits_guide_seen=1, launcher_guide_seen=1, + lumi_guides_seen=127, main_tab=3, package_updates_allowed=0, + apps_last_update_check=1900000000) + for name in ("lists", "habits", "practices", "diary", "lumi", "leaderboard"): + settings["app_used_" + name] = 1 + for key, value in settings.items(): + db.execute("INSERT INTO settings(user_id,key,value,updated_at) VALUES(?,?,?,1) " + "ON CONFLICT(user_id,key) DO UPDATE SET value=excluded.value", (user, key, str(value))) + + with application("pin") as window: + driver.press(label="Apps", role="button") + driver.wait(label="Pin to launcher", role="button") + # Match each pin to its app card by geometry, so identical action labels + # do not accidentally test a different installed app. + cards = driver.find(label="Diary", role="button") + card = next(node for node in cards if node["width"] > 100) + pins = driver.find(label="Pin to launcher", role="button") + pin = next(node for node in pins if abs(node["x"] - card["x"]) < 1 and + 0 < node["y"] - card["y"] < card["height"] + 10) + driver.press(key=pin["key"], label="Pin to launcher") + driver.wait(label="Added to your launcher.", role="text") + entry = data / "applications/xyz.waozi.inbe.diary.desktop" + assert entry.is_file() + subprocess.run(["desktop-file-validate", str(entry)], check=True, capture_output=True) + text = entry.read_text() + assert "Name=Diary\n" in text and "--app diary\n" in text + icon_path = Path(next(line[5:] for line in text.splitlines() if line.startswith("Icon="))) + with Image.open(icon_path) as icon: + assert icon.size == (128, 128) and icon.convert("RGB").getextrema()[0][0] < 100 + driver.press(key=pin["key"], label="Pin to launcher") + assert len(list((data / "applications").glob("*.desktop"))) == 1 + subprocess.run(["import", "-window", window, str(OUTPUT / "apps.png")], + env=env, check=True, capture_output=True) + + # Ask the desktop's actual entry parser to launch it. Remove the inherited + # profile so only the escaped Exec assignment can select our existing data. + entry_env = env.copy() + entry_env.pop("APP_DATA_ROOT") + with (OUTPUT / "desktop-entry.log").open("w") as log: + subprocess.run(["gio", "launch", str(entry)], env=entry_env, check=True, + stdout=log, stderr=subprocess.STDOUT, timeout=10) + + def launched_window(): + result = subprocess.run(["xdotool", "search", "--onlyvisible", "--class", + "xyz.waozi.inbe.diary"], env=env, + capture_output=True, text=True, timeout=5) + return result.stdout.splitlines()[0] if result.returncode == 0 else None + + window = wait(launched_window, "The installed desktop entry did not open Diary") + result = subprocess.run(["xdotool", "getwindowpid", window], env=env, + check=True, capture_output=True, text=True) + pid = int(result.stdout.strip()) + assert Path(f"/proc/{pid}/exe").resolve() == BINARY, "Launcher opened an unrelated process" + try: + # The process's own environment must name the disposable profile, + # including its space and percent characters, exactly. + process_env = Path(f"/proc/{pid}/environ").read_bytes().split(b"\0") + assert os.fsencode("APP_DATA_ROOT=" + str(profile)) in process_env + finally: + os.kill(pid, signal.SIGTERM) + try: + wait(lambda: not Path(f"/proc/{pid}/exe").exists(), "Pinned Diary did not stop", timeout=5) + except AssertionError: + assert Path(f"/proc/{pid}/exe").resolve() == BINARY + os.kill(pid, signal.SIGKILL) + wait(lambda: not Path(f"/proc/{pid}/exe").exists(), "Pinned Diary did not stop", timeout=5) + + for name, title in (("diary", "Diary"), ("lists", "Lists"), ("habits", "Habits"), + ("practices", "Practice"), ("lumi", "Lumi"), ("leaderboard", "Leaderboard")): + with application("launch-" + name, "--app", name) as window: + def opened(): + result = subprocess.run(["xdotool", "getwindowname", window], env=env, + capture_output=True, text=True, timeout=5) + return result.stdout.strip() == title + wait(opened, "Named app did not open: " + name) + assert not driver.find(label="Apps", role="button"), "Harness navigation is still visible" + identity = subprocess.run(["xprop", "-id", window, "WM_CLASS"], env=env, + check=True, capture_output=True, text=True).stdout + assert "xyz.waozi.inbe." + name in identity, identity + if name == "diary": + driver.wait_idle(frames=5) + assert "Could not read this entry" not in driver.text(), driver.text() + subprocess.run(["import", "-window", window, str(OUTPUT / "diary.png")], + env=env, check=True, capture_output=True) + + node_bundle = ROOT / "build/node-apps/chess.zib" + assert node_bundle.is_file(), "Run make node-apps before this check" + env["INBE_NODE_APP_FILE"] = str(node_bundle) + with application("install-node-app"): + driver.press(label="Apps", role="button") + def chess_card(): + return next((node for node in driver.find(role="button") + if node["label"].lower() == "chess" and node["width"] > 100), None) + card = wait(chess_card, "The locally offered Chess package did not appear") + driver.press(key=card["key"], label=card["label"]) + driver.wait(label="Apps", role="button") + driver.press(label="Apps", role="button") + card = wait(chess_card, "The installed Chess package did not appear") + pin = next(node for node in driver.find(label="Pin to launcher", role="button") + if abs(node["x"] - card["x"]) < 1 and + 0 < node["y"] - card["y"] < card["height"] + 10) + node_title = card["label"] + driver.press(key=pin["key"], label="Pin to launcher") + driver.wait(label="Added to your launcher.", role="text") + entry = data / "applications/xyz.waozi.inbe.chess.desktop" + assert "--app chess\n" in entry.read_text() + + # A shortcut names the package, rather than its transient slot number. + with sqlite3.connect(profile / "inbe.db") as db: + db.execute("UPDATE settings SET value='' WHERE user_id=? AND key='node_app_slot_0'", (user,)) + db.execute("INSERT INTO settings(user_id,key,value,updated_at) VALUES(?, 'node_app_slot_3', 'chess',1) " + "ON CONFLICT(user_id,key) DO UPDATE SET value=excluded.value", (user,)) + with application("launch-node-after-slot-change", "--app", "chess") as window: + def node_opened(): + result = subprocess.run(["xdotool", "getwindowname", window], env=env, + capture_output=True, text=True, timeout=5) + return result.stdout.strip() == node_title + wait(node_opened, "The pinned node app did not follow its new slot") + assert not driver.find(label="Apps", role="button"), "Harness navigation is still visible" + +print("Launcher pin, icon, duplicate prevention, desktop entry, profile, six bundled apps and relocated node app passed") diff --git a/tests/launcher_ui_test.py b/tests/launcher_ui_test.py index 0228038cb..647b85f76 100644 --- a/tests/launcher_ui_test.py +++ b/tests/launcher_ui_test.py @@ -167,7 +167,7 @@ with contextlib.ExitStack() as stack: if node["kind"] == "text" and node["label"] in ("Pinned", "More apps")} grid = [node for node in tree if node["kind"] == "button" and by_index(tree).get(node["parent"], {}).get("kind") == "scroll" - and node["label"] not in ("Install", "Uninstall")] + and node["label"] not in ("Install", "Uninstall", "Pin to launcher")] more_top = headings["More apps"]["y"] if "More apps" in headings else float("inf") pinned = [node for node in grid if node["y"] < more_top] more = [node for node in grid if node["y"] >= more_top]