Move the existing launcher into legacy/
git mv of everything (web/ android/ qt/ wasi/ android-wasm/ tests/ ci/ pixi.toml README) so history follows; legacy/ keeps its own .gitignore and a new root .gitignore starts for the MoonBit project. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
7d2bf5996f
commit
66e8e90da1
88 files changed
+138
-10
No files matched your search
@@ -0,0 +1,67 @@
|
||||
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_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()
|
||||
|
||||
if(NOT ANDROID)
|
||||
install(TARGETS ultrahome BUNDLE DESTINATION . RUNTIME DESTINATION bin)
|
||||
endif()
|
||||
@@ -0,0 +1,83 @@
|
||||
<?xml version="1.0"?>
|
||||
<!-- Qt fills in the %%INSERT_...%% markers when it builds the APK (androiddeployqt). -->
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
package="dev.ultra.launcher"
|
||||
android:installLocation="auto"
|
||||
android:versionCode="-- %%INSERT_VERSION_CODE%% --"
|
||||
android:versionName="-- %%INSERT_VERSION_NAME%% --">
|
||||
|
||||
<!-- %%INSERT_PERMISSIONS -->
|
||||
<!-- %%INSERT_FEATURES -->
|
||||
|
||||
<!-- The updater downloads new builds of the launcher and installs them over itself. -->
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
|
||||
<!-- Uninstall from the app drawer's long-press menu (ACTION_DELETE needs it on Android 9+). -->
|
||||
<uses-permission android:name="android.permission.REQUEST_DELETE_PACKAGES" />
|
||||
|
||||
<!-- Android 11+ package visibility: list every launchable activity. -->
|
||||
<queries>
|
||||
<intent>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent>
|
||||
</queries>
|
||||
|
||||
<supports-screens
|
||||
android:anyDensity="true"
|
||||
android:largeScreens="true"
|
||||
android:normalScreens="true"
|
||||
android:smallScreens="true" />
|
||||
|
||||
<application
|
||||
android:name="org.qtproject.qt.android.bindings.QtApplication"
|
||||
android:hardwareAccelerated="true"
|
||||
android:label="@string/app_name"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:theme="@style/Home"
|
||||
android:supportsRtl="true"
|
||||
android:allowBackup="false">
|
||||
|
||||
<activity
|
||||
android:name="dev.ultra.launcher.HomeActivity"
|
||||
android:exported="true"
|
||||
android:launchMode="singleTask"
|
||||
android:stateNotNeeded="true"
|
||||
android:clearTaskOnLaunch="true"
|
||||
android:excludeFromRecents="true"
|
||||
android:screenOrientation="unspecified"
|
||||
android:windowSoftInputMode="adjustNothing"
|
||||
android:configChanges="orientation|uiMode|screenLayout|screenSize|smallestScreenSize|layoutDirection|locale|fontScale|keyboard|keyboardHidden|navigation|mcc|mnc|density">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.HOME" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
<meta-data
|
||||
android:name="android.app.lib_name"
|
||||
android:value="-- %%INSERT_APP_LIB_NAME%% --" />
|
||||
<meta-data
|
||||
android:name="android.app.arguments"
|
||||
android:value="-- %%INSERT_APP_ARGUMENTS%% --" />
|
||||
</activity>
|
||||
|
||||
<receiver
|
||||
android:name="dev.ultra.launcher.Updater$InstallReceiver"
|
||||
android:exported="false" />
|
||||
|
||||
<!-- Opens Recents for the Windows button; the user turns it on in Accessibility. -->
|
||||
<service
|
||||
android:name="dev.ultra.launcher.RecentsService"
|
||||
android:label="@string/recents_service_label"
|
||||
android:exported="true"
|
||||
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
|
||||
<intent-filter>
|
||||
<action android:name="android.accessibilityservice.AccessibilityService" />
|
||||
</intent-filter>
|
||||
<meta-data
|
||||
android:name="android.accessibilityservice"
|
||||
android:resource="@xml/recents_service" />
|
||||
</service>
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<gradient android:angle="315" android:startColor="#4C1D95" android:endColor="#1E293B" />
|
||||
</shape>
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- A 3x3 grid of app dots inside the adaptive icon's 72dp safe zone. -->
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="108dp" android:height="108dp"
|
||||
android:viewportWidth="108" android:viewportHeight="108">
|
||||
<path android:fillColor="#FFFFFF"
|
||||
android:pathData="M36,36m-6,0a6,6 0,1 1,12 0a6,6 0,1 1,-12 0 M54,36m-6,0a6,6 0,1 1,12 0a6,6 0,1 1,-12 0 M72,36m-6,0a6,6 0,1 1,12 0a6,6 0,1 1,-12 0 M36,54m-6,0a6,6 0,1 1,12 0a6,6 0,1 1,-12 0 M54,54m-6,0a6,6 0,1 1,12 0a6,6 0,1 1,-12 0 M72,54m-6,0a6,6 0,1 1,12 0a6,6 0,1 1,-12 0 M36,72m-6,0a6,6 0,1 1,12 0a6,6 0,1 1,-12 0 M54,72m-6,0a6,6 0,1 1,12 0a6,6 0,1 1,-12 0 M72,72m-6,0a6,6 0,1 1,12 0a6,6 0,1 1,-12 0" />
|
||||
</vector>
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@drawable/ic_launcher_background" />
|
||||
<foreground android:drawable="@drawable/ic_launcher_foreground" />
|
||||
</adaptive-icon>
|
||||
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="app_name">ultra Home</string>
|
||||
<string name="recents_service_label">ultra Home window list</string>
|
||||
<string name="recents_service_summary">Lets the home screen\'s Windows button open Recents</string>
|
||||
<string name="recents_service_description">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.</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<!-- The wallpaper shows through the transparent window and Qt's surface. -->
|
||||
<style name="Home" parent="@android:style/Theme.DeviceDefault.Wallpaper.NoTitleBar">
|
||||
<item name="android:windowShowWallpaper">true</item>
|
||||
<item name="android:windowBackground">@android:color/transparent</item>
|
||||
<item name="android:windowIsTranslucent">false</item>
|
||||
<item name="android:statusBarColor">@android:color/transparent</item>
|
||||
<item name="android:navigationBarColor">@android:color/transparent</item>
|
||||
<item name="android:windowLayoutInDisplayCutoutMode">shortEdges</item>
|
||||
</style>
|
||||
</resources>
|
||||
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Only performGlobalAction(RECENTS): no events, no window content. -->
|
||||
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:description="@string/recents_service_description"
|
||||
android:summary="@string/recents_service_summary"
|
||||
android:accessibilityFeedbackType="feedbackGeneric"
|
||||
android:accessibilityFlags="flagDefault"
|
||||
android:canRetrieveWindowContent="false"
|
||||
android:notificationTimeout="0" />
|
||||
@@ -0,0 +1,898 @@
|
||||
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.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.file.Files;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
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 WebView build's host id: its widgets are bound to it, so they carry over.
|
||||
static final int HOST_ID = 0x0171;
|
||||
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<String, LauncherActivityInfo> activities = new ConcurrentHashMap<>();
|
||||
private AppWidgetManager widgets;
|
||||
private AppWidgetHost widgetHost;
|
||||
private CoverLayer widgetLayer;
|
||||
private final Map<Integer, AppWidgetHostView> widgetViews = new HashMap<>();
|
||||
private final Map<Integer, Long> 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(pkg); }
|
||||
@Override public void onPackageAdded(String pkg, UserHandle u) { appsChanged(pkg); }
|
||||
@Override public void onPackageChanged(String pkg, UserHandle u) { appsChanged(pkg); }
|
||||
@Override public void onPackagesAvailable(String[] pkgs, UserHandle u, boolean replacing) { appsChanged(String.join(",", pkgs)); }
|
||||
@Override public void onPackagesUnavailable(String[] pkgs, UserHandle u, boolean replacing) { appsChanged(String.join(",", pkgs)); }
|
||||
};
|
||||
|
||||
@Override
|
||||
public 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);
|
||||
a.readLegacyHome();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The WebView build kept its home screen in its page's localStorage, which lives on in
|
||||
* this app's data dir. Read it once, through a throwaway WebView on the same origin,
|
||||
* and hand the ultra.home.* keys to QML, which merges them into the Qt home.
|
||||
*/
|
||||
private void readLegacyHome() {
|
||||
final android.content.SharedPreferences prefs = getSharedPreferences("qt", MODE_PRIVATE);
|
||||
if (prefs.getBoolean("legacyRead", false)) return;
|
||||
final android.webkit.WebView w;
|
||||
try {
|
||||
w = new android.webkit.WebView(this);
|
||||
} catch (RuntimeException e) {
|
||||
Log.w("ultra", "no WebView to read the old home from", e);
|
||||
return;
|
||||
}
|
||||
w.getSettings().setJavaScriptEnabled(true);
|
||||
w.getSettings().setDomStorageEnabled(true);
|
||||
final boolean[] done = {false};
|
||||
w.setWebViewClient(new android.webkit.WebViewClient() {
|
||||
@Override
|
||||
public android.webkit.WebResourceResponse shouldInterceptRequest(
|
||||
android.webkit.WebView v, android.webkit.WebResourceRequest r) {
|
||||
return new android.webkit.WebResourceResponse("text/html", "utf-8",
|
||||
new java.io.ByteArrayInputStream("<!doctype html><title>.</title>".getBytes()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPageFinished(android.webkit.WebView v, String url) {
|
||||
if (done[0]) return;
|
||||
done[0] = true;
|
||||
v.evaluateJavascript(LEGACY_JS, value -> {
|
||||
String json = null;
|
||||
try {
|
||||
json = new JSONArray("[" + value + "]").optString(0, null);
|
||||
} catch (JSONException e) {
|
||||
Log.w("ultra", "old home unreadable: " + value);
|
||||
}
|
||||
prefs.edit().putBoolean("legacyRead", true).apply();
|
||||
if (json != null && json.startsWith("{")) Native.legacyHome(json);
|
||||
v.destroy();
|
||||
});
|
||||
}
|
||||
});
|
||||
w.loadUrl("https://appassets.androidplatform.net/index.html");
|
||||
}
|
||||
|
||||
private static final String LEGACY_JS =
|
||||
"(function(){var o={};for(var i=0;i<localStorage.length;i++){var k=localStorage.key(i);"
|
||||
+ "if(k.indexOf('ultra.home.')===0)o[k]=localStorage.getItem(k);}return JSON.stringify(o);})()";
|
||||
|
||||
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
|
||||
public void onStart() {
|
||||
super.onStart();
|
||||
Log.i("ultra", "onStart");
|
||||
widgetHost.startListening();
|
||||
Updater.check(this, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStop() {
|
||||
super.onStop();
|
||||
Log.i("ultra", "onStop");
|
||||
widgetHost.stopListening();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDestroy() {
|
||||
launcher.unregisterCallback(packages);
|
||||
if (self == this) self = null;
|
||||
super.onDestroy();
|
||||
}
|
||||
|
||||
// The home button while we are already in front.
|
||||
@Override
|
||||
public 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();
|
||||
}
|
||||
|
||||
/** packages: the ones that changed, comma-separated, so only their icons are redrawn. */
|
||||
private void appsChanged(String packages) {
|
||||
if (packages != null && !packages.isEmpty()) {
|
||||
for (String pkg : packages.split(",")) {
|
||||
if (pkg.isEmpty()) continue;
|
||||
String prefix = pkg + "/";
|
||||
activities.keySet().removeIf(k -> k.startsWith(prefix));
|
||||
}
|
||||
}
|
||||
if (qtReady) Native.appsChanged(packages == null ? "" : packages);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ called from Qt
|
||||
|
||||
/** {"apps": [{"label", "component", "system"}]}, every launchable activity, by label. */
|
||||
private static final ExecutorService lister = Executors.newSingleThreadExecutor();
|
||||
|
||||
/** apps(), worked out off Qt's thread (it takes a while), then handed to Native.appList. */
|
||||
static void listApps() {
|
||||
lister.execute(() -> Native.appList(apps()));
|
||||
}
|
||||
|
||||
static String apps() {
|
||||
HomeActivity a = self;
|
||||
if (a == null) return "{\"apps\":[]}";
|
||||
try {
|
||||
List<LauncherActivityInfo> list = new ArrayList<>(a.launcher.getActivityList(null, a.user));
|
||||
Map<LauncherActivityInfo, String> 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();
|
||||
java.util.Set<String> seen = new java.util.HashSet<>();
|
||||
for (LauncherActivityInfo i : list) {
|
||||
ComponentName cn = i.getComponentName();
|
||||
if (cn.getPackageName().equals(a.getPackageName())) continue;
|
||||
String c = cn.flattenToShortString();
|
||||
seen.add(c);
|
||||
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);
|
||||
}
|
||||
a.activities.keySet().retainAll(seen);
|
||||
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<AppWidgetProviderInfo> list = new ArrayList<>(a.widgets.getInstalledProvidersForProfile(a.user));
|
||||
Map<AppWidgetProviderInfo, String> 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 premultiplied RGBA pixels, size px square: key "a:COMPONENT" (an app) or
|
||||
* "w:PROVIDER" (a widget). Drawn icons are kept on disk, keyed by the app's last update,
|
||||
* so a fresh start reads them back instead of drawing every one again.
|
||||
*/
|
||||
static byte[] icon(String key, int size) {
|
||||
HomeActivity a = self;
|
||||
if (a == null || key == null || key.length() < 3) return null;
|
||||
size = Math.max(16, Math.min(size, 512));
|
||||
File f = a.iconFile(key, size);
|
||||
if (f != null && f.length() == (long) size * size * 4) {
|
||||
try {
|
||||
return Files.readAllBytes(f.toPath());
|
||||
} catch (java.io.IOException e) {
|
||||
f.delete();
|
||||
}
|
||||
}
|
||||
byte[] px;
|
||||
synchronized (iconLock) {
|
||||
try {
|
||||
Drawable d = key.startsWith("w:") ? a.widgetIcon(key.substring(2)) : a.appIcon(key.substring(2));
|
||||
px = d == null ? null : toPixels(d, size);
|
||||
} catch (RuntimeException | OutOfMemoryError e) {
|
||||
Log.w("ultra", "icon for " + key, e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (px != null && f != null) {
|
||||
File tmp = new File(f.getPath() + ".tmp");
|
||||
try (FileOutputStream out = new FileOutputStream(tmp)) {
|
||||
out.write(px);
|
||||
} catch (java.io.IOException e) {
|
||||
tmp.delete();
|
||||
tmp = null;
|
||||
}
|
||||
if (tmp != null && !tmp.renameTo(f)) tmp.delete();
|
||||
}
|
||||
return px;
|
||||
}
|
||||
|
||||
private File iconFile(String key, int size) {
|
||||
try {
|
||||
String pkg = key.substring(2).split("/", 2)[0];
|
||||
long stamp = getPackageManager().getPackageInfo(pkg, 0).lastUpdateTime;
|
||||
String id = "v2|" + key + "|" + size + "|" + stamp + "|" + getResources().getDisplayMetrics().densityDpi;
|
||||
byte[] h = MessageDigest.getInstance("SHA-1").digest(id.getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
StringBuilder name = new StringBuilder();
|
||||
for (byte b : h) name.append(String.format("%02x", b));
|
||||
File dir = new File(getCacheDir(), "icons");
|
||||
if (!dir.isDirectory() && !dir.mkdirs()) return null;
|
||||
return new File(dir, name.toString());
|
||||
} catch (Exception 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;
|
||||
}
|
||||
|
||||
// ARGB_8888 bitmaps hold premultiplied RGBA bytes: Qt takes them as they are, with no
|
||||
// PNG to encode here and decode there.
|
||||
private static byte[] toPixels(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));
|
||||
ByteBuffer buf = ByteBuffer.allocate(size * size * 4);
|
||||
bmp.copyPixelsToBuffer(buf);
|
||||
bmp.recycle();
|
||||
return buf.array();
|
||||
}
|
||||
|
||||
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<HomeActivity> 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
|
||||
public 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<Rect> 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]));
|
||||
});
|
||||
}
|
||||
|
||||
/** A sheet covers the screen from y (screen px) down, and dims the rest; y 0: no sheet. */
|
||||
static void sheetWidgets(int y, boolean dim) {
|
||||
onMain(a -> {
|
||||
if (a.widgetLayer == null) return;
|
||||
if (y <= 0) { a.widgetLayer.sheet(0, dim); return; }
|
||||
a.widgetLayer.getLocationOnScreen(a.layerAt);
|
||||
a.widgetLayer.sheet(Math.max(1, y - a.layerAt[1]), dim);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<Integer, int[]> 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<Integer, AppWidgetHostView> e : widgetViews.entrySet()) {
|
||||
if (!want.containsKey(e.getKey())) e.getValue().setVisibility(View.GONE);
|
||||
}
|
||||
for (Map.Entry<Integer, int[]> 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<SizeF> 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. Qt can't draw over them, so the layer clips them itself:
|
||||
* the app drawer slides down over the home screen, so cover(top) hides them above
|
||||
* its edge (-1 all of them, 0 none); a sheet rises from the bottom, so sheet(bottom,
|
||||
* dim) hides them below its top edge (0: no sheet) and dims the rest like the
|
||||
* sheet's backdrop, which then takes their touches (a tap closes the sheet). Touches
|
||||
* that land on no widget fall through to Qt underneath.
|
||||
*/
|
||||
static final class CoverLayer extends FrameLayout {
|
||||
private int top, bottom;
|
||||
private boolean dim;
|
||||
|
||||
CoverLayer(Context c) { super(c); }
|
||||
|
||||
void cover(int y) {
|
||||
if (y == top) return;
|
||||
top = y;
|
||||
apply();
|
||||
}
|
||||
|
||||
void sheet(int y, boolean dimmed) {
|
||||
if (y == bottom && dimmed == dim) return;
|
||||
bottom = y;
|
||||
dim = dimmed;
|
||||
apply();
|
||||
}
|
||||
|
||||
private void apply() {
|
||||
setVisibility(top < 0 ? View.INVISIBLE : View.VISIBLE);
|
||||
setAlpha(dim ? .55f : 1f);
|
||||
if (top <= 0 && bottom <= 0) {
|
||||
setClipBounds(null);
|
||||
} else {
|
||||
int t = Math.max(top, 0), b = bottom > 0 ? bottom : Math.max(getHeight(), t + 1);
|
||||
setClipBounds(new Rect(0, t, Math.max(getWidth(), 1), Math.max(b, t + 1)));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean dispatchTouchEvent(MotionEvent ev) {
|
||||
if (ev.getActionMasked() == MotionEvent.ACTION_DOWN
|
||||
&& (dim || top < 0 || (top > 0 && ev.getY() < top) || (bottom > 0 && ev.getY() >= bottom))) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
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(String packages); // comma-separated
|
||||
static native void appList(String json); // HomeActivity.listApps' answer
|
||||
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);
|
||||
static native void legacyHome(String json); // the WebView build's ultra.home.* keys
|
||||
}
|
||||
@@ -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() { }
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
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.JSONArray;
|
||||
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 newest release on the Gitea forge (experiments/launcher
|
||||
* on git.site.latha.org), which .gitea/workflows/launcher.yml builds on every commit to
|
||||
* main. Each release holds version.json ({"versionCode": N, "commit": SHA}) next to
|
||||
* ultra-launcher.apk, with N the APK's versionCode; the latest-release API names their
|
||||
* download URLs. 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 LATEST =
|
||||
"https://git.site.latha.org/api/v1/repos/experiments/launcher/releases/latest";
|
||||
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 release = new JSONObject(new String(get(LATEST), StandardCharsets.UTF_8));
|
||||
String versionUrl = assetUrl(release, "version.json");
|
||||
String apkUrl = assetUrl(release, "ultra-launcher.apk");
|
||||
JSONObject v = new JSONObject(new String(get(versionUrl), 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, apkUrl, latest);
|
||||
}
|
||||
|
||||
/** The download URL of the named asset in a release's JSON. */
|
||||
private static String assetUrl(JSONObject release, String name) throws Exception {
|
||||
JSONArray assets = release.getJSONArray("assets");
|
||||
for (int i = 0; i < assets.length(); i++) {
|
||||
JSONObject a = assets.getJSONObject(i);
|
||||
if (name.equals(a.getString("name"))) return a.getString("browser_download_url");
|
||||
}
|
||||
throw new IOException("no " + name + " asset in the latest release");
|
||||
}
|
||||
|
||||
@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, String apkUrl, 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(apkUrl);
|
||||
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); // asset downloads redirect to their storage 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
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)
|
||||
onStatusChanged: if (status === Image.Ready || status === Image.Error) console.info("ultra.icon shown", root.key, status === Image.Ready)
|
||||
source: root.key ? "image://icon/" + encodeURIComponent(root.key) + "?" + root.generation : ""
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
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 bool warm: true // false: hold off making icons until it opens
|
||||
property var iconGen: ({}) // package -> n, see Main.gen
|
||||
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.shown.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.shown.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.warm || root.visible ? 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.iconGen[(cell.app.component || "").split("/")[0]] || 0
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
.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;
|
||||
}
|
||||
|
||||
// The WebView build's saved home (its ultra.home.* localStorage keys) as Qt slots.
|
||||
// Widget heights were px; they become whole rows.
|
||||
function legacy(kv) {
|
||||
var out = [];
|
||||
var n = parseInt(kv["ultra.home.n"], 10) || 0;
|
||||
var num = function (k, i, d) {
|
||||
var v = parseInt(kv["ultra.home." + k + "." + i], 10);
|
||||
return isNaN(v) ? d : v;
|
||||
};
|
||||
for (var i = 0; i < n; i++) {
|
||||
var str = kv["ultra.home.str." + i];
|
||||
if (typeof str !== "string" || !str) continue;
|
||||
var x = num("cx", i, -1), y = num("cy", i, -1);
|
||||
if (num("kind", i, 0) === 1)
|
||||
out.push({kind: "widget", str: str, wid: num("wid", i, 0), w: Math.max(0, num("w", i, 0)),
|
||||
rows: widgetRows(num("h", i, 120)), x: x, y: y});
|
||||
else
|
||||
out.push({kind: "app", str: str, x: x, y: y});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import QtQuick
|
||||
|
||||
// A rounded search box. Enter is "accepted"; the text is "text", and "shown" is what
|
||||
// the box shows, including a word the keyboard is still composing (Android keyboards
|
||||
// keep it out of "text" until it is committed).
|
||||
Rectangle {
|
||||
id: root
|
||||
property alias text: input.text
|
||||
property alias placeholder: hint.text
|
||||
property alias input: input
|
||||
readonly property string shown: input.displayText
|
||||
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() }
|
||||
// Empty the box, including a word still being composed, and keep typing in it.
|
||||
// Android commits a composing word asynchronously, so it can land after the clear:
|
||||
// clear again once it has.
|
||||
function clearText() {
|
||||
Qt.inputMethod.commit();
|
||||
input.clear();
|
||||
input.forceActiveFocus();
|
||||
clearAgain.restart();
|
||||
}
|
||||
Timer { id: clearAgain; interval: 120; onTriggered: input.clear() }
|
||||
|
||||
TextInput {
|
||||
id: input
|
||||
anchors.left: parent.left
|
||||
anchors.right: clear.left
|
||||
anchors.leftMargin: 20
|
||||
anchors.rightMargin: 0
|
||||
anchors.verticalCenter: parent.verticalCenter
|
||||
color: "white"
|
||||
selectionColor: Qt.rgba(1, 1, 1, .35)
|
||||
font.pixelSize: root.fontSize
|
||||
clip: true
|
||||
// No suggestions: Android keyboards then type straight into the box rather than
|
||||
// composing words, so the list filters on every key.
|
||||
inputMethodHints: Qt.ImhNoPredictiveText | Qt.ImhSensitiveData | 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.displayText.length === 0
|
||||
}
|
||||
}
|
||||
// The clear button: a finger-sized target at the right end of the box.
|
||||
Item {
|
||||
id: clear
|
||||
objectName: "searchClear"
|
||||
anchors.right: parent.right
|
||||
anchors.top: parent.top
|
||||
anchors.bottom: parent.bottom
|
||||
width: visible ? 44 : 0
|
||||
visible: input.displayText.length > 0
|
||||
z: 1
|
||||
// Drawn, not a glyph: phone fonts may have no ✕.
|
||||
Repeater {
|
||||
model: [45, -45]
|
||||
Rectangle {
|
||||
required property var modelData
|
||||
anchors.centerIn: parent
|
||||
width: 14
|
||||
height: 2
|
||||
radius: 1
|
||||
rotation: modelData
|
||||
antialiasing: true
|
||||
color: Qt.rgba(1, 1, 1, .7)
|
||||
}
|
||||
}
|
||||
MouseArea {
|
||||
anchors.fill: parent
|
||||
preventStealing: true
|
||||
onPressed: (m) => m.accepted = true
|
||||
onClicked: { root.clearText(); root.escaped() }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
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
|
||||
// Where the panel's top edge is, for hiding native widgets under it.
|
||||
readonly property real edge: panel.y
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
#include "backend.h"
|
||||
|
||||
#include <QFile>
|
||||
#include <QGuiApplication>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QScreen>
|
||||
#include <QSettings>
|
||||
#include <QTimer>
|
||||
#include <cmath>
|
||||
|
||||
#ifdef Q_OS_ANDROID
|
||||
#include <QJniEnvironment>
|
||||
#include <QJniObject>
|
||||
#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<void>(kActivity, method, "(Ljava/lang/String;)V",
|
||||
QJniObject::fromString(s).object<jstring>());
|
||||
}
|
||||
|
||||
void callVoid(const char *method) {
|
||||
QJniObject::callStaticMethod<void>(kActivity, method, "()V");
|
||||
}
|
||||
|
||||
// Called by HomeActivity on Android's main thread: hop over to Qt's.
|
||||
template <typename F>
|
||||
void post(F f) {
|
||||
if (g_backend) QMetaObject::invokeMethod(g_backend, f, Qt::QueuedConnection);
|
||||
}
|
||||
|
||||
void jAppsChanged(JNIEnv *env, jclass, jstring packages) {
|
||||
const char *c = env->GetStringUTFChars(packages, nullptr);
|
||||
const QString s = QString::fromUtf8(c);
|
||||
env->ReleaseStringUTFChars(packages, c);
|
||||
post([=] { emit g_backend->appsChanged(s); });
|
||||
}
|
||||
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 jLegacyHome(JNIEnv *env, jclass, jstring json) {
|
||||
const char *c = env->GetStringUTFChars(json, nullptr);
|
||||
const QString s = QString::fromUtf8(c);
|
||||
env->ReleaseStringUTFChars(json, c);
|
||||
post([=] { emit g_backend->legacyHome(s); });
|
||||
}
|
||||
|
||||
void jAppList(JNIEnv *env, jclass, jstring json) {
|
||||
const char *c = env->GetStringUTFChars(json, nullptr);
|
||||
const QByteArray s(c);
|
||||
env->ReleaseStringUTFChars(json, c);
|
||||
post([=] { g_backend->takeAppList(s); });
|
||||
}
|
||||
|
||||
void registerNatives() {
|
||||
static bool done = false;
|
||||
if (done) return;
|
||||
done = true;
|
||||
const JNINativeMethod methods[] = {
|
||||
{"appsChanged", "(Ljava/lang/String;)V", reinterpret_cast<void *>(jAppsChanged)},
|
||||
{"homePressed", "()V", reinterpret_cast<void *>(jHomePressed)},
|
||||
{"backPressed", "()V", reinterpret_cast<void *>(jBackPressed)},
|
||||
{"insets", "(II)V", reinterpret_cast<void *>(jInsets)},
|
||||
{"widgetAdded", "(I)V", reinterpret_cast<void *>(jWidgetAdded)},
|
||||
{"widgetMenu", "(I)V", reinterpret_cast<void *>(jWidgetMenu)},
|
||||
{"widgetGrab", "(I)V", reinterpret_cast<void *>(jWidgetGrab)},
|
||||
{"widgetDrag", "(II)V", reinterpret_cast<void *>(jWidgetDrag)},
|
||||
{"widgetDrop", "(Z)V", reinterpret_cast<void *>(jWidgetDrop)},
|
||||
{"appList", "(Ljava/lang/String;)V", reinterpret_cast<void *>(jAppList)},
|
||||
{"legacyHome", "(Ljava/lang/String;)V", reinterpret_cast<void *>(jLegacyHome)},
|
||||
};
|
||||
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
|
||||
}
|
||||
|
||||
static QVariantList appList(const QJsonDocument &doc) {
|
||||
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;
|
||||
}
|
||||
|
||||
// The app list, and a copy kept for the next start: listing (and labelling) every app
|
||||
// takes a while on a phone, so the home screen starts from the copy meanwhile.
|
||||
QVariantList Backend::apps() const {
|
||||
#ifdef Q_OS_ANDROID
|
||||
const QByteArray json = callString("apps").toUtf8();
|
||||
#else
|
||||
const QByteArray json = demo(QStringLiteral("apps.json")).toJson(QJsonDocument::Compact);
|
||||
#endif
|
||||
const QVariantList out = appList(QJsonDocument::fromJson(json));
|
||||
if (!out.isEmpty()) QSettings().setValue(QStringLiteral("apps"), QString::fromUtf8(json));
|
||||
return out;
|
||||
}
|
||||
|
||||
// apps(), without holding up the UI thread meanwhile: the list arrives as appsLoaded.
|
||||
void Backend::requestApps() {
|
||||
#ifdef Q_OS_ANDROID
|
||||
callVoid("listApps");
|
||||
#else
|
||||
QTimer::singleShot(0, this, [this] { takeAppList(demo(QStringLiteral("apps.json")).toJson(QJsonDocument::Compact)); });
|
||||
#endif
|
||||
}
|
||||
|
||||
void Backend::takeAppList(const QByteArray &json) {
|
||||
const QVariantList out = appList(QJsonDocument::fromJson(json));
|
||||
if (!out.isEmpty()) QSettings().setValue(QStringLiteral("apps"), QString::fromUtf8(json));
|
||||
emit appsLoaded(out);
|
||||
}
|
||||
|
||||
QVariantList Backend::savedApps() const {
|
||||
return appList(QJsonDocument::fromJson(QSettings().value(QStringLiteral("apps")).toString().toUtf8()));
|
||||
}
|
||||
|
||||
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<void>(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<void>(kActivity, "coverWidgets", "(I)V", jint(py));
|
||||
#else
|
||||
Q_UNUSED(y);
|
||||
#endif
|
||||
}
|
||||
|
||||
void Backend::sheetWidgets(qreal y, bool dim) {
|
||||
#ifdef Q_OS_ANDROID
|
||||
const int py = y <= 0 ? 0 : int(std::floor(y * dpr()));
|
||||
QJniObject::callStaticMethod<void>(kActivity, "sheetWidgets", "(IZ)V", jint(py), jboolean(dim));
|
||||
#else
|
||||
Q_UNUSED(y);
|
||||
Q_UNUSED(dim);
|
||||
#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);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
#pragma once
|
||||
|
||||
#include <QObject>
|
||||
#include <QString>
|
||||
#include <QVariantList>
|
||||
#include <QVariantMap>
|
||||
#include <QtQml/qqmlregistration.h>
|
||||
|
||||
// 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 void requestApps(); // answers with appsLoaded
|
||||
Q_INVOKABLE QVariantList savedApps() const; // the last list apps() returned, for a quick start
|
||||
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);
|
||||
// A sheet covers the screen from global logical y down (0: none) and dims the rest.
|
||||
Q_INVOKABLE void sheetWidgets(qreal y, bool dim);
|
||||
// {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 appsLoaded(const QVariantList &apps);
|
||||
void appsChanged(const QString &packages); // comma-separated; empty: any
|
||||
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 legacyHome(const QString &json); // the WebView build's saved home, read once
|
||||
void toast(const QString &text); // desktop stand-in for an action
|
||||
|
||||
public:
|
||||
void takeAppList(const QByteArray &json); // HomeActivity's answer to requestApps
|
||||
|
||||
private:
|
||||
qreal dpr() const;
|
||||
qreal m_insetTop = 0, m_insetBottom = 0;
|
||||
mutable int m_demoWidget = 100;
|
||||
};
|
||||
@@ -0,0 +1,67 @@
|
||||
#include "iconprovider.h"
|
||||
|
||||
#include <QColor>
|
||||
#include <QPainter>
|
||||
#include <QUrl>
|
||||
#include <QElapsedTimer>
|
||||
#include <QLoggingCategory>
|
||||
#include <QThread>
|
||||
|
||||
Q_LOGGING_CATEGORY(lcIcon, "ultra.icon")
|
||||
|
||||
#include <cmath>
|
||||
|
||||
#ifdef Q_OS_ANDROID
|
||||
#include <QJniEnvironment>
|
||||
#include <QJniObject>
|
||||
#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;
|
||||
QElapsedTimer took;
|
||||
took.start();
|
||||
QImage img;
|
||||
#ifdef Q_OS_ANDROID
|
||||
// Premultiplied RGBA, side x side, straight from an Android bitmap.
|
||||
QJniObject pixels = QJniObject::callStaticObjectMethod(
|
||||
"dev/ultra/launcher/HomeActivity", "icon", "(Ljava/lang/String;I)[B",
|
||||
QJniObject::fromString(key).object<jstring>(), jint(px));
|
||||
if (pixels.isValid()) {
|
||||
QJniEnvironment env;
|
||||
auto arr = pixels.object<jbyteArray>();
|
||||
const jsize n = env->GetArrayLength(arr);
|
||||
const int side = int(std::lround(std::sqrt(n / 4.0)));
|
||||
if (side > 0 && jsize(side) * side * 4 == n) {
|
||||
img = QImage(side, side, QImage::Format_RGBA8888_Premultiplied);
|
||||
env->GetByteArrayRegion(arr, 0, n, reinterpret_cast<jbyte *>(img.bits()));
|
||||
}
|
||||
}
|
||||
#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();
|
||||
// Timing, to find what holds icons up on a phone: adb logcat -s ultrahome:*
|
||||
qCInfo(lcIcon, "icon %s %dpx %lldms%s", qPrintable(key), px, took.elapsed(), img.isNull() ? " (none)" : "");
|
||||
return img;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
#pragma once
|
||||
|
||||
#include <QQuickImageProvider>
|
||||
|
||||
// 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;
|
||||
};
|
||||
@@ -0,0 +1,44 @@
|
||||
#include <QGuiApplication>
|
||||
#include <QQmlApplicationEngine>
|
||||
#include <QtQml/qqmlextensionplugin.h>
|
||||
#include <QQuickWindow>
|
||||
#include <QSurfaceFormat>
|
||||
|
||||
#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;
|
||||
// Timing of the window's lifecycle, next to the icon timings (category ultra.icon).
|
||||
QObject::connect(&app, &QGuiApplication::applicationStateChanged, [](Qt::ApplicationState s) {
|
||||
qInfo("ultra.state %d", int(s));
|
||||
});
|
||||
if (auto *win = qobject_cast<QQuickWindow *>(engine.rootObjects().first())) {
|
||||
QObject::connect(win, &QQuickWindow::sceneGraphInitialized, [] { qInfo("ultra.sg initialized"); });
|
||||
QObject::connect(win, &QQuickWindow::sceneGraphInvalidated, [] { qInfo("ultra.sg invalidated"); });
|
||||
QObject::connect(win, &QQuickWindow::frameSwapped, win, [win] {
|
||||
static int n = 0;
|
||||
if (n++ < 3) qInfo("ultra.sg frame %d", n);
|
||||
});
|
||||
}
|
||||
return app.exec();
|
||||
}
|
||||
@@ -0,0 +1,390 @@
|
||||
// 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 <QGuiApplication>
|
||||
#include <QQmlApplicationEngine>
|
||||
#include <QtQml/qqmlextensionplugin.h>
|
||||
#include <QQmlContext>
|
||||
#include <QQmlExpression>
|
||||
#include <QQuickItem>
|
||||
#include <QQuickWindow>
|
||||
#include <QSettings>
|
||||
#include <QStandardPaths>
|
||||
#include <QTest>
|
||||
|
||||
#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<QJSValue>()) v = v.value<QJSValue>().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<QQuickItem *>(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<QQuickItem *>();
|
||||
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<QQuickItem *>();
|
||||
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<QQuickWindow *>(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<QQuickItem *>("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");
|
||||
{
|
||||
// the clear button empties the search and shows every app again
|
||||
settle(100);
|
||||
snap("search");
|
||||
auto *clear = win->findChild<QQuickItem *>("searchClear");
|
||||
check(clear && clear->isVisible(), "the search shows a clear button");
|
||||
if (clear) tap(clear->mapToScene(QPointF(clear->width() / 2, clear->height() / 2)));
|
||||
eq(js("drawer.query"), "", "tapping it clears the search");
|
||||
eq(js("drawer.shown.length === apps.length"), true, "and every app shows again");
|
||||
check(clear && !clear->isVisible(), "the clear button goes");
|
||||
js("drawer.query = 'ma'");
|
||||
}
|
||||
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<QQuickItem *>("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");
|
||||
|
||||
// the search pill on the front page opens the drawer (its search focuses there)
|
||||
tap(itemCenter("homeSearch"));
|
||||
check(js("drawerOpen").toBool(), "tapping the home search opens the drawer");
|
||||
snap("home-search");
|
||||
js("closeDrawer()");
|
||||
settle(300);
|
||||
check(!js("drawerOpen").toBool(), "and it closes again");
|
||||
|
||||
// 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<QQuickItem *>("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");
|
||||
|
||||
// Starting again: the saved app list names the home tiles before the real list loads,
|
||||
// and nothing is hidden meanwhile.
|
||||
js("apps = []; appRow = ({}); loading = true; setApps(Host.savedApps())");
|
||||
eq(homeLabels(), "Gmail,Chrome,Phone", "home tiles come from the saved app list");
|
||||
js("apps = []; appRow = ({})");
|
||||
eq(js("hidden.some(h => h)"), false, "nothing is hidden before the list loads");
|
||||
js("loadApps()");
|
||||
// A changed package reloads only its own icons.
|
||||
emit backend.appsChanged(QStringLiteral("com.example.chrome"));
|
||||
settle(50);
|
||||
eq(js("gen('com.example.chrome/.MainActivity') + ',' + gen('com.example.gmail/.MainActivity')"), "1,0",
|
||||
"a changed app's icons reload, the rest stay");
|
||||
|
||||
// The WebView build's saved home merges in: new slots go after, unpinned.
|
||||
emit backend.legacyHome(QStringLiteral(
|
||||
"{\"ultra.home.n\":\"3\",\"ultra.home.str.0\":\"com.example.clock/.MainActivity\","
|
||||
"\"ultra.home.cx.0\":\"4\",\"ultra.home.cy.0\":\"4\",\"ultra.home.str.1\":\"com.example.chrome/.MainActivity\","
|
||||
"\"ultra.home.kind.2\":\"1\",\"ultra.home.str.2\":\"Weather\",\"ultra.home.wid.2\":\"7\",\"ultra.home.h.2\":\"200\"}"));
|
||||
settle(50);
|
||||
eq(homeLabels(), "Gmail,Chrome,Phone,Clock,[Weather]", "the old home is brought over");
|
||||
eq(js("home[3].x"), -1, "unpinned when merged");
|
||||
eq(js("home[4].rows"), 3, "widget px become rows");
|
||||
|
||||
// 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;
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
// 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, legacy};")();
|
||||
|
||||
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");
|
||||
|
||||
// The WebView build's saved home converts: apps by component, widgets with px heights to rows.
|
||||
assert.deepEqual(L.legacy({
|
||||
"ultra.home.n": "3",
|
||||
"ultra.home.kind.0": "0", "ultra.home.str.0": "com.a/.Main", "ultra.home.cx.0": "-1", "ultra.home.cy.0": "-1",
|
||||
"ultra.home.kind.1": "1", "ultra.home.str.1": "Clock", "ultra.home.wid.1": "12", "ultra.home.h.1": "136",
|
||||
"ultra.home.w.1": "3", "ultra.home.cx.1": "1", "ultra.home.cy.1": "2",
|
||||
"ultra.home.kind.2": "0",
|
||||
}), [
|
||||
{ kind: "app", str: "com.a/.Main", x: -1, y: -1 },
|
||||
{ kind: "widget", str: "Clock", wid: 12, w: 3, rows: 2, x: 1, y: 2 },
|
||||
]);
|
||||
assert.deepEqual(L.legacy({}), []);
|
||||
Reference in new issue
Block a user