diff --git a/.github/workflows/launcher.yml b/.github/workflows/launcher.yml index ba624a2..616f82e 100644 --- a/.github/workflows/launcher.yml +++ b/.github/workflows/launcher.yml @@ -69,3 +69,76 @@ jobs: gh release create launcher-latest ultra-launcher.apk version.json --prerelease --target "$GITHUB_SHA" \ --title "ultra launcher (latest build)" \ --notes "Debug-signed APK of android/ built from $GITHUB_SHA. Install it, press Home, and pick ultra Home." + + # The Qt Quick rewrite in qt/: the grid logic and an end-to-end test of the QML UI on + # desktop Qt (offscreen), then an APK. Until it takes over, it installs as its own app + # (dev.ultra.launcher.qt, "ultra Home (Qt)") from the launcher-qt-latest prerelease. + qt-test: + runs-on: ubuntu-24.04 + timeout-minutes: 30 + steps: + - uses: actions/checkout@v5 + - uses: jurplel/install-qt-action@v4 + with: + version: "6.8.3" + cache: true + - name: Grid layout test + run: node qt/tests/layout.test.mjs + - name: Build and run the end-to-end test + run: | + sudo apt-get install -y ninja-build + cmake -S qt -B build -G Ninja -DCMAKE_BUILD_TYPE=Release + cmake --build build + QT_QPA_PLATFORM=offscreen build/ultrahome_e2e + + qt-apk: + runs-on: ubuntu-24.04 + timeout-minutes: 45 + steps: + - uses: actions/checkout@v5 + - uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: 17 + - uses: jurplel/install-qt-action@v4 + with: + version: "6.8.3" + target: android + arch: android_arm64_v8a + cache: true + - name: Android NDK for Qt 6.8 + run: | + sudo apt-get install -y ninja-build + yes | "$ANDROID_SDK_ROOT/cmdline-tools/latest/bin/sdkmanager" --install "ndk;26.1.10909125" "platforms;android-35" "build-tools;35.0.0" > /dev/null + echo "ANDROID_NDK_ROOT=$ANDROID_SDK_ROOT/ndk/26.1.10909125" >> "$GITHUB_ENV" + - name: Build the APK + # Signed with the same committed key as the WebView build, so the Qt build can + # later install over it. + env: + QT_ANDROID_KEYSTORE_PATH: ${{ github.workspace }}/android/app/debug.keystore + QT_ANDROID_KEYSTORE_ALIAS: androiddebugkey + QT_ANDROID_KEYSTORE_STORE_PASS: android + QT_ANDROID_KEYSTORE_KEY_PASS: android + run: | + "$QT_ROOT_DIR/bin/qt-cmake" -S qt -B build-android -G Ninja -DCMAKE_BUILD_TYPE=Release \ + -DANDROID_SDK_ROOT="$ANDROID_SDK_ROOT" -DANDROID_NDK_ROOT="$ANDROID_NDK_ROOT" \ + -DQT_HOST_PATH="$QT_HOST_PATH" -DQT_ANDROID_SIGN_APK=ON \ + -DVERSION_CODE=${{ github.run_number }} + cmake --build build-android --target apk + apk=$(find build-android -name "*-signed.apk" | head -1) + test -n "$apk" || { find build-android -name "*.apk"; exit 1; } + cp "$apk" ultra-launcher.apk + - uses: actions/upload-artifact@v5 + with: + name: ultra-launcher-qt-apk + path: ultra-launcher.apk + - name: Publish the launcher-qt-latest release + if: github.event_name != 'pull_request' + env: + GH_TOKEN: ${{ github.token }} + run: | + echo '{"versionCode": ${{ github.run_number }}, "commit": "'"$GITHUB_SHA"'"}' > version.json + gh release delete launcher-qt-latest --yes --cleanup-tag || true + gh release create launcher-qt-latest ultra-launcher.apk version.json --prerelease --target "$GITHUB_SHA" \ + --title "ultra launcher, Qt build (latest)" \ + --notes "The Qt Quick rewrite (qt/), built from $GITHUB_SHA. It installs next to the WebView launcher as \"ultra Home (Qt)\". Press Home and pick it to try it." diff --git a/.gitignore b/.gitignore index 6ddc840..080bab5 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,5 @@ android/.gradle/ android/build/ android/app/build/ android/local.properties +build/ +build-*/ diff --git a/README.md b/README.md index 6ab28de..25dfeec 100644 --- a/README.md +++ b/README.md @@ -26,3 +26,14 @@ cd android && ./gradlew assembleDebug # needs JDK 17 and the Android SDK `pixi run serve` serves `web/` on http://localhost:8000. In a desktop browser the launcher runs against the demo JSON files, shows a toast instead of launching, and draws widgets as labelled placeholders. Click the bar at the top to open the drawer. Every push to ultra's main publishes a new `ultra` package. To pick it up, run `pixi update ultra`, rebuild, and commit the rebuilt `web/` files. + +## Qt rewrite (in progress) + +`qt/` is the launcher rewritten as a Qt Quick (QML) app for Android, replacing ultra and the WebView. `qt/qml` is the UI (`Main.qml`, with the grid packing in `Layout.js`), `qt/src` a thin C++ backend, and `qt/android` the Java side (`HomeActivity`, a `QtActivity` that lists apps, draws icons, launches, and hosts the native widget views over the QML slots). Until it reaches parity it installs as its own app, **ultra Home (Qt)** (`dev.ultra.launcher.qt`), from the [`launcher-qt-latest` release](https://github.com/codegod100/launcher/releases/tag/launcher-qt-latest). + +```sh +node qt/tests/layout.test.mjs # grid packing +cmake -S qt -B build && cmake --build build # desktop build, needs Qt 6.8+ +build/ultrahome # try it against the demo apps +QT_QPA_PLATFORM=offscreen build/ultrahome_e2e # end-to-end test of the UI +``` diff --git a/qt/CMakeLists.txt b/qt/CMakeLists.txt new file mode 100644 index 0000000..9012286 --- /dev/null +++ b/qt/CMakeLists.txt @@ -0,0 +1,65 @@ +cmake_minimum_required(VERSION 3.21) +project(ultrahome VERSION 0.2 LANGUAGES CXX) + +# The ultra launcher, as a Qt Quick app. qt/qml is the UI; qt/src is a thin C++ backend +# over HomeActivity.java (qt/android), which does what only Android can. +# desktop: cmake -S qt -B build && cmake --build build && build/ultrahome +# android: qt-cmake -S qt -B build -DANDROID_SDK_ROOT=... -DANDROID_NDK_ROOT=... +# cmake --build build --target apk + +set(VERSION_CODE 1 CACHE STRING "Android versionCode (CI passes the workflow run number)") + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +find_package(Qt6 6.8 REQUIRED COMPONENTS Quick) +if(NOT ANDROID) + find_package(Qt6 6.8 COMPONENTS Test) +endif() +qt_standard_project_setup(REQUIRES 6.8) + +# The UI and the backend, as a static QML module both the app and its test link. +qt_add_library(launcher_ui STATIC + src/backend.cpp src/backend.h + src/iconprovider.cpp src/iconprovider.h +) +target_include_directories(launcher_ui PUBLIC src) + +qt_add_qml_module(launcher_ui + URI Launcher + VERSION 1.0 + QML_FILES + qml/Main.qml + qml/Layout.js + qml/AppIcon.qml + qml/Tile.qml + qml/Drawer.qml + qml/Sheet.qml + qml/SheetButton.qml + qml/SearchField.qml + qml/PillButton.qml + RESOURCES + demo/apps.json + demo/widgets.json +) +target_link_libraries(launcher_ui PUBLIC Qt6::Quick) + +qt_add_executable(ultrahome src/main.cpp) +target_link_libraries(ultrahome PRIVATE launcher_uiplugin launcher_ui Qt6::Quick) + +set_target_properties(ultrahome PROPERTIES + QT_ANDROID_PACKAGE_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/android" + QT_ANDROID_PACKAGE_NAME "dev.ultra.launcher.qt" + QT_ANDROID_VERSION_CODE "${VERSION_CODE}" + QT_ANDROID_VERSION_NAME "0.2.${VERSION_CODE}" + QT_ANDROID_MIN_SDK_VERSION 28 + QT_ANDROID_TARGET_SDK_VERSION 35 +) + +# The end-to-end test (desktop only): QT_QPA_PLATFORM=offscreen build/ultrahome_e2e +if(NOT ANDROID AND TARGET Qt6::Test) + qt_add_executable(ultrahome_e2e tests/e2e.cpp) + target_link_libraries(ultrahome_e2e PRIVATE launcher_uiplugin launcher_ui Qt6::Quick Qt6::Test) +endif() + +install(TARGETS ultrahome BUNDLE DESTINATION . RUNTIME DESTINATION bin) diff --git a/qt/android/AndroidManifest.xml b/qt/android/AndroidManifest.xml new file mode 100644 index 0000000..cd03ad4 --- /dev/null +++ b/qt/android/AndroidManifest.xml @@ -0,0 +1,83 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/qt/android/res/drawable/ic_launcher_background.xml b/qt/android/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..ebba2d9 --- /dev/null +++ b/qt/android/res/drawable/ic_launcher_background.xml @@ -0,0 +1,4 @@ + + + + diff --git a/qt/android/res/drawable/ic_launcher_foreground.xml b/qt/android/res/drawable/ic_launcher_foreground.xml new file mode 100644 index 0000000..d1f97a6 --- /dev/null +++ b/qt/android/res/drawable/ic_launcher_foreground.xml @@ -0,0 +1,8 @@ + + + + + diff --git a/qt/android/res/mipmap-anydpi-v26/ic_launcher.xml b/qt/android/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..6b78462 --- /dev/null +++ b/qt/android/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/qt/android/res/values/strings.xml b/qt/android/res/values/strings.xml new file mode 100644 index 0000000..6a9bf86 --- /dev/null +++ b/qt/android/res/values/strings.xml @@ -0,0 +1,7 @@ + + + ultra Home (Qt) + ultra Home window list + Lets the home screen\'s Windows button open Recents + Turn this on so the Windows button on the ultra Home screen can show your open windows (Recents). Android only lets accessibility services open Recents. This service reads nothing on screen and does nothing else. + diff --git a/qt/android/res/values/styles.xml b/qt/android/res/values/styles.xml new file mode 100644 index 0000000..838173c --- /dev/null +++ b/qt/android/res/values/styles.xml @@ -0,0 +1,12 @@ + + + + + diff --git a/qt/android/res/xml/recents_service.xml b/qt/android/res/xml/recents_service.xml new file mode 100644 index 0000000..f5eb58f --- /dev/null +++ b/qt/android/res/xml/recents_service.xml @@ -0,0 +1,9 @@ + + + diff --git a/qt/android/src/dev/ultra/launcher/HomeActivity.java b/qt/android/src/dev/ultra/launcher/HomeActivity.java new file mode 100644 index 0000000..01b2163 --- /dev/null +++ b/qt/android/src/dev/ultra/launcher/HomeActivity.java @@ -0,0 +1,745 @@ +package dev.ultra.launcher; + +import android.appwidget.AppWidgetHost; +import android.appwidget.AppWidgetHostView; +import android.appwidget.AppWidgetManager; +import android.appwidget.AppWidgetProviderInfo; +import android.content.ActivityNotFoundException; +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.pm.ApplicationInfo; +import android.content.pm.LauncherActivityInfo; +import android.content.pm.LauncherApps; +import android.content.pm.PackageManager; +import android.graphics.Bitmap; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Insets; +import android.graphics.Rect; +import android.graphics.drawable.ColorDrawable; +import android.graphics.drawable.Drawable; +import android.net.Uri; +import android.os.Build; +import android.os.Bundle; +import android.os.Handler; +import android.os.Looper; +import android.os.Process; +import android.os.UserHandle; +import android.provider.Settings; +import android.util.Log; +import android.util.SizeF; +import android.view.HapticFeedbackConstants; +import android.view.KeyEvent; +import android.view.MotionEvent; +import android.view.View; +import android.view.ViewConfiguration; +import android.view.ViewGroup; +import android.view.Window; +import android.view.WindowInsets; +import android.view.WindowManager; +import android.widget.FrameLayout; +import android.widget.Toast; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.qtproject.qt.android.bindings.QtActivity; + +import java.io.ByteArrayOutputStream; +import java.text.Collator; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * The home screen activity. The UI is the QML app in qt/qml, run by Qt; this class is the + * Android side of it. The C++ backend (qt/src/backend.cpp) calls the static methods below + * from Qt's thread, and this class calls back through {@link Native} once Qt is ready. + * + * All geometry crossing between QML and Java is in physical screen pixels: QML maps its + * items to global coordinates and the backend scales them by the device pixel ratio. + * + * Widgets are real AppWidgetHostViews in a layer above Qt's surface. QML reports where its + * live widget slots are (placeWidgets) and this class moves the views there. + */ +public class HomeActivity extends QtActivity { + /** The GitHub release the updater installs from. */ + static final String RELEASE = "launcher-qt-latest"; + static final int HOST_ID = 0x0172; + static final int REQ_BIND = 1, REQ_CONFIGURE = 2; + + private static volatile HomeActivity self; + private static volatile boolean qtReady; + + private final Handler main = new Handler(Looper.getMainLooper()); + private LauncherApps launcher; + private final UserHandle user = Process.myUserHandle(); + private final Map activities = new ConcurrentHashMap<>(); + private AppWidgetManager widgets; + private AppWidgetHost widgetHost; + private CoverLayer widgetLayer; + private final Map widgetViews = new HashMap<>(); + private final Map widgetSizes = new HashMap<>(); + private int pendingWidget = -1; + private volatile int editingWidget = -1; + private int insetTop, insetBottom; + private final int[] layerAt = new int[2]; + + private final LauncherApps.Callback packages = new LauncherApps.Callback() { + @Override public void onPackageRemoved(String pkg, UserHandle u) { appsChanged(); } + @Override public void onPackageAdded(String pkg, UserHandle u) { appsChanged(); } + @Override public void onPackageChanged(String pkg, UserHandle u) { appsChanged(); } + @Override public void onPackagesAvailable(String[] pkgs, UserHandle u, boolean replacing) { appsChanged(); } + @Override public void onPackagesUnavailable(String[] pkgs, UserHandle u, boolean replacing) { appsChanged(); } + }; + + @Override + protected void onCreate(Bundle state) { + self = this; + super.onCreate(state); + launcher = getSystemService(LauncherApps.class); + launcher.registerCallback(packages, main); + widgets = AppWidgetManager.getInstance(this); + widgetHost = new Host(this); + seeThrough(); + } + + /** The wallpaper shows through the window and Qt's surface. */ + private void seeThrough() { + Window w = getWindow(); + w.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); + w.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER); + w.setStatusBarColor(Color.TRANSPARENT); + w.setNavigationBarColor(Color.TRANSPARENT); + if (Build.VERSION.SDK_INT >= 30) { + w.setDecorFitsSystemWindows(false); + } else { + w.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE + | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION); + } + } + + /** Called once QML is up: add the widget layer over Qt's views and start talking to it. */ + static void ready() { + HomeActivity a = self; + if (a == null) return; + a.main.post(() -> { + a.seeThrough(); + if (a.widgetLayer == null) { + a.widgetLayer = new CoverLayer(a); + ViewGroup content = a.findViewById(android.R.id.content); + content.addView(a.widgetLayer, new FrameLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); + content.setOnApplyWindowInsetsListener((v, insets) -> { + a.onInsets(insets); + return v.onApplyWindowInsets(insets); + }); + content.requestApplyInsets(); + } + qtReady = true; + Native.insets(a.insetTop, a.insetBottom); + }); + } + + private void onInsets(WindowInsets insets) { + if (Build.VERSION.SDK_INT >= 30) { + Insets bars = insets.getInsets(WindowInsets.Type.systemBars() | WindowInsets.Type.displayCutout()); + Insets ime = insets.getInsets(WindowInsets.Type.ime()); + insetTop = bars.top; + insetBottom = Math.max(bars.bottom, ime.bottom); + } else { + insetTop = insets.getSystemWindowInsetTop(); + insetBottom = insets.getSystemWindowInsetBottom(); + } + if (qtReady) Native.insets(insetTop, insetBottom); + } + + @Override + protected void onStart() { + super.onStart(); + widgetHost.startListening(); + Updater.check(this, false); + } + + @Override + protected void onStop() { + super.onStop(); + widgetHost.stopListening(); + } + + @Override + protected void onDestroy() { + launcher.unregisterCallback(packages); + if (self == this) self = null; + super.onDestroy(); + } + + // The home button while we are already in front. + @Override + protected void onNewIntent(Intent intent) { + super.onNewIntent(intent); + if (qtReady) Native.homePressed(); + } + + // A home screen has nowhere to go back to: back clears the drawer, a sheet or edit mode. + @Override + public boolean dispatchKeyEvent(KeyEvent e) { + if (e.getKeyCode() == KeyEvent.KEYCODE_BACK) { + if (e.getAction() == KeyEvent.ACTION_UP && !e.isCanceled() && qtReady) Native.backPressed(); + return true; + } + return super.dispatchKeyEvent(e); + } + + @Override + @SuppressWarnings("deprecation") + public void onBackPressed() { + if (qtReady) Native.backPressed(); + } + + private void appsChanged() { + if (qtReady) Native.appsChanged(); + } + + // ------------------------------------------------------------ called from Qt + + /** {"apps": [{"label", "component", "system"}]}, every launchable activity, by label. */ + static String apps() { + HomeActivity a = self; + if (a == null) return "{\"apps\":[]}"; + try { + List list = new ArrayList<>(a.launcher.getActivityList(null, a.user)); + Map labels = new HashMap<>(); + for (LauncherActivityInfo i : list) labels.put(i, String.valueOf(i.getLabel())); + Collator by = Collator.getInstance(); + list.sort((x, y) -> by.compare(labels.get(x), labels.get(y))); + JSONArray out = new JSONArray(); + for (LauncherActivityInfo i : list) { + ComponentName cn = i.getComponentName(); + if (cn.getPackageName().equals(a.getPackageName())) continue; + String c = cn.flattenToShortString(); + a.activities.put(c, i); + JSONObject o = new JSONObject().put("label", labels.get(i)).put("component", c); + // System apps can't be uninstalled, so the drawer offers no Uninstall for them. + if ((i.getApplicationInfo().flags & ApplicationInfo.FLAG_SYSTEM) != 0) o.put("system", true); + out.put(o); + } + return new JSONObject().put("apps", out).toString(); + } catch (JSONException | RuntimeException e) { + Log.w("ultra", "listing apps", e); + return "{\"apps\":[]}"; + } + } + + /** {"widgets": [{"label", "app", "provider", "h"}]}, every widget provider; h in dp. */ + static String widgetProviders() { + HomeActivity a = self; + if (a == null) return "{\"widgets\":[]}"; + try { + List list = new ArrayList<>(a.widgets.getInstalledProvidersForProfile(a.user)); + Map labels = new HashMap<>(); + for (AppWidgetProviderInfo w : list) labels.put(w, w.loadLabel(a.getPackageManager())); + Collator by = Collator.getInstance(); + list.sort((x, y) -> by.compare(labels.get(x), labels.get(y))); + float d = a.getResources().getDisplayMetrics().density; + JSONArray out = new JSONArray(); + for (AppWidgetProviderInfo w : list) { + int h = Math.round(w.minHeight / d); + out.put(new JSONObject() + .put("label", labels.get(w)) + .put("app", a.appLabel(w.provider.getPackageName())) + .put("provider", w.provider.flattenToShortString()) + .put("h", Math.max(80, Math.min(h + 16, 420)))); + } + return new JSONObject().put("widgets", out).toString(); + } catch (JSONException | RuntimeException e) { + Log.w("ultra", "listing widgets", e); + return "{\"widgets\":[]}"; + } + } + + private String appLabel(String pkg) { + try { + PackageManager pm = getPackageManager(); + return pm.getApplicationLabel(pm.getApplicationInfo(pkg, 0)).toString(); + } catch (PackageManager.NameNotFoundException e) { + return ""; + } + } + + // Some icon drawables don't survive being loaded and drawn concurrently. + private static final Object iconLock = new Object(); + + /** An icon as a PNG, size px square: key "a:COMPONENT" (an app) or "w:PROVIDER" (a widget). */ + static byte[] icon(String key, int size) { + HomeActivity a = self; + if (a == null || key == null || key.length() < 3) return null; + synchronized (iconLock) { + try { + Drawable d = key.startsWith("w:") ? a.widgetIcon(key.substring(2)) : a.appIcon(key.substring(2)); + return d == null ? null : toPng(d, Math.max(16, Math.min(size, 512))); + } catch (RuntimeException | OutOfMemoryError e) { + Log.w("ultra", "icon for " + key, e); + return null; + } + } + } + + private Drawable appIcon(String c) { + ComponentName cn = ComponentName.unflattenFromString(c); + if (cn == null) return null; + LauncherActivityInfo info = activities.get(c); + if (info == null) { + info = launcher.resolveActivity( + new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER).setComponent(cn), user); + } + if (info == null) return null; + Drawable d = info.getIcon(getResources().getDisplayMetrics().densityDpi); + return d != null ? d : getPackageManager().getDefaultActivityIcon(); + } + + private Drawable widgetIcon(String p) { + AppWidgetProviderInfo w = provider(p); + if (w == null) return null; + Drawable d = null; + try { + d = w.loadIcon(this, getResources().getDisplayMetrics().densityDpi); + } catch (RuntimeException e) { + Log.w("ultra", "widget icon for " + p, e); + } + if (d == null) { + try { + d = getPackageManager().getApplicationIcon(w.provider.getPackageName()); + } catch (PackageManager.NameNotFoundException | RuntimeException e) { + d = getPackageManager().getDefaultActivityIcon(); + } + } + return d; + } + + private static byte[] toPng(Drawable d, int size) { + d = d.mutate(); // setBounds on a drawable shared with other callers would move theirs + Bitmap bmp = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888); + d.setBounds(0, 0, size, size); + d.draw(new Canvas(bmp)); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + bmp.compress(Bitmap.CompressFormat.PNG, 100, out); + bmp.recycle(); + return out.toByteArray(); + } + + private AppWidgetProviderInfo provider(String p) { + ComponentName cn = p == null ? null : ComponentName.unflattenFromString(p); + if (cn == null) return null; + for (AppWidgetProviderInfo w : widgets.getInstalledProvidersForProfile(user)) { + if (w.provider.equals(cn)) return w; + } + return null; + } + + private static void onMain(java.util.function.Consumer f) { + HomeActivity a = self; + if (a != null) a.main.post(() -> f.accept(a)); + } + + static void launch(String component) { + onMain(a -> { + ComponentName cn = ComponentName.unflattenFromString(component); + try { + a.launcher.startMainActivity(cn, a.user, null, null); + } catch (ActivityNotFoundException | SecurityException | NullPointerException e) { + Toast.makeText(a, "Can't open " + component, Toast.LENGTH_SHORT).show(); + } + }); + } + + static void appInfo(String component) { + onMain(a -> { + ComponentName cn = ComponentName.unflattenFromString(component); + if (cn != null) a.launcher.startAppDetailsActivity(cn, a.user, null, null); + }); + } + + /** The system asks the user to confirm; the app list reloads when the package goes. */ + static void uninstall(String component) { + onMain(a -> { + ComponentName cn = ComponentName.unflattenFromString(component); + if (cn != null) a.startIntent(new Intent(Intent.ACTION_DELETE, + Uri.fromParts("package", cn.getPackageName(), null))); + }); + } + + static void openSettings() { onMain(a -> a.startIntent(new Intent(Settings.ACTION_SETTINGS))); } + + static void pickWallpaper() { + onMain(a -> a.startIntent(Intent.createChooser(new Intent(Intent.ACTION_SET_WALLPAPER), "Wallpaper"))); + } + + static void checkUpdates() { + HomeActivity a = self; + if (a != null) Updater.check(a, true); + } + + static void haptic() { + onMain(a -> a.getWindow().getDecorView().performHapticFeedback(HapticFeedbackConstants.LONG_PRESS, + HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING)); + } + + /** + * Show Recents through RecentsService. Until the user has turned the service on, take + * them to Accessibility settings, with our service highlighted where Settings supports it. + */ + static void openRecents() { + onMain(a -> { + if (RecentsService.showRecents()) return; + Toast.makeText(a, "Turn on \"ultra Home window list\" to show open windows", Toast.LENGTH_LONG).show(); + String me = new ComponentName(a, RecentsService.class).flattenToString(); + Bundle args = new Bundle(); + args.putString(":settings:fragment_args_key", me); + a.startIntent(new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS) + .putExtra(":settings:fragment_args_key", me) + .putExtra(":settings:show_fragment_args", args)); + }); + } + + private void startIntent(Intent i) { + try { + startActivity(i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); + } catch (ActivityNotFoundException e) { + Toast.makeText(this, "Not available on this device", Toast.LENGTH_SHORT).show(); + } + } + + // ------------------------------------------------------------ widgets + + /** Bind a widget for provider p, then configure it if it asks to be; see onActivityResult. */ + static void addWidget(String p) { + onMain(a -> a.bindWidget(p)); + } + + private void bindWidget(String p) { + AppWidgetProviderInfo w = provider(p); + if (w == null) return; + int id = widgetHost.allocateAppWidgetId(); + pendingWidget = id; + if (widgets.bindAppWidgetIdIfAllowed(id, user, w.provider, null)) { + configureWidget(id); + } else { + Intent i = new Intent(AppWidgetManager.ACTION_APPWIDGET_BIND) + .putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id) + .putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, w.provider) + .putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER_PROFILE, user); + try { + startActivityForResult(i, REQ_BIND); + } catch (ActivityNotFoundException e) { + dropPending(); + } + } + } + + private void configureWidget(int id) { + AppWidgetProviderInfo w = widgets.getAppWidgetInfo(id); + if (w != null && w.configure != null) { + try { + widgetHost.startAppWidgetConfigureActivityForResult(this, id, 0, REQ_CONFIGURE, null); + return; + } catch (ActivityNotFoundException | SecurityException e) { + // Fall through: add it unconfigured, as most launchers do. + } + } + widgetReady(id); + } + + private void widgetReady(int id) { + pendingWidget = -1; + if (qtReady) Native.widgetAdded(id); + } + + private void dropPending() { + if (pendingWidget != -1) widgetHost.deleteAppWidgetId(pendingWidget); + pendingWidget = -1; + } + + @Override + protected void onActivityResult(int req, int result, Intent data) { + super.onActivityResult(req, result, data); + if (pendingWidget == -1 || (req != REQ_BIND && req != REQ_CONFIGURE)) return; + if (result != RESULT_OK) { + dropPending(); + } else if (req == REQ_BIND) { + configureWidget(pendingWidget); + } else { + widgetReady(pendingWidget); + } + } + + static void removeWidget(int id) { + onMain(a -> { + AppWidgetHostView v = a.widgetViews.remove(id); + if (v != null && a.widgetLayer != null) a.widgetLayer.removeView(v); + a.widgetSizes.remove(id); + a.widgetHost.deleteAppWidgetId(id); + }); + } + + /** + * A placed widget's natural width and how far it may be resized, in physical px: + * {"w", "minW", "minH", "maxW", "maxH" (0 = no limit), "h", "v" (whether it resizes + * horizontally / vertically)}. + */ + static String widgetLimits(int id) { + HomeActivity a = self; + JSONObject o = new JSONObject(); + if (a == null) return o.toString(); + try { + AppWidgetProviderInfo w = a.widgets.getAppWidgetInfo(id); + if (w == null) return o.toString(); + // A minResize larger than the min size (or unset) means the min size applies. + int minW = w.minResizeWidth > 0 && w.minResizeWidth < w.minWidth ? w.minResizeWidth : w.minWidth; + int minH = w.minResizeHeight > 0 && w.minResizeHeight < w.minHeight ? w.minResizeHeight : w.minHeight; + int maxW = 0, maxH = 0; + if (Build.VERSION.SDK_INT >= 31) { + maxW = w.maxResizeWidth; + maxH = w.maxResizeHeight; + } + o.put("w", w.minWidth).put("minW", minW).put("minH", minH).put("maxW", maxW).put("maxH", maxH) + .put("h", (w.resizeMode & AppWidgetProviderInfo.RESIZE_HORIZONTAL) != 0) + .put("v", (w.resizeMode & AppWidgetProviderInfo.RESIZE_VERTICAL) != 0); + } catch (JSONException | RuntimeException e) { + Log.w("ultra", "widget limits", e); + } + return o.toString(); + } + + /** Keep the system's edge gestures off these rects ([[x, y, w, h], ...] screen px). */ + static void excludeGestures(String json) { + if (Build.VERSION.SDK_INT < 29) return; + onMain(a -> { + View root = a.getWindow().getDecorView(); + int[] at = new int[2]; + root.getLocationOnScreen(at); + List rects = new ArrayList<>(); + try { + JSONArray arr = new JSONArray(json); + for (int i = 0; i < arr.length(); i++) { + JSONArray r = arr.getJSONArray(i); + int x = r.getInt(0) - at[0], y = r.getInt(1) - at[1]; + rects.add(new Rect(x, y, x + r.getInt(2), y + r.getInt(3))); + } + } catch (JSONException e) { + return; + } + root.setSystemGestureExclusionRects(rects); + }); + } + + /** The drawer covers the screen down to y (screen px); -1 is all of it, 0 none. */ + static void coverWidgets(int y) { + onMain(a -> { + if (a.widgetLayer == null) return; + if (y <= 0) { a.widgetLayer.cover(y); return; } + a.widgetLayer.getLocationOnScreen(a.layerAt); + a.widgetLayer.cover(Math.max(1, y - a.layerAt[1])); + }); + } + + /** + * Lay widget views over QML's live slots: [[id, x, y, w, h, editing], ...] in screen + * px, where editing is 1 for the one showing resize handles. + */ + static void placeWidgets(String json) { + onMain(a -> a.place(json)); + } + + private void place(String json) { + if (widgetLayer == null) return; + float d = getResources().getDisplayMetrics().density; + widgetLayer.getLocationOnScreen(layerAt); + Map want = new HashMap<>(); + int editing = -1; + try { + JSONArray arr = new JSONArray(json); + for (int i = 0; i < arr.length(); i++) { + JSONArray r = arr.getJSONArray(i); + if (r.optInt(5) == 1) editing = r.getInt(0); + want.put(r.getInt(0), new int[] {r.getInt(1) - layerAt[0], r.getInt(2) - layerAt[1], + r.getInt(3), r.getInt(4)}); + } + } catch (JSONException e) { + return; + } + editingWidget = editing; + for (Map.Entry e : widgetViews.entrySet()) { + if (!want.containsKey(e.getKey())) e.getValue().setVisibility(View.GONE); + } + for (Map.Entry e : want.entrySet()) { + int id = e.getKey(); + int[] r = e.getValue(); + AppWidgetHostView v = widgetViews.get(id); + if (v == null) { + AppWidgetProviderInfo info = widgets.getAppWidgetInfo(id); + if (info == null) continue; // the provider was uninstalled + v = widgetHost.createView(this, id, info); + widgetViews.put(id, v); + widgetLayer.addView(v); + } + FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(r[2], r[3]); + lp.leftMargin = r[0]; + lp.topMargin = r[1]; + v.setLayoutParams(lp); + v.setVisibility(View.VISIBLE); + // Scrolling moves a widget without resizing it; only tell it about new sizes (dp). + int wdp = Math.round(r[2] / d), hdp = Math.round(r[3] / d); + long size = ((long) wdp << 32) | hdp; + Long was = widgetSizes.put(id, size); + if (was == null || was != size) { + if (Build.VERSION.SDK_INT >= 31) { + List sizes = new ArrayList<>(); + sizes.add(new SizeF(wdp, hdp)); + v.updateAppWidgetSize(new Bundle(), sizes); + } else { + v.updateAppWidgetSize(new Bundle(), wdp, hdp, wdp, hdp); + } + } + } + } + + /** + * Widget views that report a long press to QML instead of to the widget. The press + * lifts the widget's slot; the moves and the release that follow go to QML as + * widgetDrag(x, y) in screen px and widgetDrop(moved), so it can be dragged to a new + * place. A widget showing resize handles is picked up by any press on it (widgetGrab). + */ + static final class Host extends AppWidgetHost { + Host(HomeActivity a) { super(a, HOST_ID); } + + @Override + protected AppWidgetHostView onCreateView(Context context, int id, AppWidgetProviderInfo info) { + return new WidgetView(context, id); + } + } + + /** + * Holds the widget views. The app drawer slides down over the home screen, so the + * widgets must be hidden above its edge: cover(top) clips them (and their touches) + * above top px, -1 hides them all, 0 shows them all. Touches that land on no widget + * fall through to Qt underneath. + */ + static final class CoverLayer extends FrameLayout { + private int top; + + CoverLayer(Context c) { super(c); } + + void cover(int y) { + if (y == top) return; + top = y; + setVisibility(y < 0 ? View.INVISIBLE : View.VISIBLE); + setClipBounds(y > 0 ? new Rect(0, y, Math.max(getWidth(), 1), Math.max(getHeight(), y + 1)) : null); + } + + @Override + public boolean dispatchTouchEvent(MotionEvent ev) { + if (top != 0 && ev.getActionMasked() == MotionEvent.ACTION_DOWN && (top < 0 || ev.getY() < top)) return false; + return super.dispatchTouchEvent(ev); + } + } + + static final class WidgetView extends AppWidgetHostView { + private final int id; + private float downX, downY; + private boolean longPressed, moved; + private final Runnable fire = new Runnable() { + @Override public void run() { + longPressed = true; + moved = false; + performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); + setAlpha(.85f); + if (qtReady) Native.widgetMenu(id); + } + }; + + WidgetView(Context c, int id) { + super(c); + this.id = id; + } + + /** + * No inset: AppWidgetHostView pads older widgets by getDefaultPaddingForWidget + * (about 8dp a side) whenever it binds one, which left a margin inside the slot. + */ + @Override + public void setPadding(int left, int top, int right, int bottom) { + super.setPadding(0, 0, 0, 0); + } + + private int slop() { return ViewConfiguration.get(getContext()).getScaledTouchSlop(); } + + @Override + public boolean onInterceptTouchEvent(MotionEvent e) { + switch (e.getActionMasked()) { + case MotionEvent.ACTION_DOWN: + longPressed = false; + downX = e.getX(); + downY = e.getY(); + HomeActivity a = self; + if (a != null && a.editingWidget == id) { + // Being resized: the press moves it, without a long press first. + longPressed = true; + moved = false; + setAlpha(.85f); + if (qtReady) Native.widgetGrab(id); + return true; + } + postDelayed(fire, ViewConfiguration.getLongPressTimeout()); + break; + case MotionEvent.ACTION_MOVE: + if (Math.hypot(e.getX() - downX, e.getY() - downY) > slop()) removeCallbacks(fire); + break; + case MotionEvent.ACTION_UP: + case MotionEvent.ACTION_CANCEL: + removeCallbacks(fire); + if (longPressed) { + drop(); // released before any move reached onTouchEvent + return true; + } + break; + } + return longPressed; // once fired, take the gesture away from the widget + } + + private void drop() { + longPressed = false; + setAlpha(1f); + if (qtReady) Native.widgetDrop(moved); + } + + @Override + public boolean onTouchEvent(MotionEvent e) { + if (!longPressed) { + // Where no child took the press, its moves come here instead of through + // onInterceptTouchEvent; keep the gesture so they do. + int act = e.getActionMasked(); + if (act == MotionEvent.ACTION_UP || act == MotionEvent.ACTION_CANCEL + || (act == MotionEvent.ACTION_MOVE && Math.hypot(e.getX() - downX, e.getY() - downY) > slop())) { + removeCallbacks(fire); + } + return super.onTouchEvent(e) || act == MotionEvent.ACTION_DOWN; + } + switch (e.getActionMasked()) { + case MotionEvent.ACTION_MOVE: + if (!moved && Math.hypot(e.getX() - downX, e.getY() - downY) > slop()) moved = true; + // Raw screen coordinates: this view moves as QML reorders slots. + if (moved && qtReady) Native.widgetDrag(Math.round(e.getRawX()), Math.round(e.getRawY())); + break; + case MotionEvent.ACTION_UP: + case MotionEvent.ACTION_CANCEL: + drop(); + break; + } + return true; + } + } +} diff --git a/qt/android/src/dev/ultra/launcher/Native.java b/qt/android/src/dev/ultra/launcher/Native.java new file mode 100644 index 0000000..e591353 --- /dev/null +++ b/qt/android/src/dev/ultra/launcher/Native.java @@ -0,0 +1,20 @@ +package dev.ultra.launcher; + +/** + * Calls into the C++ backend (qt/src/backend.cpp registers these). HomeActivity only calls + * them once the backend has said it is ready, so they are never called unregistered. + * Geometry is in physical screen px. + */ +final class Native { + private Native() {} + + static native void appsChanged(); + static native void homePressed(); + static native void backPressed(); + static native void insets(int top, int bottom); + static native void widgetAdded(int id); + static native void widgetMenu(int id); + static native void widgetGrab(int id); + static native void widgetDrag(int x, int y); + static native void widgetDrop(boolean moved); +} diff --git a/qt/android/src/dev/ultra/launcher/RecentsService.java b/qt/android/src/dev/ultra/launcher/RecentsService.java new file mode 100644 index 0000000..9ef3551 --- /dev/null +++ b/qt/android/src/dev/ultra/launcher/RecentsService.java @@ -0,0 +1,41 @@ +package dev.ultra.launcher; + +import android.accessibilityservice.AccessibilityService; +import android.content.Intent; +import android.view.accessibility.AccessibilityEvent; + +/** + * An accessibility service that does nothing but open Recents (the system's list of open + * windows) for the home screen's Windows button. Android lets no other app open Recents, + * so the user turns this on once under Settings > Accessibility. It reads no window + * content and asks for no events. + */ +public class RecentsService extends AccessibilityService { + private static volatile RecentsService running; + + /** Open Recents; false when the service isn't turned on. */ + static boolean showRecents() { + RecentsService s = running; + return s != null && s.performGlobalAction(GLOBAL_ACTION_RECENTS); + } + + @Override + protected void onServiceConnected() { + running = this; + } + + @Override + public boolean onUnbind(Intent intent) { + running = null; + return super.onUnbind(intent); + } + + @Override + public void onDestroy() { + running = null; + super.onDestroy(); + } + + @Override public void onAccessibilityEvent(AccessibilityEvent event) { } + @Override public void onInterrupt() { } +} diff --git a/qt/android/src/dev/ultra/launcher/Updater.java b/qt/android/src/dev/ultra/launcher/Updater.java new file mode 100644 index 0000000..984da3f --- /dev/null +++ b/qt/android/src/dev/ultra/launcher/Updater.java @@ -0,0 +1,178 @@ +package dev.ultra.launcher; + +import android.app.PendingIntent; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.content.pm.PackageInfo; +import android.content.pm.PackageInstaller; +import android.content.pm.PackageManager; +import android.os.Build; +import android.os.Handler; +import android.os.Looper; +import android.util.Log; +import android.widget.Toast; + +import org.json.JSONObject; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * Updates the launcher from the rolling "launcher-latest" GitHub prerelease. CI uploads + * version.json ({"versionCode": N, "commit": SHA}) next to ultra-launcher.apk, with N the + * workflow run number, which is also the APK's versionCode. When N is newer than the installed + * build, the APK is streamed into a PackageInstaller session and committed. Android then asks + * the user to confirm (or, on Android 12+ once this app installed itself, may not ask at all). + * + * The home screen checks on start at most every CHECK_EVERY; the home menu's + * "Check for updates" checks now and reports what it found. + */ +final class Updater { + static final String BASE = "https://github.com/codegod100/launcher/releases/download/" + HomeActivity.RELEASE + "/"; + static final long CHECK_EVERY = 6 * 60 * 60 * 1000L; + static final String EXTRA_VERSION = "dev.ultra.launcher.VERSION"; + + private static final AtomicBoolean busy = new AtomicBoolean(); + private static final Handler main = new Handler(Looper.getMainLooper()); + + private Updater() {} + + private static SharedPreferences prefs(Context c) { + return c.getSharedPreferences("updater", Context.MODE_PRIVATE); + } + + /** Check in the background; manual checks always run and say what happened. */ + static void check(Context ctx, boolean manual) { + Context c = ctx.getApplicationContext(); + long now = System.currentTimeMillis(); + if (!manual && now - prefs(c).getLong("lastCheck", 0) < CHECK_EVERY) return; + if (!busy.compareAndSet(false, true)) { + if (manual) toast(c, "Already checking for updates"); + return; + } + prefs(c).edit().putLong("lastCheck", now).apply(); + if (manual) toast(c, "Checking for updates…"); + new Thread(() -> { + try { + run(c, manual); + } catch (Exception e) { + Log.w("ultra", "update check", e); + if (manual) toast(c, "Couldn't check for updates"); + } finally { + busy.set(false); + } + }, "updater").start(); + } + + private static void run(Context c, boolean manual) throws Exception { + JSONObject v = new JSONObject(new String(get(BASE + "version.json"), StandardCharsets.UTF_8)); + long latest = v.getLong("versionCode"); + long installed = installedVersion(c); + if (latest <= installed) { + if (manual) toast(c, "ultra Home is up to date (build " + installed + ")"); + return; + } + // An install the user cancelled isn't offered again until there is a newer one, or they ask. + if (!manual && latest == prefs(c).getLong("declined", -1)) return; + toast(c, "Downloading launcher update (build " + latest + ")…"); + install(c, latest); + } + + @SuppressWarnings("deprecation") + static long installedVersion(Context c) throws PackageManager.NameNotFoundException { + PackageInfo p = c.getPackageManager().getPackageInfo(c.getPackageName(), 0); + return Build.VERSION.SDK_INT >= 28 ? p.getLongVersionCode() : p.versionCode; + } + + private static void install(Context c, long version) throws IOException { + PackageInstaller pi = c.getPackageManager().getPackageInstaller(); + PackageInstaller.SessionParams params = + new PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL); + params.setAppPackageName(c.getPackageName()); + if (Build.VERSION.SDK_INT >= 31) { + params.setRequireUserAction(PackageInstaller.SessionParams.USER_ACTION_NOT_REQUIRED); + } + int id = pi.createSession(params); + try (PackageInstaller.Session s = pi.openSession(id)) { + HttpURLConnection conn = open(BASE + "ultra-launcher.apk"); + try (InputStream in = conn.getInputStream(); + OutputStream out = s.openWrite("ultra-launcher.apk", 0, conn.getContentLengthLong())) { + byte[] buf = new byte[64 * 1024]; + for (int n; (n = in.read(buf)) > 0; ) out.write(buf, 0, n); + s.fsync(out); + } finally { + conn.disconnect(); + } + Intent done = new Intent(c, InstallReceiver.class).putExtra(EXTRA_VERSION, version); + int flags = PendingIntent.FLAG_UPDATE_CURRENT + | (Build.VERSION.SDK_INT >= 31 ? PendingIntent.FLAG_MUTABLE : 0); + s.commit(PendingIntent.getBroadcast(c, id, done, flags).getIntentSender()); + } catch (IOException | RuntimeException e) { + pi.abandonSession(id); + throw e; + } + } + + private static HttpURLConnection open(String url) throws IOException { + HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); + conn.setConnectTimeout(15000); + conn.setReadTimeout(30000); + conn.setUseCaches(false); + conn.setInstanceFollowRedirects(true); // github.com redirects assets to its download host + int code = conn.getResponseCode(); + if (code != HttpURLConnection.HTTP_OK) { + conn.disconnect(); + throw new IOException("HTTP " + code + " for " + url); + } + return conn; + } + + private static byte[] get(String url) throws IOException { + HttpURLConnection conn = open(url); + try (InputStream in = conn.getInputStream()) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buf = new byte[8192]; + for (int n; (n = in.read(buf)) > 0; ) out.write(buf, 0, n); + return out.toByteArray(); + } finally { + conn.disconnect(); + } + } + + static void toast(Context c, String msg) { + main.post(() -> Toast.makeText(c, msg, Toast.LENGTH_LONG).show()); + } + + /** Hears back from the install session: shows Android's confirm screen, or notes the outcome. */ + public static final class InstallReceiver extends BroadcastReceiver { + @Override + @SuppressWarnings("deprecation") + public void onReceive(Context c, Intent intent) { + int status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE); + switch (status) { + case PackageInstaller.STATUS_PENDING_USER_ACTION: + Intent confirm = intent.getParcelableExtra(Intent.EXTRA_INTENT); + if (confirm != null) c.startActivity(confirm.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); + break; + case PackageInstaller.STATUS_SUCCESS: + break; // the new build replaces this process + case PackageInstaller.STATUS_FAILURE_ABORTED: + prefs(c).edit().putLong("declined", intent.getLongExtra(EXTRA_VERSION, -1)).apply(); + break; + default: + String why = intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE); + Log.w("ultra", "update install failed: " + status + " " + why); + Toast.makeText(c, "Launcher update failed" + (why == null ? "" : ": " + why), + Toast.LENGTH_LONG).show(); + } + } + } +} diff --git a/qt/demo/apps.json b/qt/demo/apps.json new file mode 100644 index 0000000..3318b39 --- /dev/null +++ b/qt/demo/apps.json @@ -0,0 +1,87 @@ +{ + "apps": [ + { + "label": "Calculator", + "component": "com.example.calculator/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%23f59e0b%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EC%3C/text%3E%3C/svg%3E" + }, + { + "label": "Calendar", + "component": "com.example.calendar/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%233b82f6%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EC%3C/text%3E%3C/svg%3E" + }, + { + "label": "Camera", + "component": "com.example.camera/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%2364748b%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EC%3C/text%3E%3C/svg%3E" + }, + { + "label": "Chrome", + "component": "com.example.chrome/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%2322c55e%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EC%3C/text%3E%3C/svg%3E" + }, + { + "label": "Clock", + "component": "com.example.clock/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%230ea5e9%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EC%3C/text%3E%3C/svg%3E" + }, + { + "label": "Contacts", + "component": "com.example.contacts/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%236366f1%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EC%3C/text%3E%3C/svg%3E" + }, + { + "label": "Files", + "component": "com.example.files/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%23eab308%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EF%3C/text%3E%3C/svg%3E" + }, + { + "label": "Gmail", + "component": "com.example.gmail/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%23ef4444%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EG%3C/text%3E%3C/svg%3E" + }, + { + "label": "Maps", + "component": "com.example.maps/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%2310b981%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EM%3C/text%3E%3C/svg%3E" + }, + { + "label": "Messages", + "component": "com.example.messages/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%238b5cf6%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EM%3C/text%3E%3C/svg%3E" + }, + { + "label": "Music", + "component": "com.example.music/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%23ec4899%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EM%3C/text%3E%3C/svg%3E" + }, + { + "label": "Phone", + "system": true, + "component": "com.example.phone/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%2314b8a6%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EP%3C/text%3E%3C/svg%3E" + }, + { + "label": "Photos", + "component": "com.example.photos/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%23f97316%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EP%3C/text%3E%3C/svg%3E" + }, + { + "label": "Play Store", + "system": true, + "component": "com.example.playstore/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%2306b6d4%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EP%3C/text%3E%3C/svg%3E" + }, + { + "label": "Settings", + "system": true, + "component": "com.example.settings/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%2371717a%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3ES%3C/text%3E%3C/svg%3E" + }, + { + "label": "Weather", + "component": "com.example.weather/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%2338bdf8%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EW%3C/text%3E%3C/svg%3E" + } + ] +} \ No newline at end of file diff --git a/qt/demo/widgets.json b/qt/demo/widgets.json new file mode 100644 index 0000000..c770d4c --- /dev/null +++ b/qt/demo/widgets.json @@ -0,0 +1,32 @@ +{ + "widgets": [ + { + "label": "Clock", + "app": "Clock", + "provider": "com.example.clock/.Widget", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Crect%20width%3D%2248%22%20height%3D%2248%22%20rx%3D%2212%22%20fill%3D%22%230ea5e9%22/%3E%3Crect%20x%3D%2210%22%20y%3D%2214%22%20width%3D%2228%22%20height%3D%2220%22%20rx%3D%224%22%20fill%3D%22%23fff%22%20opacity%3D%22.85%22/%3E%3C/svg%3E", + "h": 140 + }, + { + "label": "Weather", + "app": "Google", + "provider": "com.example.weather/.Widget", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Crect%20width%3D%2248%22%20height%3D%2248%22%20rx%3D%2212%22%20fill%3D%22%2338bdf8%22/%3E%3Crect%20x%3D%2210%22%20y%3D%2214%22%20width%3D%2228%22%20height%3D%2220%22%20rx%3D%224%22%20fill%3D%22%23fff%22%20opacity%3D%22.85%22/%3E%3C/svg%3E", + "h": 120 + }, + { + "label": "Calendar", + "app": "Calendar", + "provider": "com.example.calendar/.Widget", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Crect%20width%3D%2248%22%20height%3D%2248%22%20rx%3D%2212%22%20fill%3D%22%233b82f6%22/%3E%3Crect%20x%3D%2210%22%20y%3D%2214%22%20width%3D%2228%22%20height%3D%2220%22%20rx%3D%224%22%20fill%3D%22%23fff%22%20opacity%3D%22.85%22/%3E%3C/svg%3E", + "h": 200 + }, + { + "label": "Music", + "app": "Music", + "provider": "com.example.music/.Widget", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Crect%20width%3D%2248%22%20height%3D%2248%22%20rx%3D%2212%22%20fill%3D%22%23ec4899%22/%3E%3Crect%20x%3D%2210%22%20y%3D%2214%22%20width%3D%2228%22%20height%3D%2220%22%20rx%3D%224%22%20fill%3D%22%23fff%22%20opacity%3D%22.85%22/%3E%3C/svg%3E", + "h": 110 + } + ] +} diff --git a/qt/qml/AppIcon.qml b/qt/qml/AppIcon.qml new file mode 100644 index 0000000..a46bc3a --- /dev/null +++ b/qt/qml/AppIcon.qml @@ -0,0 +1,30 @@ +import QtQuick + +// An app's or widget's icon from HomeActivity (image://icon/KEY), or a blank disc +// until it arrives or if it can't be drawn. +Item { + id: root + property string key: "" // "a:COMPONENT" or "w:PROVIDER" + property int generation: 0 // bumped when the app list changes, so icons reload + property real size: 40 + width: size + height: size + + Rectangle { + anchors.fill: parent + radius: width / 2 + color: Qt.rgba(1, 1, 1, .18) + visible: img.status !== Image.Ready + } + Image { + id: img + anchors.fill: parent + asynchronous: true + fillMode: Image.PreserveAspectFit + smooth: true + mipmap: true + sourceSize.width: Math.ceil(root.size * Screen.devicePixelRatio) + sourceSize.height: Math.ceil(root.size * Screen.devicePixelRatio) + source: root.key ? "image://icon/" + encodeURIComponent(root.key) + "?" + root.generation : "" + } +} diff --git a/qt/qml/Drawer.qml b/qt/qml/Drawer.qml new file mode 100644 index 0000000..3e34467 --- /dev/null +++ b/qt/qml/Drawer.qml @@ -0,0 +1,147 @@ +import QtQuick + +// Every app, with a search. It slides down over the home screen; swiping up past the +// end of the list (or Close, or back) puts it away. In pick mode a tap adds an app to +// the home screen or takes it off, and the keyboard stays down. +Item { + id: root + property bool open: false + property bool picking: false + property var apps: [] // [{label, component, system}] + property var homeSet: ({}) // component -> true: on the home screen + property bool loading: true + property int generation: 0 + property real insetTop: 0 + property real insetBottom: 0 + property alias query: search.text + readonly property real edge: y + height // the drawer's bottom edge, for covering widgets + readonly property var shown: { + const q = search.text.toLowerCase(); + const out = []; + for (let i = 0; i < apps.length; i++) + if (!q || apps[i].label.toLowerCase().indexOf(q) >= 0) out.push(i); + return out; + } + signal openApp(int row) + signal toggleApp(int row) + signal appMenu(int row) + signal closeRequested() + + width: parent.width + height: parent.height + y: open ? 0 : -height + visible: y > -height + Behavior on y { NumberAnimation { duration: 220; easing.type: Easing.OutCubic } } + + function openFirst() { + if (shown.length > 0 && search.text.length > 0) openApp(shown[0]); + } + + onOpenChanged: { + if (open && !picking) search.focusNow(); + if (!open) { + search.input.focus = false; + Qt.inputMethod.hide(); + search.text = ""; + grid.positionViewAtBeginning(); + } + } + + Rectangle { + anchors.fill: parent + color: Qt.rgba(10 / 255, 10 / 255, 14 / 255, .9) + } + MouseArea { anchors.fill: parent } // nothing under the drawer takes its touches + + Column { + id: head + x: Math.max(16, (root.width - 560) / 2 + 16) + width: Math.min(root.width, 560) - 32 + y: root.insetTop + 16 + spacing: 16 + Row { + width: parent.width + spacing: 8 + SearchField { + id: search + width: parent.width - close.width - 8 + placeholder: "Search apps" + onAccepted: root.openFirst() + onEscaped: text = "" + } + PillButton { + id: close + anchors.verticalCenter: search.verticalCenter + text: root.picking ? "Done" : "Close" + onClicked: root.closeRequested() + } + } + Text { + visible: root.picking + width: parent.width + text: "Tap apps to add them to the home screen or take them off." + color: "white" + opacity: .8 + font.pixelSize: 14 + wrapMode: Text.Wrap + horizontalAlignment: Text.AlignHCenter + } + } + + GridView { + id: grid + objectName: "drawerGrid" + x: head.x + width: head.width + anchors.top: head.bottom + anchors.topMargin: 16 + anchors.bottom: parent.bottom + readonly property int cols: root.width >= 480 ? 5 : 4 + cellWidth: width / cols + cellHeight: 104 + clip: true + bottomMargin: root.insetBottom + 24 + boundsBehavior: Flickable.DragOverBounds + model: root.shown + // Swiping up once the list is at its end puts the drawer away. + onDragEnded: if (verticalOvershoot > 48) root.closeRequested() + delegate: Item { + id: cell + required property int index + required property var modelData + readonly property var app: root.apps[modelData] || ({}) + width: grid.cellWidth + height: grid.cellHeight + Tile { + width: parent.width + height: 84 + key: "a:" + (cell.app.component || "") + label: cell.app.label || "" + generation: root.generation + iconSize: 52 + fontSize: 12 + spacing: 6 + checkable: root.picking + checked: root.picking && root.homeSet[cell.app.component] === true + pressed: area.pressed + } + MouseArea { + id: area + width: parent.width + height: 84 + pressAndHoldInterval: 450 + onClicked: root.picking ? root.toggleApp(cell.modelData) : root.openApp(cell.modelData) + onPressAndHold: if (!root.picking) root.appMenu(cell.modelData) + } + } + } + + Text { + anchors.centerIn: grid + visible: root.loading || root.shown.length === 0 + text: root.loading ? "Loading apps…" : "No apps match." + color: "white" + opacity: .85 + font.pixelSize: 15 + } +} diff --git a/qt/qml/Layout.js b/qt/qml/Layout.js new file mode 100644 index 0000000..8c80564 --- /dev/null +++ b/qt/qml/Layout.js @@ -0,0 +1,139 @@ +.pragma library + +// The home grid, as plain functions over the home list so they can be tested on their +// own (tests/layout.test.mjs). A slot is +// {kind: "app", str: COMPONENT, x, y} +// {kind: "widget", str: LABEL, wid: HOST_ID, w: COLUMNS (0: whole row), rows, x, y} +// where x, y is the cell it was dropped into (column, row from 0), or -1, -1: placed in +// order into the first free cells that fit it ("dense" packing, so apps fill the cells +// beside a widget and the grid has no holes). + +var CELL = 64; // row height, px +var RGAP = 8; // gap between rows +var CGAP = 8; // gap between columns + +// Rows of app tiles nearest to a widget height in px, at least one. +function widgetRows(px) { + return Math.max(1, Math.floor((px + RGAP + (CELL + RGAP) / 2) / (CELL + RGAP))); +} + +function slotW(s, cols) { + if (s.kind !== "widget") return 1; + return (s.w <= 0 || s.w > cols) ? cols : s.w; +} + +function slotH(s) { + return s.kind === "widget" ? Math.max(1, s.rows | 0) : 1; +} + +function pinned(s, cols) { + return s.x >= 0 && s.y >= 0 && s.x + slotW(s, cols) <= cols; +} + +// Where each slot goes: [{col, row, w, h}] (null for a hidden slot), and the rows used, +// at least nrows (the rows that fill the screen). +function pack(home, cols, nrows, hidden) { + var occ = []; + function taken(c, r) { return occ[r] !== undefined && occ[r][c] === true; } + function fits(c, r, w, h) { + if (c < 0 || c + w > cols) return false; + for (var y = r; y < r + h; y++) + for (var x = c; x < c + w; x++) + if (taken(x, y)) return false; + return true; + } + function mark(c, r, w, h) { + for (var y = r; y < r + h; y++) { + if (occ[y] === undefined) occ[y] = []; + for (var x = c; x < c + w; x++) occ[y][x] = true; + } + } + var cells = new Array(home.length); + var rows = Math.max(0, nrows | 0); + var i, s, w, h; + // Pinned slots first, where they were put (they may overlap each other). + for (i = 0; i < home.length; i++) { + s = home[i]; + cells[i] = null; + if ((hidden && hidden[i]) || !pinned(s, cols)) continue; + w = slotW(s, cols); h = slotH(s); + cells[i] = {col: s.x, row: s.y, w: w, h: h}; + mark(s.x, s.y, w, h); + rows = Math.max(rows, s.y + h); + } + // The rest in order, each into the first free cells that fit it. + for (i = 0; i < home.length; i++) { + s = home[i]; + if ((hidden && hidden[i]) || cells[i] !== null) continue; + w = slotW(s, cols); h = slotH(s); + for (var r = 0; cells[i] === null; r++) { + for (var c = 0; c + w <= cols; c++) { + if (fits(c, r, w, h)) { + cells[i] = {col: c, row: r, w: w, h: h}; + mark(c, r, w, h); + rows = Math.max(rows, r + h); + break; + } + } + } + } + return {cells: cells, rows: rows}; +} + +// A cell's box in px, given the column width. +function box(cell, colW) { + return {x: cell.col * (colW + CGAP), y: cell.row * (CELL + RGAP), + w: cell.w * colW + (cell.w - 1) * CGAP, h: cell.h * CELL + (cell.h - 1) * RGAP}; +} + +// The cell nearest to the top left of a box at x, y (px in the grid). +function cellAt(x, y, colW) { + return [Math.max(0, Math.round(x / (colW + CGAP))), Math.max(0, Math.round(y / (CELL + RGAP)))]; +} + +// Slot i pinned with its top left at col, row (kept on the screen's grid). +function pin(home, i, col, row, cols, nrows) { + var s = home[i]; + var x = col, y = row; + if (x + slotW(s, cols) > cols) x = cols - slotW(s, cols); + if (nrows > 0 && y + slotH(s) > nrows) y = nrows - slotH(s); + s.x = Math.max(0, x); + s.y = Math.max(0, y); +} + +// Unpin the slots under pinned slot i, so they flow into free cells. +function clearCells(home, i, cols) { + var a = home[i]; + for (var j = 0; j < home.length; j++) { + var b = home[j]; + if (j === i || b.x < 0) continue; + if (b.x < a.x + slotW(a, cols) && a.x < b.x + slotW(b, cols) + && b.y < a.y + slotH(a) && a.y < b.y + slotH(b)) { + b.x = -1; + b.y = -1; + } + } +} + +// Take slot a out and put it back at b, shifting the slots between. +function move(home, a, b) { + var s = home.splice(a, 1)[0]; + home.splice(b, 0, s); +} + +// Resize steps: the number of cells (of size px, gap apart) nearest to want px, kept +// within [min, max] px where it can be (max 0: no limit), and within [lo, hi] cells. +function span(k, size, gap) { return k * size + (k - 1) * gap; } +function fit(want, lo, hi, size, gap, min, max) { + var k = Math.round((want + gap) / (size + gap)); + while (k < hi && span(k, size, gap) < min - 8) k++; + while (k > lo && max > 0 && span(k, size, gap) > max + 8) k--; + return Math.max(lo, Math.min(hi, k)); +} + +// Columns a new widget of natural width px starts at (0: the whole row). +function widgetCols(px, colW, cols) { + if (!px) return 0; + var k = Math.max(1, Math.ceil((px + CGAP - 8) / (colW + CGAP))); + return k >= cols ? 0 : k; +} diff --git a/qt/qml/Main.qml b/qt/qml/Main.qml new file mode 100644 index 0000000..819a199 --- /dev/null +++ b/qt/qml/Main.qml @@ -0,0 +1,908 @@ +import QtQuick +import Launcher.Host +import "Layout.js" as L + +// An Android home screen. The home starts blank: you add apps and widgets to it with a +// long press. Swiping down opens the drawer with every app and a search. +// +// The home grid packs apps and widgets in order with no holes (Layout.js), and runs on +// to the bottom of the screen, so the empty cells there take apps too. A long press on +// a home app or widget picks it up: drag it over another to move it there in the order, +// or into an empty cell to leave it in that cell; or let go without moving to get its +// menu. Letting go of a widget that way shows resize handles on its right and bottom +// edges instead: dragging them snaps the widget to whole grid columns and rows, within +// the sizes it allows, and dragging the widget itself moves it, staying in that mode. +// +// Host (backend.cpp, over HomeActivity.java) lists apps and widget providers, launches +// things, and draws real widget views over the slots this file reports (placeWidgets). +Window { + id: root + objectName: "home" + visible: true + width: 412 + height: 892 + color: "transparent" + title: "ultra Home" + + // ---- model + property var apps: [] // [{label, component, system}], by label + property var appRow: ({}) // component -> row in apps + property bool loading: true + property int generation: 0 // bumped when the app list changes + property var home: [] // slots, see Layout.js + property bool drawerOpen: false + property bool picking: false // the drawer adds apps to home / takes them off + property string sheet: "" // "", "menu", "item", "app", "widgets" + property int item: -1 // home slot the item sheet is about + property int appSheetRow: -1 // app row the app sheet is about + property string gone: "" // being uninstalled: its home slot goes once it leaves the list + property int lifted: -1 // home slot picked up by a long press + property int resizing: -1 // widget slot showing resize handles + property bool regrab: false // the lifted slot was grabbed from resizing: drop it back there + property var providers: [] // widget providers, for the picker + property bool wloading: false + property var chosen: null // provider being added + property real scrollY: 0 + readonly property int homeCap: 200 + + // ---- geometry (logical px) + readonly property real insetTop: Math.max(0, Host.insetTop - (Host.android ? root.y : 0)) + readonly property real insetBottom: Host.insetBottom + readonly property real contentW: Math.min(width, 560) + readonly property real contentX: (width - contentW) / 2 + readonly property real gridX: contentX + 16 + readonly property real gridW: contentW - 32 + readonly property int cols: width >= 480 ? 6 : 5 + readonly property real colW: (gridW - (cols - 1) * L.CGAP) / cols + readonly property real panelY: insetTop + 16 + readonly property real panelH: 54 + readonly property real gridTop: panelY + panelH + 16 // in home content coordinates + readonly property real gridBottom: height - (insetBottom + 24) + readonly property int nrows: home.length > 0 + ? Math.max(1, Math.floor((gridBottom - gridTop + L.RGAP) / (L.CELL + L.RGAP))) : 0 + readonly property var hidden: home.map(s => s.kind === "app" && appRow[s.str] === undefined) + readonly property var packed: L.pack(home, cols, nrows, hidden) + readonly property real gridH: Math.max(0, packed.rows * (L.CELL + L.RGAP) - L.RGAP) + readonly property real contentH: gridTop + gridH + insetBottom + 24 + readonly property real maxScroll: Math.max(0, contentH - height) + onMaxScrollChanged: if (scrollY > maxScroll) scrollY = maxScroll + + function boxOf(i) { return packed.cells[i] ? L.box(packed.cells[i], colW) : null } + + // ---- updates + function commit() { + home = home.slice(); + Host.saveHome(JSON.stringify(home.map(s => s.kind === "widget" + ? {kind: "widget", str: s.str, wid: s.wid, w: s.w, rows: s.rows, x: s.x, y: s.y} + : {kind: "app", str: s.str, x: s.x, y: s.y}))); + } + + function loadHome() { + let saved = []; + try { saved = JSON.parse(Host.loadHome() || "[]"); } catch (e) { saved = []; } + const out = []; + for (const s of saved) { + if (!s || typeof s.str !== "string" || out.length >= homeCap) continue; + out.push(s.kind === "widget" + ? {kind: "widget", str: s.str, wid: s.wid | 0, w: s.w | 0, rows: Math.max(1, s.rows | 0), + x: s.x ?? -1, y: s.y ?? -1} + : {kind: "app", str: s.str, x: s.x ?? -1, y: s.y ?? -1}); + } + home = out; + } + + function loadApps() { + const list = Host.apps(); + const rows = {}; + for (let i = 0; i < list.length; i++) rows[list[i].component] = i; + apps = list; + appRow = rows; + loading = false; + dropGone(); + } + + function reload() { + generation++; + loadApps(); + if (sheet === "app") { sheet = ""; appSheetRow = -1; } + } + + // Once an app uninstalled from the drawer is out of the list, take it off home. + function dropGone() { + if (!gone || appRow[gone] !== undefined) return; + for (let i = 0; i < home.length; i++) { + if (home[i].kind === "app" && home[i].str === gone) { removeSlot(i); break; } + } + gone = ""; + } + + property string notice: "" + function say(msg) { notice = msg; noticeTimer.restart(); } + Timer { id: noticeTimer; interval: 1800; onTriggered: root.notice = "" } + + function homeOf(component) { + for (let i = 0; i < home.length; i++) + if (home[i].kind === "app" && home[i].str === component) return i; + return -1; + } + + readonly property var homeSet: { + const m = {}; + for (const s of home) if (s.kind === "app") m[s.str] = true; + return m; + } + + function addApp(row) { + const c = apps[row].component; + if (homeOf(c) >= 0) say("Already on the home screen"); + else if (home.length >= homeCap) say("The home screen is full"); + else { home.push({kind: "app", str: c, x: -1, y: -1}); commit(); say("Added to home"); } + } + + function toggleApp(row) { + const c = apps[row].component, i = homeOf(c); + if (i >= 0) removeSlot(i); + else if (home.length < homeCap) { home.push({kind: "app", str: c, x: -1, y: -1}); commit(); } + } + + function removeSlot(i) { + if (i < 0 || i >= home.length) return; + if (home[i].kind === "widget") Host.removeWidget(home[i].wid); + home.splice(i, 1); + commit(); + } + + function swapSlots(a, b) { + if (a < 0 || b < 0 || a >= home.length || b >= home.length) return; + const t = home[a]; home[a] = home[b]; home[b] = t; + commit(); + } + + function slotOfWidget(wid) { + for (let i = 0; i < home.length; i++) + if (home[i].kind === "widget" && home[i].wid === wid) return i; + return -1; + } + + function closeAll() { + drawerOpen = false; picking = false; sheet = ""; item = -1; appSheetRow = -1; + lifted = -1; resizing = -1; regrab = false; + } + + function openDrawer() { if (sheet === "") drawerOpen = true; } + function closeDrawer() { if (drawerOpen && sheet === "") { drawerOpen = false; picking = false; } } + function closeSheet() { sheet = ""; item = -1; appSheetRow = -1; } + + function launchApp(row) { Host.launch(apps[row].component); closeAll(); } + + function back() { + if (lifted >= 0) { lifted = -1; regrab = false; } + else if (resizing >= 0) resizing = -1; + else if (sheet !== "") closeSheet(); + else if (drawerOpen) { drawerOpen = false; picking = false; } + } + + function goHome() { closeAll(); scrollY = 0; } + + // ---- picking up and moving home slots + function lift(i) { + if (drawerOpen || sheet !== "" || i === lifted) return; + Host.haptic(); + resizing = -1; regrab = false; lifted = i; + } + function grab(i) { + if (i < 0 || i !== resizing || drawerOpen || sheet !== "") return; + resizing = -1; regrab = true; lifted = i; + } + property var carry: null // {dx, dy, cell}: where the lifted slot was held, the cell sent last + + function toGrid(x, y) { return {x: x - gridX, y: y + scrollY - gridTop} } + function inside(b, x, y) { return b && x >= b.x && x <= b.x + b.w && y >= b.y && y <= b.y + b.h } + // The slot under grid point x, y (not the lifted one if skipLifted). + function slotAtGrid(x, y, skipLifted) { + for (let i = 0; i < home.length; i++) { + if (skipLifted && i === lifted) continue; + if (inside(boxOf(i), x, y)) return i; + } + return -1; + } + + // The finger is at x, y (window px; x0, y0 where it went down). Over another app the + // lifted app takes its place in the order (the grid stays packed); over an empty cell + // the slot is left in that cell, top left by where it was held. A widget always goes + // to the cell under it, so it can sit on any row, and apps flow around it. + function dragTo(x, y, x0, y0) { + if (lifted < 0) return; + const p = toGrid(x, y), b = boxOf(lifted); + if (!b) return; + if (!carry) { + const p0 = toGrid(x0, y0); + carry = {dx: p0.x - b.x, dy: p0.y - b.y, cell: -1}; + } + const widget = home[lifted].kind === "widget"; + if (!widget && inside(b, p.x, p.y)) return; + const fc = L.cellAt(p.x - colW / 2, p.y - L.CELL / 2, colW); + let to = slotAtGrid(p.x, p.y, true); + if (to < 0) to = slotAtGrid(fc[0] * (colW + L.CGAP) + colW / 2, fc[1] * (L.CELL + L.RGAP) + L.CELL / 2, true); + if (to >= 0 && !widget) { + carry.cell = -1; + home[lifted].x = -1; home[lifted].y = -1; // back into the flow, at that place + L.move(home, lifted, to); + lifted = to; + commit(); + return; + } + if (p.y > packed.rows * (L.CELL + L.RGAP)) return; // below the grid + const c = L.cellAt(p.x - carry.dx, p.y - carry.dy, colW); + const cell = c[1] * 64 + Math.min(c[0], 63); + if (cell !== carry.cell) { + carry.cell = cell; + L.pin(home, lifted, c[0], c[1], cols, nrows); + commit(); + } + } + + // Letting go: whatever a pinned slot now covers moves on to free cells. Let go + // without moving, an app gets its menu and a widget its resize handles. + function drop(moved) { + carry = null; + if (lifted < 0) return; + if (home[lifted].x >= 0) { L.clearCells(home, lifted, cols); commit(); } + if (!moved || regrab) { + if (home[lifted].kind === "widget") resizing = lifted; + else { item = lifted; sheet = "item"; } + } + lifted = -1; + regrab = false; + } + + // ---- widgets + function pickWidget() { + sheet = "widgets"; + widgetSearch.text = ""; + wloading = true; + Qt.callLater(() => { providers = Host.widgetProviders(); wloading = false; }); + } + readonly property var shownProviders: { + const q = widgetSearch.text.toLowerCase(), out = []; + for (let i = 0; i < providers.length; i++) { + const p = providers[i]; + if (!q || p.label.toLowerCase().indexOf(q) >= 0 || p.app.toLowerCase().indexOf(q) >= 0) out.push(i); + } + return out; + } + function chooseWidget(i) { + if (i < 0) return; + if (home.length < homeCap) { chosen = providers[i]; Host.addWidget(chosen.provider); } + else say("The home screen is full"); + closeSheet(); + } + function widgetAdded(id) { + if (!chosen || home.length >= homeCap) return; + const lim = Host.widgetLimits(id); + home.push({kind: "widget", str: chosen.label, wid: id, w: L.widgetCols(lim.w || 0, colW, cols), + rows: L.widgetRows(chosen.h), x: -1, y: -1}); + chosen = null; + commit(); + } + + // Resize the widget being edited to cols columns and rows rows. + function resizeTo(c, r) { + if (resizing < 0) return; + const s = home[resizing]; + s.w = c >= cols ? 0 : c; + s.rows = r; + if (s.x >= 0) { L.pin(home, resizing, s.x, s.y, cols, nrows); L.clearCells(home, resizing, cols); } + commit(); + } + + // ---- telling Host where the live widget slots are + // A slot is live (its native view is shown over it) while nothing covers the home + // screen. While one is resized the others step aside, so nothing covers its handles. + // Under the open drawer the widgets stay put and the drawer's edge covers them. + readonly property var liveSlots: { + const out = []; + if (drawerOpen || sheet !== "") return out; + for (let i = 0; i < home.length; i++) { + const s = home[i], b = boxOf(i); + if (s.kind !== "widget" || !b || (resizing >= 0 && i !== resizing)) continue; + const g = homeContent.mapToGlobal(gridX + b.x, gridTop + b.y - scrollY); + out.push({id: s.wid, x: g.x, y: g.y, w: b.w, h: b.h, editing: i === resizing}); + } + return out; + } + property string placed: "" + function place() { + const j = JSON.stringify(liveSlots); + if (j === placed || (drawerOpen && sheet === "")) return; + placed = j; + Host.placeWidgets(liveSlots); + } + onLiveSlotsChanged: Qt.callLater(place) + + // Keep the system's back swipe off the resize handles. + readonly property var handleRects: { + if (resizing < 0 || !handles.visible || handles.width + handles.x + handles.y + handles.height < 0) return []; + return [rHandle, bHandle, rbHandle].map(h => { + const g = h.mapToGlobal(0, 0); + return {x: g.x, y: g.y, w: h.width, h: h.height}; + }); + } + onHandleRectsChanged: Host.excludeGestures(handleRects) + + // Native widgets sit above Qt's surface, so the drawer can't cover them by itself. + // While it slides the backend hides them above its bottom edge (a little ahead, by + // its speed, since the native side trails a frame), and once it is gone shows them + // again after a frame without it. + property real coverSent: 0 + property real coverLast: 0 + property bool uncoverPending: false + function cover() { + let y = 0; + if (drawer.visible) { + const b = drawer.edge; + y = b >= height - 1 ? -1 : Math.max(0, Math.ceil(b + 2 * Math.max(0, b - coverLast))); + coverLast = b; + if (y >= height) y = height - 1; + } else coverLast = 0; + if (y === 0) { if (coverSent !== 0) uncoverPending = true; return; } + uncoverPending = false; + const gy = y < 0 ? -1 : homeContent.mapToGlobal(0, y).y; + if (gy !== coverSent) { coverSent = gy; Host.coverWidgets(gy); } + } + onFrameSwapped: if (uncoverPending) { uncoverPending = false; coverSent = 0; Host.coverWidgets(0); } + + // ---- Host + Connections { + target: Host + function onAppsChanged() { root.reload() } + function onHomePressed() { root.goHome() } + function onBackPressed() { root.back() } + function onWidgetAdded(id) { root.widgetAdded(id) } + function onWidgetMenu(id) { + const i = root.slotOfWidget(id); + if (i >= 0 && !root.drawerOpen && root.sheet === "") { root.resizing = -1; root.regrab = false; root.lifted = i; } + } + function onWidgetGrab(id) { root.grab(root.slotOfWidget(id)) } + function onWidgetDrag(x, y) { + const p = homeContent.mapFromGlobal(x, y); + touch.dragged = true; + root.dragTo(p.x, p.y, p.x, p.y); + } + function onWidgetDrop(moved) { root.drop(moved) } + function onToast(text) { root.say(text) } + } + + Component.onCompleted: { + loadHome(); + Host.ready(); + Qt.callLater(loadApps); + } + + // ---- view + Item { + id: homeContent + anchors.fill: parent + + // The desktop stand-in for a wallpaper. + Rectangle { + anchors.fill: parent + visible: !Host.android + gradient: Gradient { + orientation: Gradient.Vertical + GradientStop { position: 0; color: "#1e293b" } + GradientStop { position: .55; color: "#4c1d95" } + GradientStop { position: 1; color: "#0f172a" } + } + } + + Item { + id: scroller + width: parent.width + height: root.contentH + y: -root.scrollY + + // The panel at the top of home: shortcuts to system surfaces. + Rectangle { + id: panel + width: Math.min(352, root.contentW - 32) + height: root.panelH + x: (root.width - width) / 2 + y: root.panelY + radius: 20 + color: Qt.rgba(1, 1, 1, .12) + border.color: Qt.rgba(1, 1, 1, .16) + border.width: 1 + Rectangle { + id: windowsBtn + property bool pressed: false + anchors.fill: parent + anchors.margins: 7 + radius: 14 + color: pressed ? Qt.rgba(1, 1, 1, .22) : Qt.rgba(1, 1, 1, .1) + Row { + anchors.centerIn: parent + spacing: 10 + Item { // the Windows glyph: two overlapping windows + width: 18; height: 18 + anchors.verticalCenter: parent.verticalCenter + Rectangle { x: 0; y: 0; width: 13; height: 13; radius: 4; color: "transparent" + border.color: "white"; border.width: 2; opacity: .6 } + Rectangle { x: 5; y: 5; width: 13; height: 13; radius: 4; color: Qt.rgba(1, 1, 1, .15) + border.color: "white"; border.width: 2 } + } + Text { + text: "Windows" + color: "white" + font.pixelSize: 15 + font.weight: Font.Medium + style: Text.Raised + styleColor: Qt.rgba(0, 0, 0, .35) + anchors.verticalCenter: parent.verticalCenter + } + } + } + } + + // The home grid. + Item { + id: grid + objectName: "homeGrid" + x: root.gridX + y: root.gridTop + width: root.gridW + height: root.gridH + + Repeater { + model: root.home.length + delegate: Item { + id: slot + required property int index + readonly property var s: root.home[index] || ({}) + readonly property var b: root.boxOf(index) + readonly property bool isWidget: s.kind === "widget" + readonly property bool isLifted: index === root.lifted + readonly property bool isResizing: index === root.resizing + readonly property bool live: Host.android && isWidget && !root.drawerOpen + && root.sheet === "" && (root.resizing < 0 || isResizing) + readonly property int row: isWidget ? -1 : (root.appRow[s.str] ?? -1) + objectName: "slot" + index + visible: b !== null + x: b ? b.x : 0 + y: b ? b.y : 0 + width: b ? b.w : 0 + height: b ? b.h : 0 + z: isLifted || isResizing ? 2 : 0 + scale: isLifted ? 1.12 : 1 + opacity: root.lifted >= 0 && !isLifted ? .8 : 1 + Behavior on scale { NumberAnimation { duration: 150; easing.type: Easing.OutCubic } } + + Rectangle { // the frame: a picked-up slot, or a widget with no live view + anchors.fill: parent + radius: slot.isWidget ? 20 : 16 + visible: slot.isLifted || (slot.isWidget && (!slot.live || slot.isResizing)) + color: slot.isLifted ? Qt.rgba(1, 1, 1, .16) : Qt.rgba(1, 1, 1, .1) + border.color: slot.isWidget && !slot.isLifted ? Qt.rgba(1, 1, 1, .3) : "transparent" + border.width: 1 + } + Rectangle { // the outline around a widget being resized + visible: slot.isResizing + anchors.fill: parent + anchors.margins: -5 + radius: 24 + color: "transparent" + border.color: Qt.rgba(1, 1, 1, .85) + border.width: 2 + } + Text { + visible: slot.isWidget && !slot.live + anchors.centerIn: parent + width: parent.width - 16 + text: slot.s.str || "" + color: "white" + opacity: .75 + font.pixelSize: 14 + horizontalAlignment: Text.AlignHCenter + elide: Text.ElideRight + style: Text.Raised + styleColor: Qt.rgba(0, 0, 0, .55) + } + Tile { + visible: !slot.isWidget + anchors.fill: parent + key: "a:" + (slot.s.str || "") + label: slot.row >= 0 ? root.apps[slot.row].label : "" + generation: root.generation + iconSize: 40 + fontSize: 11 + spacing: 4 + pressed: touch.pressedSlot === slot.index && !slot.isLifted && touch.pressed && root.lifted < 0 + } + } + } + } + + Text { + visible: root.home.length === 0 + x: root.contentX + 32 + width: root.contentW - 64 + y: root.height * .3 + root.insetTop + text: "Swipe down for all apps. Long-press to add apps and widgets." + color: "white" + opacity: .85 + font.pixelSize: 15 + lineHeight: 1.5 + wrapMode: Text.Wrap + horizontalAlignment: Text.AlignHCenter + style: Text.Raised + styleColor: Qt.rgba(0, 0, 0, .55) + } + } + + // Every touch on the home screen: taps, long presses, dragging a lifted slot, + // scrolling a grid taller than the screen, and the swipe down to the drawer. + MouseArea { + id: touch + objectName: "homeTouch" + anchors.fill: parent + enabled: !root.drawerOpen && root.sheet === "" + property var start: null // {x, y, t, scroll, moved} + property int pressedSlot: -1 + property bool longFired: false + property bool dragged: false + + function onPanel(x, y) { + const p = windowsBtn.mapFromItem(touch, x, y); + return p.x >= 0 && p.y >= 0 && p.x <= windowsBtn.width && p.y <= windowsBtn.height; + } + + onPressed: (m) => { + const g = root.toGrid(m.x, m.y); + start = {x: m.x, y: m.y, t: Date.now(), scroll: root.scrollY, moved: false}; + pressedSlot = root.slotAtGrid(g.x, g.y, false); + longFired = false; + dragged = false; + windowsBtn.pressed = onPanel(m.x, m.y); + if (root.resizing >= 0 && pressedSlot === root.resizing) { + // A widget showing handles is moved by its body, no long press needed. + root.grab(pressedSlot); + longFired = true; + return; + } + hold.restart(); + } + onPositionChanged: (m) => { + if (!start) return; + if (!start.moved && Math.hypot(m.x - start.x, m.y - start.y) < 10) return; + if (!start.moved) { start.moved = true; hold.stop(); windowsBtn.pressed = false; } + if (root.lifted >= 0) { dragged = true; root.dragTo(m.x, m.y, start.x, start.y); return; } + if (!longFired) root.scrollY = Math.max(0, Math.min(root.maxScroll, start.scroll - (m.y - start.y))); + } + onReleased: (m) => { + hold.stop(); + windowsBtn.pressed = false; + const s = start; + start = null; + if (!s) return; + if (root.lifted >= 0) { root.drop(s.moved); return; } + if (longFired) return; + if (!s.moved) { + const i = pressedSlot; + if (onPanel(m.x, m.y)) { Host.openRecents(); root.resizing = -1; } + else if (i >= 0 && root.home[i].kind === "app") { root.resizing = -1; Host.launch(root.home[i].str); } + else if (root.resizing >= 0) root.resizing = -1; // a tap beside the widget finishes + return; + } + const dx = m.x - s.x, dy = m.y - s.y; + if (Date.now() - s.t < 700 && Math.abs(dy) >= 60 && Math.abs(dx) <= Math.abs(dy) + && dy > 0 && s.scroll <= 0) + root.openDrawer(); + } + onCanceled: { + hold.stop(); + windowsBtn.pressed = false; + if (root.lifted >= 0) root.drop(start ? start.moved : false); + start = null; + } + Timer { + id: hold + interval: 450 + onTriggered: { + if (!touch.start || touch.start.moved) return; + touch.longFired = true; + windowsBtn.pressed = false; + if (touch.pressedSlot >= 0) root.lift(touch.pressedSlot); + else { root.resizing = -1; Host.haptic(); root.sheet = "menu"; } + } + } + } + + // Resize handles just outside the widget's right and bottom edges, where its + // native view doesn't cover them. + Item { + id: handles + readonly property var b: root.resizing >= 0 ? root.boxOf(root.resizing) : null + visible: b !== null && root.lifted < 0 && root.sheet === "" + x: root.gridX + (b ? b.x : 0) + y: root.gridTop - root.scrollY + (b ? b.y : 0) + width: b ? b.w : 0 + height: b ? b.h : 0 + property var rs: null + + function begin(edge) { + const i = root.resizing, c = root.packed.cells[i]; + // Sizes are measured from where its top left was when the drag began, + // though the widget may move as it resizes and the grid repacks. + rs = {edge: edge, lim: Host.widgetLimits(root.home[i].wid), cols: c.w, rows: c.h, + at: handles.mapToItem(homeContent, 0, 0)}; + } + function track(area, m) { + if (!rs) return; + const g = area.mapToItem(homeContent, m.x, m.y), lim = rs.lim; + const p = {x: g.x - rs.at.x, y: g.y - rs.at.y}; + let c = rs.cols, r = rs.rows; + if (rs.edge !== "b" && lim.h !== false) + c = L.fit(p.x, 1, root.cols, root.colW, L.CGAP, lim.minW || 0, lim.maxW || 0); + if (rs.edge !== "r" && lim.v !== false) + r = L.fit(p.y, 1, 20, L.CELL, L.RGAP, lim.minH || 0, lim.maxH || 0); + if (c === rs.cols && r === rs.rows) return; + rs.cols = c; rs.rows = r; + Host.haptic(); + root.resizeTo(c, r); + } + + component Handle: MouseArea { + id: h + property string edge + preventStealing: true + onPressed: handles.begin(edge) + onPositionChanged: (m) => handles.track(h, m) + onReleased: handles.rs = null + onCanceled: handles.rs = null + } + Handle { + id: rHandle + objectName: "handleR" + edge: "r" + x: parent.width; y: 0; width: 16; height: parent.height + Rectangle { x: 6; anchors.verticalCenter: parent.verticalCenter; width: 6; height: 40; radius: 3; color: "white" } + } + Handle { + id: bHandle + objectName: "handleB" + edge: "b" + x: 0; y: parent.height; width: parent.width; height: 16 + Rectangle { y: 5; anchors.horizontalCenter: parent.horizontalCenter; width: 40; height: 6; radius: 3; color: "white" } + } + Handle { + id: rbHandle + objectName: "handleRB" + edge: "rb" + x: parent.width - 28; y: parent.height; width: 44; height: 16 + Rectangle { x: 26; y: 1; width: 14; height: 14; radius: 4; color: "white" } + } + } + + // While a widget is resized: what to do, and Remove / Done. + Rectangle { + id: resizeBar + visible: root.resizing >= 0 && root.sheet === "" && !root.drawerOpen + anchors.horizontalCenter: parent.horizontalCenter + y: root.height - root.insetBottom - 16 - height + width: Math.min(root.width - 32, barRow.implicitWidth + 24) + height: Math.max(48, barRow.implicitHeight + 12) + radius: height / 2 + color: Qt.rgba(0, 0, 0, .8) + MouseArea { anchors.fill: parent } + Row { + id: barRow + anchors.verticalCenter: parent.verticalCenter + x: 16 + spacing: 6 + Text { + width: Math.min(implicitWidth, root.width - 32 - 24 - 16 - removeBtn.width - doneBtn.width - 12) + anchors.verticalCenter: parent.verticalCenter + text: "Drag to move, or drag the handles to resize" + color: "white" + font.pixelSize: 13 + wrapMode: Text.Wrap + } + PillButton { + id: removeBtn + text: "Remove" + fontSize: 13 + anchors.verticalCenter: parent.verticalCenter + onClicked: { const i = root.resizing; root.resizing = -1; root.removeSlot(i); } + } + PillButton { + id: doneBtn + text: "Done" + primary: true + fontSize: 13 + anchors.verticalCenter: parent.verticalCenter + onClicked: root.resizing = -1 + } + } + } + + Drawer { + id: drawer + objectName: "drawer" + open: root.drawerOpen + picking: root.picking + apps: root.apps + homeSet: root.homeSet + loading: root.loading + generation: root.generation + insetTop: root.insetTop + insetBottom: root.insetBottom + onEdgeChanged: root.cover() + onVisibleChanged: root.cover() + onOpenApp: (row) => root.launchApp(row) + onToggleApp: (row) => root.toggleApp(row) + onAppMenu: (row) => { + if (root.sheet !== "") return; + Host.haptic(); + root.appSheetRow = row; + root.sheet = "app"; + } + onCloseRequested: root.closeDrawer() + } + + // ---- sheets + Sheet { + id: menuSheet + open: root.sheet === "menu" + title: "Home screen" + bottomInset: root.insetBottom + onCloseRequested: root.closeSheet() + SheetButton { text: "Add apps"; onClicked: { root.sheet = ""; root.picking = true; root.drawerOpen = true; } } + SheetButton { text: "Add widget"; onClicked: root.pickWidget() } + SheetButton { text: "Wallpaper"; onClicked: { Host.pickWallpaper(); root.closeSheet(); } } + SheetButton { text: "Settings"; onClicked: { Host.openSettings(); root.closeSheet(); } } + SheetButton { text: "Check for updates"; onClicked: { Host.checkUpdates(); root.closeSheet(); } } + } + + Sheet { + id: itemSheet + readonly property var s: root.item >= 0 && root.item < root.home.length ? root.home[root.item] : null + open: root.sheet === "item" && s !== null + title: !s ? "" : s.kind === "widget" ? s.str + : (root.appRow[s.str] !== undefined ? root.apps[root.appRow[s.str]].label : "") + bottomInset: root.insetBottom + onCloseRequested: root.closeSheet() + SheetButton { + visible: root.item > 0 + text: "Move earlier" + onClicked: { root.swapSlots(root.item, root.item - 1); root.closeSheet(); } + } + SheetButton { + visible: root.item >= 0 && root.item < root.home.length - 1 + text: "Move later" + onClicked: { root.swapSlots(root.item + 1, root.item); root.closeSheet(); } + } + SheetButton { + visible: itemSheet.s !== null && itemSheet.s.kind === "app" + text: "App info" + onClicked: { Host.appInfo(itemSheet.s.str); root.closeSheet(); } + } + SheetButton { + text: itemSheet.s !== null && itemSheet.s.kind === "widget" ? "Remove widget" : "Remove from home" + onClicked: { const i = root.item; root.resizing = -1; root.closeSheet(); root.removeSlot(i); } + } + } + + Sheet { + id: appSheet + readonly property var app: root.appSheetRow >= 0 && root.appSheetRow < root.apps.length + ? root.apps[root.appSheetRow] : null + open: root.sheet === "app" && app !== null + title: app ? app.label : "" + bottomInset: root.insetBottom + onCloseRequested: root.closeSheet() + SheetButton { + text: appSheet.app && root.homeSet[appSheet.app.component] ? "Remove from home" : "Add to home" + onClicked: { + const c = appSheet.app.component, i = root.homeOf(c); + if (i >= 0) root.removeSlot(i); else root.addApp(root.appSheetRow); + root.closeSheet(); + } + } + SheetButton { + text: "App info" + onClicked: { Host.appInfo(appSheet.app.component); root.closeSheet(); } + } + SheetButton { + visible: appSheet.app !== null && !appSheet.app.system + text: "Uninstall" + onClicked: { root.gone = appSheet.app.component; Host.uninstall(root.gone); root.closeSheet(); } + } + } + + Sheet { + id: widgetSheet + open: root.sheet === "widgets" + title: "Add a widget" + bottomInset: root.insetBottom + onCloseRequested: root.closeSheet() + onOpenChanged: if (!open) { widgetSearch.input.focus = false; Qt.inputMethod.hide(); } + Text { + visible: root.wloading || root.providers.length === 0 || root.shownProviders.length === 0 + width: parent.width + topPadding: 12 + bottomPadding: 12 + horizontalAlignment: Text.AlignHCenter + color: "#a1a1aa" + font.pixelSize: 15 + text: root.wloading ? "Loading widgets…" + : root.providers.length === 0 ? "No widgets installed." : "No widgets match." + } + SearchField { + id: widgetSearch + visible: !root.wloading && root.providers.length > 0 + width: parent.width + height: visible ? 44 : 0 + placeholder: "Search widgets" + fontSize: 15 + color: "#27272a" + onAccepted: root.chooseWidget(root.shownProviders.length ? root.shownProviders[0] : -1) + onEscaped: text = "" + } + Item { width: 1; height: 8 } + Repeater { + model: root.wloading ? [] : root.shownProviders + delegate: Rectangle { + id: wrow + required property var modelData + readonly property var p: root.providers[modelData] + width: parent ? parent.width : 0 + height: 56 + radius: 8 + color: wArea.pressed ? "#2e2e36" : "transparent" + AppIcon { + x: 8 + anchors.verticalCenter: parent.verticalCenter + size: 40 + key: "w:" + wrow.p.provider + generation: root.generation + } + Column { + x: 60 + width: parent.width - 68 + anchors.verticalCenter: parent.verticalCenter + Text { width: parent.width; text: wrow.p.label; color: "#fafafa"; font.pixelSize: 15; elide: Text.ElideRight } + Text { + width: parent.width + visible: wrow.p.app.length > 0 && wrow.p.app !== wrow.p.label + text: wrow.p.app + color: "#a1a1aa" + font.pixelSize: 13 + elide: Text.ElideRight + } + } + MouseArea { id: wArea; anchors.fill: parent; onClicked: root.chooseWidget(wrow.modelData) } + } + } + } + + // A short notice at the bottom (e.g. "Added to home"). + Rectangle { + visible: root.notice.length > 0 + anchors.horizontalCenter: parent.horizontalCenter + y: (resizeBar.visible ? resizeBar.y - 8 : root.height - root.insetBottom - 32) - height + width: Math.min(root.width - 32, noticeText.implicitWidth + 32) + height: 36 + radius: 18 + color: Qt.rgba(0, 0, 0, .8) + Text { + id: noticeText + anchors.centerIn: parent + width: Math.min(implicitWidth, root.width - 64) + elide: Text.ElideMiddle + text: root.notice + color: "white" + font.pixelSize: 14 + } + } + } +} diff --git a/qt/qml/PillButton.qml b/qt/qml/PillButton.qml new file mode 100644 index 0000000..0f82bbb --- /dev/null +++ b/qt/qml/PillButton.qml @@ -0,0 +1,27 @@ +import QtQuick + +// A rounded text button: "ghost" (clear until pressed) or "primary" (filled). +Rectangle { + id: root + property alias text: label.text + property bool primary: false + property real fontSize: 14 + signal clicked() + implicitWidth: label.implicitWidth + 28 + implicitHeight: 36 + radius: height / 2 + color: primary ? (area.pressed ? "#d4d4d8" : "white") + : (area.pressed ? Qt.rgba(1, 1, 1, .18) : "transparent") + Text { + id: label + anchors.centerIn: parent + color: root.primary ? "#111" : "white" + font.pixelSize: root.fontSize + font.weight: Font.Medium + } + MouseArea { + id: area + anchors.fill: parent + onClicked: root.clicked() + } +} diff --git a/qt/qml/SearchField.qml b/qt/qml/SearchField.qml new file mode 100644 index 0000000..55b26ed --- /dev/null +++ b/qt/qml/SearchField.qml @@ -0,0 +1,60 @@ +import QtQuick + +// A rounded search box. Enter is "accepted"; the text is "text". +Rectangle { + id: root + property alias text: input.text + property alias placeholder: hint.text + property alias input: input + property real fontSize: 16 + signal accepted() + signal escaped() + implicitHeight: 44 + radius: height / 2 + color: Qt.rgba(1, 1, 1, .1) + border.color: Qt.rgba(1, 1, 1, .15) + border.width: 1 + + function focusNow() { input.forceActiveFocus(); Qt.inputMethod.show() } + + TextInput { + id: input + anchors.left: parent.left + anchors.right: clear.left + anchors.leftMargin: 20 + anchors.rightMargin: 8 + anchors.verticalCenter: parent.verticalCenter + color: "white" + selectionColor: Qt.rgba(1, 1, 1, .35) + font.pixelSize: root.fontSize + clip: true + inputMethodHints: Qt.ImhNoPredictiveText | Qt.ImhNoAutoUppercase + onAccepted: root.accepted() + Keys.onEscapePressed: root.escaped() + Text { + id: hint + anchors.fill: parent + verticalAlignment: Text.AlignVCenter + color: Qt.rgba(1, 1, 1, .6) + font.pixelSize: root.fontSize + visible: input.text.length === 0 && !input.preeditText + } + } + Text { + id: clear + anchors.right: parent.right + anchors.rightMargin: 14 + anchors.verticalCenter: parent.verticalCenter + width: visible ? 20 : 0 + visible: input.text.length > 0 + text: "✕" + color: Qt.rgba(1, 1, 1, .7) + font.pixelSize: 14 + horizontalAlignment: Text.AlignHCenter + MouseArea { + anchors.fill: parent + anchors.margins: -10 + onClicked: { input.text = ""; root.escaped() } + } + } +} diff --git a/qt/qml/Sheet.qml b/qt/qml/Sheet.qml new file mode 100644 index 0000000..5993f26 --- /dev/null +++ b/qt/qml/Sheet.qml @@ -0,0 +1,69 @@ +import QtQuick + +// A panel that rises from the bottom over a dimmed screen (long-press menus, the +// widget picker). Its children go in a column; tapping outside closes it. +Item { + id: root + property bool open: false + property string title: "" + property real bottomInset: 0 + property real maxWidth: 560 + default property alias content: column.data + signal closeRequested() + anchors.fill: parent + visible: open || panel.y < height + enabled: open + + Rectangle { + anchors.fill: parent + color: "black" + opacity: root.open ? .45 : 0 + Behavior on opacity { NumberAnimation { duration: 150 } } + MouseArea { anchors.fill: parent; onClicked: root.closeRequested() } + } + Rectangle { + id: panel + width: Math.min(root.width, root.maxWidth) + anchors.horizontalCenter: parent.horizontalCenter + height: Math.min(root.height * .7, column.implicitHeight + 36 + root.bottomInset + 16) + y: root.open ? root.height - height : root.height + Behavior on y { NumberAnimation { duration: 200; easing.type: Easing.OutCubic } } + radius: 20 + color: "#18181b" + MouseArea { anchors.fill: parent } // keep taps on the sheet off the overlay + // square off the bottom corners + Rectangle { anchors.bottom: parent.bottom; width: parent.width; height: 20; color: parent.color } + Rectangle { + width: 36; height: 5; radius: 3 + anchors.horizontalCenter: parent.horizontalCenter + y: 12 + color: "#3f3f46" + } + Flickable { + id: flick + anchors.fill: parent + anchors.topMargin: 28 + anchors.leftMargin: 16 + anchors.rightMargin: 16 + anchors.bottomMargin: root.bottomInset + 16 + contentHeight: column.implicitHeight + clip: true + boundsBehavior: Flickable.StopAtBounds + Column { + id: column + width: flick.width + Text { + visible: root.title.length > 0 + text: root.title + color: "#fafafa" + font.pixelSize: 16 + font.weight: Font.DemiBold + leftPadding: 8 + bottomPadding: 8 + width: parent.width + elide: Text.ElideRight + } + } + } + } +} diff --git a/qt/qml/SheetButton.qml b/qt/qml/SheetButton.qml new file mode 100644 index 0000000..2f6c0c9 --- /dev/null +++ b/qt/qml/SheetButton.qml @@ -0,0 +1,25 @@ +import QtQuick + +// A row in a sheet's menu. +Rectangle { + id: root + property alias text: label.text + signal clicked() + width: parent ? parent.width : 0 + height: 48 + radius: 8 + color: area.pressed ? "#2e2e36" : "transparent" + Text { + id: label + anchors.left: parent.left + anchors.leftMargin: 8 + anchors.verticalCenter: parent.verticalCenter + color: "#fafafa" + font.pixelSize: 16 + } + MouseArea { + id: area + anchors.fill: parent + onClicked: root.clicked() + } +} diff --git a/qt/qml/Tile.qml b/qt/qml/Tile.qml new file mode 100644 index 0000000..d619c6a --- /dev/null +++ b/qt/qml/Tile.qml @@ -0,0 +1,61 @@ +import QtQuick + +// An app: its icon over its name. +Item { + id: root + property string key: "" + property string label: "" + property int generation: 0 + property real iconSize: 40 + property real fontSize: 11 + property real spacing: 4 + property bool checkable: false // the drawer's pick mode: a check circle in the corner + property bool checked: false + property bool pressed: false + + Rectangle { + anchors.fill: parent + radius: 12 + color: Qt.rgba(1, 1, 1, .12) + visible: root.pressed + } + Column { + anchors.centerIn: parent + width: parent.width + spacing: root.spacing + AppIcon { + anchors.horizontalCenter: parent.horizontalCenter + key: root.key + generation: root.generation + size: root.iconSize + } + Text { + width: parent.width - 4 + anchors.horizontalCenter: parent.horizontalCenter + text: root.label + color: "white" + font.pixelSize: root.fontSize + horizontalAlignment: Text.AlignHCenter + elide: Text.ElideRight + style: Text.Raised + styleColor: Qt.rgba(0, 0, 0, .55) + } + } + Rectangle { + visible: root.checkable + width: 20; height: 20; radius: 10 + x: parent.width / 2 + root.iconSize / 2 - 12 + y: 2 + color: root.checked ? "white" : Qt.rgba(0, 0, 0, .35) + border.color: "white" + border.width: 2 + Text { + anchors.centerIn: parent + visible: root.checked + text: "✓" + color: "#111" + font.pixelSize: 12 + font.bold: true + } + } +} diff --git a/qt/src/backend.cpp b/qt/src/backend.cpp new file mode 100644 index 0000000..a783388 --- /dev/null +++ b/qt/src/backend.cpp @@ -0,0 +1,244 @@ +#include "backend.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef Q_OS_ANDROID +#include +#include +#endif + +namespace { +Backend *g_backend = nullptr; + +#ifdef Q_OS_ANDROID +constexpr char kActivity[] = "dev/ultra/launcher/HomeActivity"; + +QString callString(const char *method) { + return QJniObject::callStaticObjectMethod(kActivity, method, "()Ljava/lang/String;").toString(); +} + +void callWithString(const char *method, const QString &s) { + QJniObject::callStaticMethod(kActivity, method, "(Ljava/lang/String;)V", + QJniObject::fromString(s).object()); +} + +void callVoid(const char *method) { + QJniObject::callStaticMethod(kActivity, method, "()V"); +} + +// Called by HomeActivity on Android's main thread: hop over to Qt's. +template +void post(F f) { + if (g_backend) QMetaObject::invokeMethod(g_backend, f, Qt::QueuedConnection); +} + +void jAppsChanged(JNIEnv *, jclass) { post([] { emit g_backend->appsChanged(); }); } +void jHomePressed(JNIEnv *, jclass) { post([] { emit g_backend->homePressed(); }); } +void jBackPressed(JNIEnv *, jclass) { post([] { emit g_backend->backPressed(); }); } +void jInsets(JNIEnv *, jclass, jint top, jint bottom) { post([=] { g_backend->setInsets(top, bottom); }); } +void jWidgetAdded(JNIEnv *, jclass, jint id) { post([=] { emit g_backend->widgetAdded(id); }); } +void jWidgetMenu(JNIEnv *, jclass, jint id) { post([=] { emit g_backend->widgetMenu(id); }); } +void jWidgetGrab(JNIEnv *, jclass, jint id) { post([=] { emit g_backend->widgetGrab(id); }); } +void jWidgetDrag(JNIEnv *, jclass, jint x, jint y) { + post([=] { + const qreal r = QGuiApplication::primaryScreen()->devicePixelRatio(); + emit g_backend->widgetDrag(x / r, y / r); + }); +} +void jWidgetDrop(JNIEnv *, jclass, jboolean moved) { post([=] { emit g_backend->widgetDrop(moved); }); } + +void registerNatives() { + static bool done = false; + if (done) return; + done = true; + const JNINativeMethod methods[] = { + {"appsChanged", "()V", reinterpret_cast(jAppsChanged)}, + {"homePressed", "()V", reinterpret_cast(jHomePressed)}, + {"backPressed", "()V", reinterpret_cast(jBackPressed)}, + {"insets", "(II)V", reinterpret_cast(jInsets)}, + {"widgetAdded", "(I)V", reinterpret_cast(jWidgetAdded)}, + {"widgetMenu", "(I)V", reinterpret_cast(jWidgetMenu)}, + {"widgetGrab", "(I)V", reinterpret_cast(jWidgetGrab)}, + {"widgetDrag", "(II)V", reinterpret_cast(jWidgetDrag)}, + {"widgetDrop", "(Z)V", reinterpret_cast(jWidgetDrop)}, + }; + QJniEnvironment env; + env.registerNativeMethods("dev/ultra/launcher/Native", methods, int(std::size(methods))); +} +#endif + +QJsonDocument demo(const QString &name) { + QFile f(QStringLiteral(":/qt/qml/Launcher/demo/") + name); + if (!f.open(QIODevice::ReadOnly)) return {}; + return QJsonDocument::fromJson(f.readAll()); +} +} // namespace + +Backend::Backend(QObject *parent) : QObject(parent) { g_backend = this; } + +Backend *Backend::instance() { return g_backend; } + +bool Backend::isAndroid() const { +#ifdef Q_OS_ANDROID + return true; +#else + return false; +#endif +} + +qreal Backend::dpr() const { + QScreen *s = QGuiApplication::primaryScreen(); + return s ? s->devicePixelRatio() : 1.0; +} + +void Backend::setInsets(int top, int bottom) { + m_insetTop = top / dpr(); + m_insetBottom = bottom / dpr(); + emit insetsChanged(); +} + +void Backend::ready() { +#ifdef Q_OS_ANDROID + registerNatives(); + callVoid("ready"); +#endif +} + +QVariantList Backend::apps() const { +#ifdef Q_OS_ANDROID + const QJsonDocument doc = QJsonDocument::fromJson(callString("apps").toUtf8()); +#else + const QJsonDocument doc = demo(QStringLiteral("apps.json")); +#endif + QVariantList out; + for (const QJsonValue &v : doc.object().value(QStringLiteral("apps")).toArray()) { + const QJsonObject o = v.toObject(); + out.append(QVariantMap{{"label", o.value("label").toString()}, + {"component", o.value("component").toString()}, + {"system", o.value("system").toBool()}}); + } + return out; +} + +QVariantList Backend::widgetProviders() const { +#ifdef Q_OS_ANDROID + const QJsonDocument doc = QJsonDocument::fromJson(callString("widgetProviders").toUtf8()); +#else + const QJsonDocument doc = demo(QStringLiteral("widgets.json")); +#endif + QVariantList out; + for (const QJsonValue &v : doc.object().value(QStringLiteral("widgets")).toArray()) { + const QJsonObject o = v.toObject(); + out.append(QVariantMap{{"label", o.value("label").toString()}, + {"app", o.value("app").toString()}, + {"provider", o.value("provider").toString()}, + {"h", o.value("h").toInt(120)}}); + } + return out; +} + +#ifdef Q_OS_ANDROID +void Backend::launch(const QString &c) { callWithString("launch", c); } +void Backend::appInfo(const QString &c) { callWithString("appInfo", c); } +void Backend::uninstall(const QString &c) { callWithString("uninstall", c); } +void Backend::openSettings() { callVoid("openSettings"); } +void Backend::pickWallpaper() { callVoid("pickWallpaper"); } +void Backend::openRecents() { callVoid("openRecents"); } +void Backend::checkUpdates() { callVoid("checkUpdates"); } +void Backend::haptic() { callVoid("haptic"); } +void Backend::addWidget(const QString &p) { callWithString("addWidget", p); } +void Backend::removeWidget(int id) { QJniObject::callStaticMethod(kActivity, "removeWidget", "(I)V", jint(id)); } +#else +void Backend::launch(const QString &c) { emit toast("Open " + c); } +void Backend::appInfo(const QString &c) { emit toast("App info for " + c); } +void Backend::uninstall(const QString &c) { emit toast("Uninstall " + c); } +void Backend::openSettings() { emit toast("Open system settings"); } +void Backend::pickWallpaper() { emit toast("Pick a wallpaper"); } +void Backend::openRecents() { emit toast("Show open windows"); } +void Backend::checkUpdates() { emit toast("Check for updates"); } +void Backend::haptic() {} +void Backend::addWidget(const QString &) { + const int id = m_demoWidget++; + QTimer::singleShot(0, this, [this, id] { emit widgetAdded(id); }); +} +void Backend::removeWidget(int) {} +#endif + +void Backend::placeWidgets(const QVariantList &list) { +#ifdef Q_OS_ANDROID + const qreal r = dpr(); + QJsonArray out; + for (const QVariant &v : list) { + const QVariantMap m = v.toMap(); + const qreal x = m.value("x").toReal() * r, y = m.value("y").toReal() * r; + const qreal w = m.value("w").toReal() * r, h = m.value("h").toReal() * r; + out.append(QJsonArray{m.value("id").toInt(), qRound(x), qRound(y), qRound(x + w) - qRound(x), + qRound(y + h) - qRound(y), m.value("editing").toBool() ? 1 : 0}); + } + callWithString("placeWidgets", QString::fromUtf8(QJsonDocument(out).toJson(QJsonDocument::Compact))); +#else + Q_UNUSED(list); +#endif +} + +void Backend::coverWidgets(qreal y) { +#ifdef Q_OS_ANDROID + const int py = y <= 0 ? int(y) : int(std::ceil(y * dpr())); + QJniObject::callStaticMethod(kActivity, "coverWidgets", "(I)V", jint(py)); +#else + Q_UNUSED(y); +#endif +} + +QVariantMap Backend::widgetLimits(int id) const { +#ifdef Q_OS_ANDROID + const QJsonObject o = QJsonDocument::fromJson( + QJniObject::callStaticObjectMethod(kActivity, "widgetLimits", "(I)Ljava/lang/String;", jint(id)) + .toString().toUtf8()).object(); + const qreal r = dpr(); + QVariantMap m; + for (const char *k : {"w", "minW", "minH", "maxW", "maxH"}) { + if (o.contains(k)) m.insert(k, o.value(k).toDouble() / r); + } + for (const char *k : {"h", "v"}) { + if (o.contains(k)) m.insert(k, o.value(k).toBool()); + } + return m; +#else + Q_UNUSED(id); + return {{"minW", 120}, {"minH", 80}, {"maxW", 0}, {"maxH", 0}, {"h", true}, {"v", true}}; +#endif +} + +void Backend::excludeGestures(const QVariantList &rects) { +#ifdef Q_OS_ANDROID + const qreal r = dpr(); + QJsonArray out; + for (const QVariant &v : rects) { + const QVariantMap m = v.toMap(); + out.append(QJsonArray{qRound(m.value("x").toReal() * r), qRound(m.value("y").toReal() * r), + qRound(m.value("w").toReal() * r), qRound(m.value("h").toReal() * r)}); + } + callWithString("excludeGestures", QString::fromUtf8(QJsonDocument(out).toJson(QJsonDocument::Compact))); +#else + Q_UNUSED(rects); +#endif +} + +QString Backend::loadHome() const { + QSettings s; + return s.value(QStringLiteral("home")).toString(); +} + +void Backend::saveHome(const QString &json) { + QSettings s; + s.setValue(QStringLiteral("home"), json); +} diff --git a/qt/src/backend.h b/qt/src/backend.h new file mode 100644 index 0000000..8646b5e --- /dev/null +++ b/qt/src/backend.h @@ -0,0 +1,80 @@ +#pragma once + +#include +#include +#include +#include +#include + +// The QML app's window onto Android (HomeActivity.java). On a phone each call goes +// through JNI; on a desktop the backend serves demo data from qt/demo and turns the +// actions into toasts, so the UI can be tried and tested without a device. +// +// Geometry in and out of QML is in logical (QML) px; the backend scales it to the +// physical screen px HomeActivity works in. +class Backend : public QObject { + Q_OBJECT + Q_PROPERTY(bool android READ isAndroid CONSTANT) + Q_PROPERTY(qreal insetTop READ insetTop NOTIFY insetsChanged) + Q_PROPERTY(qreal insetBottom READ insetBottom NOTIFY insetsChanged) + +public: + explicit Backend(QObject *parent = nullptr); + static Backend *instance(); + + bool isAndroid() const; + qreal insetTop() const { return m_insetTop; } + qreal insetBottom() const { return m_insetBottom; } + + // Lists: [{label, component, system}] and [{label, app, provider, h}]. + Q_INVOKABLE QVariantList apps() const; + Q_INVOKABLE QVariantList widgetProviders() const; + + Q_INVOKABLE void launch(const QString &component); + Q_INVOKABLE void appInfo(const QString &component); + Q_INVOKABLE void uninstall(const QString &component); + Q_INVOKABLE void openSettings(); + Q_INVOKABLE void pickWallpaper(); + Q_INVOKABLE void openRecents(); + Q_INVOKABLE void checkUpdates(); + Q_INVOKABLE void haptic(); + + // Widgets: addWidget answers with widgetAdded(id) once bound (and configured). + Q_INVOKABLE void addWidget(const QString &provider); + Q_INVOKABLE void removeWidget(int id); + // [{id, x, y, w, h, editing}] in global logical px. + Q_INVOKABLE void placeWidgets(const QVariantList &list); + // The drawer covers the screen down to global logical y; -1 all of it, 0 none. + Q_INVOKABLE void coverWidgets(qreal y); + // {w, minW, minH, maxW, maxH (0: no limit), h, v} in logical px. + Q_INVOKABLE QVariantMap widgetLimits(int id) const; + // [{x, y, w, h}] in global logical px: no system back swipe there. + Q_INVOKABLE void excludeGestures(const QVariantList &rects); + + // The home layout, as JSON, kept in the app's settings. + Q_INVOKABLE QString loadHome() const; + Q_INVOKABLE void saveHome(const QString &json); + + // Tell HomeActivity QML is up (it then adds the widget layer and starts calling back). + Q_INVOKABLE void ready(); + + // From HomeActivity (on Android's thread; queued to Qt's). + void setInsets(int top, int bottom); + +signals: + void insetsChanged(); + void appsChanged(); + void homePressed(); + void backPressed(); + void widgetAdded(int id); + void widgetMenu(int id); + void widgetGrab(int id); + void widgetDrag(qreal x, qreal y); // global logical px + void widgetDrop(bool moved); + void toast(const QString &text); // desktop stand-in for an action + +private: + qreal dpr() const; + qreal m_insetTop = 0, m_insetBottom = 0; + mutable int m_demoWidget = 100; +}; diff --git a/qt/src/iconprovider.cpp b/qt/src/iconprovider.cpp new file mode 100644 index 0000000..a4344ff --- /dev/null +++ b/qt/src/iconprovider.cpp @@ -0,0 +1,53 @@ +#include "iconprovider.h" + +#include +#include +#include + +#ifdef Q_OS_ANDROID +#include +#include +#endif + +QImage IconProvider::requestImage(const QString &id, QSize *size, const QSize &requested) { + QString key = id; + const int q = key.lastIndexOf(QLatin1Char('?')); + if (q >= 0) key.truncate(q); + key = QUrl::fromPercentEncoding(key.toUtf8()); + const int px = requested.width() > 0 ? requested.width() : 144; + QImage img; +#ifdef Q_OS_ANDROID + QJniObject png = QJniObject::callStaticObjectMethod( + "dev/ultra/launcher/HomeActivity", "icon", "(Ljava/lang/String;I)[B", + QJniObject::fromString(key).object(), jint(px)); + if (png.isValid()) { + QJniEnvironment env; + auto arr = png.object(); + const jsize n = env->GetArrayLength(arr); + QByteArray bytes(n, Qt::Uninitialized); + env->GetByteArrayRegion(arr, 0, n, reinterpret_cast(bytes.data())); + img.loadFromData(bytes, "PNG"); + } +#else + // A disc in a colour picked from the key, with the name's first letter. + img = QImage(px, px, QImage::Format_ARGB32_Premultiplied); + img.fill(Qt::transparent); + QPainter p(&img); + p.setRenderHint(QPainter::Antialiasing); + const QColor c = QColor::fromHsv(int(qHash(key) % 360), 160, 220); + const bool widget = key.startsWith(QLatin1String("w:")); + p.setBrush(c); + p.setPen(Qt::NoPen); + if (widget) p.drawRoundedRect(QRectF(0, 0, px, px), px / 4.0, px / 4.0); + else p.drawEllipse(QRectF(0, 0, px, px)); + QString name = key.mid(2).section(QLatin1Char('/'), 0, 0).section(QLatin1Char('.'), -1); + p.setPen(Qt::white); + QFont f; + f.setPixelSize(px * 5 / 12); + f.setBold(true); + p.setFont(f); + p.drawText(QRectF(0, 0, px, px), Qt::AlignCenter, name.left(1).toUpper()); +#endif + if (size) *size = img.size(); + return img; +} diff --git a/qt/src/iconprovider.h b/qt/src/iconprovider.h new file mode 100644 index 0000000..d72b780 --- /dev/null +++ b/qt/src/iconprovider.h @@ -0,0 +1,13 @@ +#pragma once + +#include + +// image://icon/a:COMPONENT is an app's icon, image://icon/w:PROVIDER a widget's. +// On a phone HomeActivity draws them; on a desktop they are lettered discs. +// QML asks with the key percent-encoded and an optional "?n" suffix that only +// busts the pixmap cache after the app list changes. +class IconProvider : public QQuickImageProvider { +public: + IconProvider() : QQuickImageProvider(QQuickImageProvider::Image) {} + QImage requestImage(const QString &id, QSize *size, const QSize &requested) override; +}; diff --git a/qt/src/main.cpp b/qt/src/main.cpp new file mode 100644 index 0000000..a7ae38c --- /dev/null +++ b/qt/src/main.cpp @@ -0,0 +1,32 @@ +#include +#include +#include +#include +#include + +#include "backend.h" +#include "iconprovider.h" + +Q_IMPORT_QML_PLUGIN(LauncherPlugin) + +int main(int argc, char *argv[]) { + // The window is see-through: the wallpaper shows behind the home screen. + QQuickWindow::setDefaultAlphaBuffer(true); + QSurfaceFormat fmt = QSurfaceFormat::defaultFormat(); + fmt.setAlphaBufferSize(8); + QSurfaceFormat::setDefaultFormat(fmt); + + QGuiApplication app(argc, argv); + QGuiApplication::setOrganizationName(QStringLiteral("ultra")); + QGuiApplication::setApplicationName(QStringLiteral("home")); + + Backend backend; + QQmlApplicationEngine engine; + engine.addImageProvider(QStringLiteral("icon"), new IconProvider); + qmlRegisterSingletonInstance("Launcher.Host", 1, 0, "Host", &backend); + QObject::connect(&engine, &QQmlApplicationEngine::objectCreationFailed, &app, + [] { QCoreApplication::exit(1); }, Qt::QueuedConnection); + engine.loadFromModule("Launcher", "Main"); + if (engine.rootObjects().isEmpty()) return 1; + return app.exec(); +} diff --git a/qt/tests/e2e.cpp b/qt/tests/e2e.cpp new file mode 100644 index 0000000..a2b8c53 --- /dev/null +++ b/qt/tests/e2e.cpp @@ -0,0 +1,347 @@ +// End-to-end test of the QML launcher against the desktop backend's demo data +// (qt/demo): it drives the window with synthetic touches the way a finger would. +// cmake -S qt -B build && cmake --build build && QT_QPA_PLATFORM=offscreen build/ultrahome_e2e +// ULTRA_SHOTS=dir also saves a screenshot at each step. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "backend.h" +#include "iconprovider.h" + +namespace { +QQuickWindow *win = nullptr; +int failures = 0; +int shot = 0; + +QVariant js(const QString &code) { + QQmlExpression e(qmlContext(win), win, code); + QVariant v = e.evaluate(); + if (e.hasError()) { + qWarning().noquote() << "JS error in" << code << ":" << e.error().toString(); + ++failures; + } + if (v.canConvert()) v = v.value().toVariant(); + return v; +} + +void check(bool ok, const QString &what) { + if (!ok) { + ++failures; + qWarning().noquote() << "FAIL:" << what; + } else { + qInfo().noquote() << "ok " << what; + } +} + +void eq(const QVariant &got, const QVariant &want, const QString &what) { + const bool ok = got == want || got.toString() == want.toString(); + check(ok, what + (ok ? QString() : QStringLiteral(" (got %1, want %2)").arg(got.toString(), want.toString()))); +} + +void settle(int ms = 60) { QTest::qWait(ms); } + +void snap(const char *name) { + const QByteArray dir = qgetenv("ULTRA_SHOTS"); + if (dir.isEmpty()) return; + win->grabWindow().save(QStringLiteral("%1/%2-%3.png").arg(QString::fromLocal8Bit(dir)).arg(++shot, 2, 10, QLatin1Char('0')).arg(name)); +} + +QPointF center(const QString &rectJs) { + const QVariantMap r = js(rectJs).toMap(); + return {r.value("x").toReal() + r.value("w").toReal() / 2, r.value("y").toReal() + r.value("h").toReal() / 2}; +} + +// The window rect of home slot i. +QString slotRect(int i) { + return QStringLiteral("(() => { const b = boxOf(%1); return {x: gridX + b.x, y: gridTop + b.y - scrollY, w: b.w, h: b.h}; })()").arg(i); +} + +QPoint pt(QPointF p) { return p.toPoint(); } + +void press(QPointF p) { QTest::mousePress(win, Qt::LeftButton, {}, pt(p)); } +void release(QPointF p) { QTest::mouseRelease(win, Qt::LeftButton, {}, pt(p)); } +void moveTo(QPointF from, QPointF to, int steps = 8) { + for (int i = 1; i <= steps; ++i) { + QTest::mouseMove(win, pt(from + (to - from) * (qreal(i) / steps))); + QTest::qWait(10); + } +} +void tap(QPointF p) { press(p); settle(30); release(p); settle(); } +void hold(QPointF p) { press(p); QTest::qWait(560); } +void swipe(QPointF from, QPointF to) { press(from); moveTo(from, to, 6); release(to); settle(300); } + +QPointF itemCenter(const char *objectName) { + auto *it = win->findChild(QString::fromLatin1(objectName)); + if (!it) { qWarning() << "no item" << objectName; ++failures; return {}; } + return it->mapToScene(QPointF(it->width() / 2, it->height() / 2)); +} + +QString homeLabels() { + return js("home.map(s => s.kind === 'widget' ? '[' + s.str + ']' : apps[appRow[s.str]].label).join(',')").toString(); +} + +// Tap a sheet's button by its text. +void sheetButton(const QString &text) { + QQuickItem *found = nullptr; + const auto items = win->findChildren(); + for (QQuickItem *it : items) { + if (QString::fromLatin1(it->metaObject()->className()).startsWith("SheetButton") && it->isVisible() + && it->property("text").toString() == text && it->property("enabled").toBool()) { + // only buttons in an open sheet + QQuickItem *p = it->parentItem(); + bool open = false; + while (p) { + if (p->property("open").isValid()) { open = p->property("open").toBool(); break; } + p = p->parentItem(); + } + if (open) { found = it; break; } + } + } + if (!found) { + qWarning().noquote() << "no sheet button" << text; + for (QQuickItem *it : items) + if (it->property("text").isValid() && it->isVisible()) + qWarning() << " " << it->metaObject()->className() << it->property("text").toString(); + ++failures; + return; + } + settle(250); // let the sheet rise + tap(found->mapToScene(QPointF(found->width() / 2, found->height() / 2))); +} + +QStringList sheetButtons() { + QStringList out; + const auto items = win->findChildren(); + for (QQuickItem *it : items) { + if (!QString::fromLatin1(it->metaObject()->className()).startsWith("SheetButton") || !it->isVisible()) continue; + QQuickItem *p = it->parentItem(); + while (p && !p->property("open").isValid()) p = p->parentItem(); + if (p && p->property("open").toBool()) out << it->property("text").toString(); + } + return out; +} +} // namespace + +Q_IMPORT_QML_PLUGIN(LauncherPlugin) + +int main(int argc, char *argv[]) { + QStandardPaths::setTestModeEnabled(true); + QGuiApplication app(argc, argv); + QGuiApplication::setOrganizationName(QStringLiteral("ultra-test")); + QGuiApplication::setApplicationName(QStringLiteral("home-e2e")); + QSettings().clear(); + + Backend backend; + QQmlApplicationEngine engine; + engine.addImageProvider(QStringLiteral("icon"), new IconProvider); + qmlRegisterSingletonInstance("Launcher.Host", 1, 0, "Host", &backend); + engine.loadFromModule("Launcher", "Main"); + if (engine.rootObjects().isEmpty()) return 2; + win = qobject_cast(engine.rootObjects().first()); + win->resize(412, 892); + win->show(); + if (!QTest::qWaitForWindowExposed(win)) return 2; + settle(300); + snap("blank"); + + const QPointF blank(206, 700); + eq(js("home.length"), 0, "home starts blank"); + check(js("apps.length").toInt() > 5, "apps load from the demo list"); + + // the home menu's update check goes to the host and closes the menu + hold(blank); release(blank); settle(300); + eq(js("sheet"), "menu", "a long press on the blank home opens its menu"); + snap("menu"); + sheetButton("Check for updates"); + eq(js("notice"), "Check for updates", "update check goes to the host"); + eq(js("sheet"), "", "the menu closes"); + + // add apps through the drawer's pick mode + hold(blank); release(blank); settle(300); + sheetButton("Add apps"); + settle(300); + check(js("drawerOpen && picking").toBool(), "Add apps opens the drawer to pick"); + for (const char *name : {"Chrome", "Gmail", "Phone"}) { + js(QStringLiteral("drawer.query = '%1'").arg(name)); + settle(100); + auto *grid = win->findChild("drawerGrid"); + tap(grid->mapToScene(QPointF(grid->width() / 8, 42))); + js("drawer.query = ''"); + } + snap("picking"); + eq(js("home.length"), 3, "three apps picked"); + js("closeDrawer()"); + settle(300); + eq(homeLabels(), "Chrome,Gmail,Phone", "picked apps are on home in order"); + snap("three-apps"); + + // add a widget: long press on blank home, below the apps; search the picker + hold(blank); release(blank); settle(300); + sheetButton("Add widget"); + settle(200); + eq(js("sheet"), "widgets", "the widget picker opens"); + js("widgetSearch.text = 'cal'"); + eq(js("shownProviders.map(i => providers[i].label).join(',')"), "Calendar", "search the picker by widget name"); + js("widgetSearch.text = 'weather'"); + eq(js("shownProviders.map(i => providers[i].label).join(',')"), "Weather", "or by its app"); + js("widgetSearch.text = 'zzz'"); + snap("picker-empty"); + js("widgetSearch.text = 'clock'"); + js("chooseWidget(shownProviders[0])"); + settle(100); + eq(homeLabels(), "Chrome,Gmail,Phone,[Clock]", "the widget is added after the apps"); + eq(js("home[3].wid"), 100, "with the host's widget id"); + snap("widget"); + + // hold a home app and drag it over another: reorder + hold(center(slotRect(0))); + eq(js("lifted"), 0, "a long press lifts the slot"); + moveTo(center(slotRect(0)), center(slotRect(1))); + release(center(slotRect(1))); + settle(); + eq(homeLabels(), "Gmail,Chrome,Phone,[Clock]", "dragging over the next app swaps them"); + eq(js("sheet"), "", "a drag doesn't open the menu"); + eq(js("lifted"), -1, "letting go drops it"); + + // hold without moving: the menu, and Move later + hold(center(slotRect(0))); release(center(slotRect(0))); settle(300); + eq(js("sheet"), "item", "holding an app without moving opens its menu"); + snap("item-menu"); + sheetButton("Move later"); + eq(homeLabels(), "Chrome,Gmail,Phone,[Clock]", "Move later"); + + // the grid runs down the screen; an app dropped in an empty cell there stays in it + check(js("nrows").toInt() >= 8, QStringLiteral("rows fill the screen (%1)").arg(js("nrows").toInt())); + { + const QPointF from = center(slotRect(1)); + const QPointF to = from + QPointF(10, 6 * 72); + hold(from); + moveTo(from, to, 1); // a quick move, straight past the widget + release(to); + settle(); + eq(js("[home[1].x, home[1].y].join(',')"), "1,6", "Gmail is left six rows down"); + eq(js("packed.cells[0].col"), 0, "Chrome stays in the first cell"); + eq(js("packed.cells[2].col"), 1, "Phone flows up into the cell Gmail left"); + snap("pinned"); + // dragging it back over an app puts it back in the packed order + const QPointF back = center(slotRect(0)); + hold(to); + moveTo(to, back); + release(back); + settle(); + eq(homeLabels(), "Gmail,Chrome,Phone,[Clock]", "dragged back over Chrome, it takes its place"); + eq(js("home[0].x"), -1, "and is in the flow again"); + } + + // swipe down opens the drawer; search; Enter opens the first match + swipe(QPointF(206, 400), QPointF(206, 600)); + check(js("drawerOpen").toBool(), "swipe down opens the drawer"); + eq(js("liveSlots.length"), 0, "no live widget slots under the drawer"); + snap("drawer"); + js("drawer.query = 'ma'"); + eq(js("drawer.shown.map(i => apps[i].label).join(',')"), "Gmail,Maps", "the search filters the list"); + js("drawer.openFirst()"); + settle(300); + eq(js("notice"), "Open com.example.gmail/.MainActivity", "opening the first match launches it"); + check(!js("drawerOpen").toBool(), "launching closes the drawer"); + + // the drawer's long-press menu: Uninstall, not for system apps + swipe(QPointF(206, 400), QPointF(206, 600)); + js("drawer.query = 'calc'"); + settle(100); + { + auto *grid = win->findChild("drawerGrid"); + const QPointF p = grid->mapToScene(QPointF(grid->width() / 8, 42)); + hold(p); release(p); settle(300); + } + eq(sheetButtons().join(','), "Add to home,App info,Uninstall", "an app's menu in the drawer"); + snap("app-menu"); + sheetButton("Uninstall"); + eq(js("notice"), "Uninstall com.example.calculator/.MainActivity", "Uninstall goes to the host"); + check(js("sheet === '' && drawerOpen").toBool(), "uninstalling closes the menu, not the drawer"); + js("appSheetRow = drawer.shown[0]; sheet = 'app'"); + settle(250); + sheetButton("Add to home"); + eq(js("notice"), "Added to home", "Add to home says so"); + js("back()"); + settle(300); + eq(homeLabels(), "Gmail,Chrome,Phone,[Clock],Calculator", "added at the end"); + // the uninstalled app leaves home once it is gone from the list + js("apps = apps.filter(a => a.label !== 'Calculator'); const r = {}; apps.forEach((a, i) => r[a.component] = i); appRow = r; dropGone()"); + eq(homeLabels(), "Gmail,Chrome,Phone,[Clock]", "uninstalled apps leave home"); + + // tap launches + tap(center(slotRect(0))); + eq(js("notice"), "Open com.example.gmail/.MainActivity", "tapping a home app opens it"); + + // hold a widget without moving: resize handles; drag them to snap it to the grid + hold(center(slotRect(3))); release(center(slotRect(3))); settle(200); + eq(js("resizing"), 3, "a widget gets handles, not the menu"); + eq(js("sheet"), "", "and no menu"); + snap("resizing"); + { + auto *rb = win->findChild("handleRB"); + const QPointF from = rb->mapToScene(QPointF(rb->width() / 2, rb->height() / 2)); + const QVariantMap r = js(slotRect(3)).toMap(); + const qreal colW = js("colW").toReal(); + const QPointF to(r.value("x").toReal() + colW * 2.1, r.value("y").toReal() + 140); + press(from); + moveTo(from, to); + release(to); + settle(); + eq(js("[home[3].w, home[3].rows].join(',')"), "2,2", "snapped to two columns, two rows"); + eq(js("resizing"), 3, "letting go of a handle keeps the handles"); + snap("resized"); + } + // while it shows handles, dragging the widget itself moves it, without another long press + { + const QPointF from = center(slotRect(3)); + const QVariantMap r = js(slotRect(3)).toMap(); + const QPointF grabAt(r.value("x").toReal() + 20, r.value("y").toReal() + 20); + const QPointF to(js("gridX").toReal() + 20, js("gridTop").toReal() + 20); + Q_UNUSED(from); + press(grabAt); + settle(30); + eq(js("lifted"), 3, "pressing a widget with handles picks it up"); + moveTo(grabAt, to); + release(to); + settle(); + eq(js("[home[3].x, home[3].y].join(',')"), "0,0", "dragged onto the top row, first cell"); + eq(js("packed.cells.filter((c, i) => i !== 3 && c.row < 2).length"), 3, "the apps fill the cells beside it"); + eq(js("resizing"), 3, "it keeps its handles after the move"); + snap("moved-widget"); + } + // Done, then Remove from its menu + js("resizing = -1"); + hold(center(slotRect(3))); + eq(js("lifted"), 3, "hold lifts the widget"); + release(center(slotRect(3))); + settle(100); + eq(js("resizing"), 3, "and letting go shows the handles"); + js("removeSlot(resizing); resizing = -1"); + eq(homeLabels(), "Gmail,Chrome,Phone", "the widget is removed"); + + // saved, and loaded again + js("loadHome()"); + eq(homeLabels(), "Gmail,Chrome,Phone", "the layout is saved"); + + // back closes things in order; home closes everything + swipe(QPointF(206, 400), QPointF(206, 600)); + js("back()"); + settle(300); + check(!js("drawerOpen").toBool(), "back closes the drawer"); + snap("end"); + + if (failures) qWarning() << failures << "failures"; + else qInfo() << "e2e ok"; + return failures ? 1 : 0; +} diff --git a/qt/tests/layout.test.mjs b/qt/tests/layout.test.mjs new file mode 100644 index 0000000..cb555de --- /dev/null +++ b/qt/tests/layout.test.mjs @@ -0,0 +1,63 @@ +// node qt/tests/layout.test.mjs: checks the home grid packing in qml/Layout.js. +import { readFileSync } from "node:fs"; +import assert from "node:assert/strict"; + +const src = readFileSync(new URL("../qml/Layout.js", import.meta.url), "utf8").replace(".pragma library", ""); +const L = new Function(src + "; return {widgetRows, slotW, slotH, pack, box, cellAt, pin, clearCells, move, fit, widgetCols};")(); + +const app = (x = -1, y = -1) => ({ kind: "app", str: "a", x, y }); +const widget = (w, rows, x = -1, y = -1) => ({ kind: "widget", str: "W", wid: 1, w, rows, x, y }); +const cells = (home, cols = 5, nrows = 0) => L.pack(home, cols, nrows).cells.map((c) => c && [c.col, c.row, c.w, c.h]); + +// Apps fill rows left to right. +assert.deepEqual(cells([app(), app(), app(), app(), app(), app()]), + [[0, 0, 1, 1], [1, 0, 1, 1], [2, 0, 1, 1], [3, 0, 1, 1], [4, 0, 1, 1], [0, 1, 1, 1]]); +// A whole-row widget takes its rows; apps after it go below. +assert.deepEqual(cells([widget(0, 2), app()]), [[0, 0, 5, 2], [0, 2, 1, 1]]); +// Dense: apps fill the cells beside a narrow widget, before and after it in order. +assert.deepEqual(cells([widget(3, 2), app(), app(), app(), app(), app()]), + [[0, 0, 3, 2], [3, 0, 1, 1], [4, 0, 1, 1], [3, 1, 1, 1], [4, 1, 1, 1], [0, 2, 1, 1]]); +// A widget too wide for what's left of a row starts the next one, and apps backfill. +assert.deepEqual(cells([app(), app(), app(), widget(3, 1), app()]), + [[0, 0, 1, 1], [1, 0, 1, 1], [2, 0, 1, 1], [0, 1, 3, 1], [3, 0, 1, 1]]); +// Pinned slots keep their cell; the rest flow around them. +assert.deepEqual(cells([app(), app(2, 3), app()]), [[0, 0, 1, 1], [2, 3, 1, 1], [1, 0, 1, 1]]); +// Rows: at least nrows, more if the slots need them. +assert.equal(L.pack([app()], 5, 9).rows, 9); +assert.equal(L.pack([app(0, 12)], 5, 9).rows, 13); +// A pin that no longer fits the columns flows instead. +assert.deepEqual(cells([widget(3, 1, 3, 0)], 5), [[0, 0, 3, 1]]); +// Hidden slots (apps no longer installed) take no cell. +assert.deepEqual(L.pack([app(), app()], 5, 0, [true, false]).cells.map((c) => c && c.col), [null, 0]); + +// Pinning stays on the grid; dropping a pinned slot moves pinned slots off its cells. +{ + const h = [widget(2, 2), app(1, 1), app(4, 4)]; + L.pin(h, 0, 4, 9, 5, 8); + assert.deepEqual([h[0].x, h[0].y], [3, 6]); + L.pin(h, 0, 0, 0, 5, 8); + L.clearCells(h, 0, 5); + assert.deepEqual([h[1].x, h[1].y, h[2].x, h[2].y], [-1, -1, 4, 4]); +} +// Moving in the order. +{ + const h = ["a", "b", "c", "d"]; + L.move(h, 0, 2); + assert.deepEqual(h, ["b", "c", "a", "d"]); + L.move(h, 3, 0); + assert.deepEqual(h, ["d", "b", "c", "a"]); +} +// Widget heights in px to rows (64px rows, 8px gaps), as the old launcher stored them. +assert.deepEqual([40, 64, 100, 136, 208, 420].map(L.widgetRows), [1, 1, 2, 2, 3, 6]); +// Resize steps snap to cells within the widget's limits. +assert.equal(L.fit(150, 1, 5, 64, 8, 0, 0), 2); +assert.equal(L.fit(10, 1, 5, 64, 8, 200, 0), 3); +assert.equal(L.fit(400, 1, 5, 64, 8, 0, 150), 2); +// A new widget's columns from its natural width. +assert.equal(L.widgetCols(0, 70, 5), 0); +assert.equal(L.widgetCols(110, 70, 5), 2); +assert.equal(L.widgetCols(400, 70, 5), 0); +// Boxes and cells in px. +assert.deepEqual(L.box({ col: 1, row: 2, w: 2, h: 1 }, 70), { x: 78, y: 144, w: 148, h: 64 }); +assert.deepEqual(L.cellAt(80, 150, 70), [1, 2]); +console.log("layout ok");