mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-21 05:46:03 +00:00
Target Android SDK 37 for Play Store review
Integrate current main while preserving the original SDK migration history. Update the Android toolchain, runtime permissions, foreground service lifecycle, storage access, native execution and platform API compatibility. Complete translations and regression coverage. Validation: 3,260 JVM tests, 1,620 Python tests (eight skips), 171 Rust tests, six native regression programs and release lint with zero errors. Signed APK upgrade installed on the requested device. Signed app bundle validated with bundletool. Review candidate: physical before/after feature checks, performance parity and native 16 KiB audio compatibility remain pending. Play Console acceptance has not been verified.
This commit is contained in:
commit
b14587baeb
1553 files changed
+124616
-8790
No files matched your search
@@ -2,7 +2,27 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools">
|
||||
|
||||
<queries>
|
||||
<package android:name="com.xiaoji.egggame" />
|
||||
<intent>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent>
|
||||
<intent>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.HOME" />
|
||||
</intent>
|
||||
<intent>
|
||||
<action android:name="android.content.pm.action.CONFIRM_INSTALL" />
|
||||
</intent>
|
||||
<intent>
|
||||
<action android:name="android.content.pm.action.CONFIRM_PERMISSIONS" />
|
||||
</intent>
|
||||
</queries>
|
||||
|
||||
<uses-permission android:name="android.permission.REORDER_TASKS" />
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.ACCESS_LOCAL_NETWORK" />
|
||||
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
|
||||
@@ -12,6 +32,8 @@
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
|
||||
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
|
||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
|
||||
@@ -20,7 +42,10 @@
|
||||
<uses-permission android:name="android.permission.VIBRATE" />
|
||||
<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" />
|
||||
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
|
||||
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
|
||||
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
|
||||
<uses-permission android:name="android.permission.REQUEST_DELETE_PACKAGES" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
|
||||
<uses-permission android:name="android.permission.CAMERA" />
|
||||
@@ -37,19 +62,45 @@
|
||||
android:localeConfig="@xml/locales_config"
|
||||
android:networkSecurityConfig="@xml/network_security_config"
|
||||
android:allowBackup="false"
|
||||
android:allowAudioPlaybackCapture="true"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:theme="@style/AppTheme"
|
||||
android:hardwareAccelerated="true"
|
||||
android:largeHeap="true"
|
||||
android:extractNativeLibs="true"
|
||||
android:pageSizeCompat="enabled"
|
||||
android:requestLegacyExternalStorage="true"
|
||||
android:enableOnBackInvokedCallback="false"
|
||||
android:appCategory="game"
|
||||
android:isGame="true">
|
||||
|
||||
<meta-data android:name="android.game_mode_config" android:resource="@xml/game_mode_config" />
|
||||
<service android:name=".glasses.LumaRgbCaptureService" android:exported="false"
|
||||
android:process=":rgb_diagnostic" />
|
||||
<service android:name=".input.HomeButtonService"
|
||||
android:label="@string/integration_shortcuts_service"
|
||||
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE"
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.accessibilityservice.AccessibilityService" />
|
||||
</intent-filter>
|
||||
<meta-data android:name="android.accessibilityservice" android:resource="@xml/home_button_service" />
|
||||
</service>
|
||||
<service android:name=".session.BottomNotificationListener"
|
||||
android:label="@string/bottom_notifications_listener"
|
||||
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE"
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.service.notification.NotificationListenerService" />
|
||||
</intent-filter>
|
||||
</service>
|
||||
<receiver android:name=".core.ShortcutsListingReceiver" android:exported="false"
|
||||
android:process=":shortcuts_sync">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
<meta-data android:name="com.oculus.supportedDevices" android:value="quest2|quest3|quest3s" />
|
||||
<activity android:name=".QuestXrActivity" android:exported="true" android:launchMode="singleTask"
|
||||
android:permission="android.permission.DUMP"
|
||||
@@ -64,11 +115,23 @@
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".PairingGuideActivity"
|
||||
android:exported="false"
|
||||
android:launchMode="singleTask"
|
||||
android:taskAffinity="${applicationId}.pairingguide"
|
||||
android:excludeFromRecents="true"
|
||||
android:supportsPictureInPicture="true"
|
||||
android:resizeableActivity="true"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density|keyboard|keyboardHidden|navigation"
|
||||
android:theme="@style/AppTheme" />
|
||||
|
||||
<activity
|
||||
android:name=".FrontEndActivity"
|
||||
android:exported="true"
|
||||
android:screenOrientation="sensorLandscape"
|
||||
android:screenOrientation="user"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density|keyboard|keyboardHidden|navigation">
|
||||
<layout android:defaultWidth="1024dp" android:defaultHeight="640dp" />
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.VIEW" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
@@ -119,7 +182,7 @@
|
||||
android:excludeFromRecents="true"
|
||||
android:noHistory="true"
|
||||
android:taskAffinity="${applicationId}.home"
|
||||
android:screenOrientation="sensorLandscape"
|
||||
android:screenOrientation="user"
|
||||
android:theme="@android:style/Theme.Translucent.NoTitleBar">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
@@ -129,6 +192,18 @@
|
||||
</activity>
|
||||
|
||||
|
||||
<activity
|
||||
android:name=".PinRequestActivity"
|
||||
android:exported="true"
|
||||
android:excludeFromRecents="true"
|
||||
android:taskAffinity="${applicationId}.pin"
|
||||
android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen">
|
||||
<intent-filter>
|
||||
<action android:name="android.content.pm.action.CONFIRM_PIN_SHORTCUT" />
|
||||
<action android:name="android.content.pm.action.CONFIRM_PIN_APPWIDGET" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".input.ControllerEditorActivity"
|
||||
android:exported="false"
|
||||
@@ -138,16 +213,23 @@
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density" />
|
||||
|
||||
<activity
|
||||
android:name=".files.FileManagerActivity"
|
||||
android:name=".sync.SyncthingWebActivity"
|
||||
android:exported="false"
|
||||
android:screenOrientation="sensorLandscape"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
|
||||
android:theme="@style/AppTheme" />
|
||||
|
||||
<activity
|
||||
android:name=".files.FileManagerActivity"
|
||||
android:exported="false"
|
||||
android:screenOrientation="user"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
|
||||
android:theme="@style/AppTheme" />
|
||||
|
||||
<activity
|
||||
android:name=".files.FilePickerActivity"
|
||||
android:exported="false"
|
||||
android:screenOrientation="sensorLandscape"
|
||||
android:screenOrientation="user"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
|
||||
android:theme="@style/AppTheme" />
|
||||
|
||||
@@ -155,10 +237,31 @@
|
||||
android:process=":xboxlogin" android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
|
||||
android:theme="@style/AppTheme" />
|
||||
|
||||
<activity android:name=".stores.xbox.XboxCloudPlayerActivity" android:exported="false"
|
||||
android:screenOrientation="sensorLandscape" android:hardwareAccelerated="true"
|
||||
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize|density|navigation|uiMode"
|
||||
android:theme="@style/AppTheme" />
|
||||
|
||||
<service android:name=".stores.xbox.XboxCloudTokenService" android:exported="false" />
|
||||
|
||||
<activity android:name=".stores.xbox.XboxNativePlayerActivity" android:exported="false"
|
||||
android:process=":xcloudnative" android:screenOrientation="sensorLandscape" android:hardwareAccelerated="true"
|
||||
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize|density|navigation|uiMode"
|
||||
android:theme="@style/AppTheme" />
|
||||
|
||||
<activity android:name=".stores.xbox.XboxCloudActivity" android:exported="false"
|
||||
android:process=":xboxcloud" android:launchMode="singleTop" android:screenOrientation="sensorLandscape"
|
||||
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize|density|navigation|uiMode"
|
||||
android:theme="@style/AppTheme" />
|
||||
|
||||
<activity android:name=".stores.xbox.XboxCloudSettingsActivity" android:exported="false"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
|
||||
android:theme="@style/AppTheme" />
|
||||
|
||||
<activity
|
||||
android:name=".stores.StoreLoginActivity"
|
||||
android:exported="false"
|
||||
android:screenOrientation="sensorLandscape"
|
||||
android:screenOrientation="user"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
|
||||
android:theme="@style/AppTheme" />
|
||||
|
||||
@@ -181,6 +284,26 @@
|
||||
android:resizeableActivity="true"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density" />
|
||||
|
||||
<activity
|
||||
android:name=".ui.DualScreenActivity"
|
||||
android:exported="false"
|
||||
android:excludeFromRecents="true"
|
||||
android:taskAffinity="${applicationId}.dualscreen"
|
||||
android:theme="@style/SessionTheme"
|
||||
android:resizeableActivity="true"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density" />
|
||||
|
||||
<activity
|
||||
android:name=".ui.SessionTypingActivity"
|
||||
android:exported="false"
|
||||
android:excludeFromRecents="true"
|
||||
android:noHistory="true"
|
||||
android:taskAffinity="${applicationId}.typing"
|
||||
android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen"
|
||||
android:resizeableActivity="true"
|
||||
android:windowSoftInputMode="stateAlwaysHidden|adjustNothing"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density" />
|
||||
|
||||
<activity
|
||||
android:name=".gpu.SteamVrRestartActivity"
|
||||
android:exported="false"
|
||||
@@ -194,12 +317,17 @@
|
||||
<service
|
||||
android:name=".session.SessionService"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="specialUse"
|
||||
android:foregroundServiceType="specialUse|mediaPlayback|microphone"
|
||||
android:stopWithTask="false">
|
||||
<property
|
||||
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
|
||||
android:value="Runs the user's Linux game session (compositor, Steam client, audio) while the app is not on screen" />
|
||||
</service>
|
||||
<!-- The compositor's native state is one per process, so the bottom-screen desktop's compositor runs in its own. -->
|
||||
<service
|
||||
android:name=".wayland.BottomDesktopCompositorService"
|
||||
android:process=":bottom_desktop"
|
||||
android:exported="false" />
|
||||
<service
|
||||
android:name=".runtime.RuntimeInstallService"
|
||||
android:exported="false"
|
||||
@@ -216,6 +344,10 @@
|
||||
android:name=".stores.download.StoreDownloadService"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="dataSync" />
|
||||
<service
|
||||
android:name=".sync.SyncthingService"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="dataSync" />
|
||||
<provider
|
||||
android:name="androidx.core.content.FileProvider"
|
||||
android:authorities="${applicationId}.logs"
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -3,31 +3,52 @@
|
||||
"lxqt-r1": "c2bb860b3b1688287451e2495be5db313ec07f8c8af501dfac2768a9f417bc86",
|
||||
"desktop-kde-r1": "55747e75d0ec055ab7ea1e92a757f3be227cc3205bb9101f5b53cadef6318579",
|
||||
"desktop-kde-r2": "9ba832677b498654136c69d8c8330434d17e4d53cd099acac9bde3ba429b35bf",
|
||||
"emulators-r1": "a1f4806a9663d28f424b4cab1277e0ede80a92e69de5bc063cdc8b45af220164"
|
||||
"emulators-r1": "a1f4806a9663d28f424b4cab1277e0ede80a92e69de5bc063cdc8b45af220164",
|
||||
"desktop-kde-r3": "8b7142fcec8d86143ae39fc14ffc86907d30d9a5b5a45f49cb1b55109d6fc4eb"
|
||||
},
|
||||
"desktopApplications": {
|
||||
"ark-26.08.1-1-aarch64.pkg.tar.xz": "93e2c2b75ff20cd29b4f312ed1979ef6f27255b93232b93bfcdb31239903c1d4",
|
||||
"breeze-6.7.5-1-aarch64.pkg.tar.xz": "1d7f4eb9d8d234caaea23621909f5233d19462c2f058afeeb54bed7b81bd03bd",
|
||||
"breeze-gtk-6.7.5-1-any.pkg.tar.xz": "a0f59bc4fc426879c8f8a97f6dcc707fb7d1b52913da5eb7e9db83777b6957b7",
|
||||
"breeze-icons-6.30.0-1-aarch64.pkg.tar.xz": "4bae4689032501156687a227024e56554820747644953c67fc8d2e2b6b0b045a",
|
||||
"dolphin-26.08.1-1-aarch64.pkg.tar.xz": "fef738ab8132d3eba1156b98c116699ce0a5efcb4cb462efbacdcf4c47f79a23",
|
||||
"firefox-157.0.1-1-aarch64.pkg.tar.xz": "d142fdb8a339a65eca7cea6a2bba5b29202386166abd9d59851d6757c9eb2163",
|
||||
"gwenview-26.08.1-1-aarch64.pkg.tar.xz": "a9dc7d5ab73fa677905d5a57248b1b9b404b6b16e862958cc7443d387f684a47",
|
||||
"kate-26.08.1-1-aarch64.pkg.tar.xz": "acf50710042746f243a3b219a1ae0f788e338f3dd9d75093e8bb671a618b83b6",
|
||||
"kde-cli-tools-6.7.5-1-aarch64.pkg.tar.xz": "af466398a912a994a97fadfe46aff401d88a90d7fdce7e843dc4218098fa38ac",
|
||||
"kde-gtk-config-6.7.5-1-aarch64.pkg.tar.xz": "ba6cb4cb01dbb3f2c247f2f6973ede3b64c0849f89340217b51dfbf11cb8cb5c",
|
||||
"kinfocenter-6.7.5-1-aarch64.pkg.tar.xz": "f3d5416db96b50f9a5b8a284d82ae21d834a8cce646010abdd7087491c399b0b",
|
||||
"konsole-26.08.1-1-aarch64.pkg.tar.xz": "1ecf87c0d11d620ebe4aeafb02788e0d5f4fe9019ad9c5d9f1011c43237dd5ec",
|
||||
"kscreen-6.7.5-1-aarch64.pkg.tar.xz": "8fbaa6fedf93edeba021a5416b551663654919b27c2ee237d696ec0b0ce7d5b7",
|
||||
"kwin-6.7.5-1-aarch64.pkg.tar.xz": "a7535710c74b90359f80306134b2b7581132cbac508dc84b7e07ef275cc8c3fe",
|
||||
"7zip-26.05-1-aarch64.pkg.tar.xz": "17569bafbc5bd1a044ca1db164b96cb15857a22a3575f36679de46e693ae285e",
|
||||
"ark-26.08.2-1-aarch64.pkg.tar.xz": "b93cc90c4fc8a6cb0247fe8fb0f9de1c2074f5173fa2735d3d1959c9162c08f2",
|
||||
"breeze-6.8.1-1-aarch64.pkg.tar.xz": "70a2ff3afd41602f184814af5c6e298ff84ef7cb7e5880ca7cb4f6fb28521511",
|
||||
"breeze-gtk-6.8.1-1-any.pkg.tar.xz": "e92b9acf3155db22d4a288a43e8d95c20c72b8d8cffd028dd6800eb01a304bf0",
|
||||
"breeze-icons-6.31.0-1-aarch64.pkg.tar.xz": "b252ef02395621b5891d72c5f7fccd1a1ead1ce770886e9fced4bf21e1130096",
|
||||
"discover-6.8.1-1-aarch64.pkg.tar.xz": "64cfca615e7c18530c684325eb36a5c45e18c63b31f651335474f53b0178958c",
|
||||
"dolphin-26.08.2-1-aarch64.pkg.tar.xz": "4b5f7a9212c88d47146b374742f67f5620ab128ad893d945721bb43501066b70",
|
||||
"elisa-26.08.2-1-aarch64.pkg.tar.xz": "fd2df84a2905b59fba0ab1b7fadafe567c5a1dfd44d53ae4cd4996f683b83ba2",
|
||||
"filelight-26.08.2-1-aarch64.pkg.tar.xz": "17f39435104baf0743ab508bdde6e8bd1b3417b025b67ca8f343032d2fdef3e6",
|
||||
"firefox-158.0.1-1-aarch64.pkg.tar.xz": "4940e14c05522bfee8df901e1cfe81f56036c82e8f3d95f9f7a2a12e6b38d232",
|
||||
"flatpak-kcm-6.8.1-1-aarch64.pkg.tar.xz": "3145601002fb87d61307949a3011a8f27a7b1e9851fc59835460f934f8e00098",
|
||||
"git-2.56.0-1-aarch64.pkg.tar.xz": "b152a20edb215e98cada4b2dfbd02a9e925bda0b2de6ac1441e9e60b6698d3b5",
|
||||
"gwenview-26.08.2-1-aarch64.pkg.tar.xz": "02aae3973ec0563022c89e312ce7696d05d33514101ae2a01df3275717929de2",
|
||||
"htop-3.5.3-1-aarch64.pkg.tar.xz": "a58899bd2596d55575493509b3a5aa6f53075cb3d88bb6c712088c57068d9eb7",
|
||||
"kate-26.08.2-1-aarch64.pkg.tar.xz": "89c21ad8e62d20961b13f8fac8d9f4d358b1a3feebed243f6412e4ad996d5e9e",
|
||||
"kcalc-26.08.2-1-aarch64.pkg.tar.xz": "79b3303ccc5ae956e97313439456243e59f0b79a8166ca91606a25d1c9e41029",
|
||||
"kde-cli-tools-6.8.1-1-aarch64.pkg.tar.xz": "b052e9c25e7d6896be67846696f14c9e00430c0445f358ee64cf2a8ea16aa2eb",
|
||||
"kde-gtk-config-6.8.1-1-aarch64.pkg.tar.xz": "3095da034ac5fe8594165e3396f61f083b0c011cd96807146ddfb53690118608",
|
||||
"kfind-26.08.2-1-aarch64.pkg.tar.xz": "b4108cc3bd9efd62970379aadb3cb22e99dd1f54873ff432392edd0a833bb393",
|
||||
"kinfocenter-6.8.1-1-aarch64.pkg.tar.xz": "758882ef13a166205acab0e6bb96ce756d638d91e501db400cb579b9e1331d31",
|
||||
"konsole-26.08.2-1-aarch64.pkg.tar.xz": "0cf27f69d1792a094d4a935f578c82f8151b2d359198d9cd32bfdbd8dec544e4",
|
||||
"kscreen-6.8.1-1-aarch64.pkg.tar.xz": "72c948dfdebfef305623527de27274baf1a2328c87e71033fd852e386d9fdf5c",
|
||||
"kwin-6.8.1-2-aarch64.pkg.tar.xz": "726c98a3f8682b487c2b313633edbd80aa8b20ff657a6b63bbb1b73454f6e0c4",
|
||||
"less-1:710-1-aarch64.pkg.tar.xz": "8e1d4cbecf6d2ae734cfc1c5495367c0a9245f92dfd2bc03d4d0ab14f8b26ff2",
|
||||
"man-db-2.13.1-2-aarch64.pkg.tar.xz": "67515751f848717e1f6d3470f57ad2ea6900ee07618fd2726b6fcaa695687e80",
|
||||
"man-pages-6.19-1-any.pkg.tar.xz": "69df38f1a1aa35240d239ff82a2e067950ac394f23b8a6c7307580ccd7e95f07",
|
||||
"mpv-1:0.41.0-6-aarch64.pkg.tar.xz": "6c89d00736820210a3c7f32af4cf95d155191d463f9df8bd22137c45f30a554a",
|
||||
"plasma-desktop-6.7.5-1-aarch64.pkg.tar.xz": "b266dd42cea965b5ab1cc1ae600877e9d3bc83ec642c61fe1669c4457e641a55",
|
||||
"plasma-integration-6.7.5-1-aarch64.pkg.tar.xz": "daa96da14d9a4d12c0d9c0341e1be6836a9a437c469d61da5e9844d51e2606cf",
|
||||
"plasma-pa-6.7.5-1-aarch64.pkg.tar.xz": "02dbefe9d3e0069b2bb37cac2a6be18b8f0a1887c87704a0716e7a9268eadcd8",
|
||||
"plasma-workspace-6.7.5-1-aarch64.pkg.tar.xz": "3a1455857afaa9ccf342ab6167f0f15794ee9d248b0925398ea6f62f12730a86",
|
||||
"spectacle-1:6.7.5-1-aarch64.pkg.tar.xz": "0c9837412ea6119edef18bcb0a8fceb74634cb35be0ca78b3e1dd1ff2443866e",
|
||||
"systemsettings-6.7.5-1-aarch64.pkg.tar.xz": "b02b6a726857d5125c92d1ec95379216c7a3bc1f187a3b46e88c0d056b29ce70",
|
||||
"xdg-desktop-portal-kde-6.7.5-1-aarch64.pkg.tar.xz": "2c57d17d34d577023eb9cd7b0fca1ba9163549afe60450f6271aa148af099ef2"
|
||||
"okular-26.08.2-1-aarch64.pkg.tar.xz": "aef87cf74730d2345092184d7e9b14a0068ba4030de58564aa770506175cbf06",
|
||||
"plasma-desktop-6.8.1-1-aarch64.pkg.tar.xz": "4b24662a2059b21ca98b5b35b72216f22c9e316057247ea018bf6318b07cfdb6",
|
||||
"plasma-integration-6.8.1-1-aarch64.pkg.tar.xz": "514f7d2a96370814b9374d7c52e1873257af6e18190d130e5a8d3d6d1fffdc54",
|
||||
"plasma-pa-6.8.1-1-aarch64.pkg.tar.xz": "13dff66d30072744c7870bd1a294ae96f0fee086a1533b8052d7dfc038d57c45",
|
||||
"plasma-systemmonitor-6.8.1-1-aarch64.pkg.tar.xz": "551b7c1f24cd5df64de4f5ba199bc71c00e2924c16a8241b21c020584794e10d",
|
||||
"plasma-workspace-6.8.1-1-aarch64.pkg.tar.xz": "4c713990aeab118d50865c818f9689ae7637dc6556e4a0e2fec5e0b348cdcd29",
|
||||
"spectacle-1:6.8.1-1-aarch64.pkg.tar.xz": "0d697803bd0135701688be3869d4d99eec6b8b43ca761610da73f44cb77bfa5c",
|
||||
"systemsettings-6.8.1-1-aarch64.pkg.tar.xz": "db528089fa328d67dadb50be3b822858238785d8c659a9ef95389b993efcb234",
|
||||
"unrar-1:7.3.1-1-aarch64.pkg.tar.xz": "9883e19b1f1adfa430285191b1f96db4cc208608baebd955f3fe9fee92cd3bdd",
|
||||
"unzip-6.0-23-aarch64.pkg.tar.xz": "edc91c7e4e400f20345439744262d1ceded104c78d940659a6b9876076ef33fc",
|
||||
"wget-1.25.0-6-aarch64.pkg.tar.xz": "e2bf0067cca93877c737c7d48bc36fff32e184c7874829429b9473c10a12dd39",
|
||||
"wl-clipboard-1:2.3.0-1-aarch64.pkg.tar.xz": "723a63b140e00085a533ebb1ec36fa9305b5e6cbd8fb80c0521fbeff77a72982",
|
||||
"xclip-0.13-6-aarch64.pkg.tar.xz": "772ec9336b679b0ef277d1ef0b69b74777467239e16ec845af00c07fa849d166",
|
||||
"xdg-desktop-portal-kde-6.8.1-1-aarch64.pkg.tar.xz": "8098c0ef0454335bb7c806049d66977c512657346222606737d72a7ae1de3146",
|
||||
"zip-3.0-14-aarch64.pkg.tar.xz": "9887f177544021809d065d0298514e98f76b55f9120119f748f5a28c8bb51994"
|
||||
},
|
||||
"legacyApplications": {
|
||||
"featherpad-1.6.3-1-aarch64.pkg.tar.xz": "fcac55215815c0b712453f9bcc09abfe4b518e36025a111a7a7598ef04913f3d",
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
desktop-kde-r1
|
||||
desktop-kde-r2
|
||||
desktop-kde-r3
|
||||
@@ -0,0 +1,18 @@
|
||||
<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
|
||||
<style>
|
||||
html, body { margin: 0; height: 100%; background: #000; overflow: hidden; }
|
||||
#player { position: absolute; inset: 0; }
|
||||
#status { position: absolute; left: 0; right: 0; bottom: 12%; text-align: center; color: #ddd;
|
||||
font: 16px sans-serif; text-shadow: 0 0 4px #000; pointer-events: none; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="player"></div>
|
||||
<div id="status"></div>
|
||||
<script src="player.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,187 @@
|
||||
/* DroidDeck Xbox Cloud Gaming player. Includes Greenlight's player (c) UnknownSKL (Jim Kroon), MIT. */
|
||||
(()=>{var _=class{_player;_dataChannel;constructor(e){this._player=e,this._dataChannel=this._player._peerConnection.createDataChannel(this.getChannelName(),this.getChannelConfig()),this._dataChannel.onopen=this.onOpen.bind(this),this._dataChannel.onmessage=this.onMessage.bind(this),this._dataChannel.onclosing=this.onClosing.bind(this),this._dataChannel.onclose=this.onClose.bind(this),this._dataChannel.onerror=this.onError.bind(this)}getChannelName(){return"channel"}getChannelConfig(){return{}}onOpen(e){console.log(this.getChannelName(),"Opening channel:",e)}onMessage(e){console.log(this.getChannelName(),"Message channel:",e)}onClosing(e){console.log(this.getChannelName(),"Closing channel:",e)}onClose(e){console.log(this.getChannelName(),"Closed channel:",e)}onError(e){console.log(this.getChannelName(),"Error channel:",e)}send(e){if(this._dataChannel.readyState!=="open"){console.log("["+this.getChannelName()+"] Tried to send data while channel is not open. readyState is:",this._dataChannel.readyState);return}return typeof e=="string"&&(e=new TextEncoder().encode(e)),this._dataChannel.send(e)}getPlayer(){return this._player}destroy(){}};var S=class extends _{_micPermissions="prompt";_micStream;constructor(e){super(e),navigator.permissions.query({name:"microphone"}).then(t=>{this._micPermissions=t.state,t.onchange=()=>{this._micPermissions=t.state}})}getChannelName(){return"chat"}getChannelConfig(){return{ordered:!0,protocol:"chatV1"}}destroy(){}};var v=class r{_player;_index;_physicalGamepadId=-1;_rumbleInterval;_isFocused=!0;_gamepadOverride={buttons:{}};_options={enable_keyboard:!1,enable_gamepad:!0,enable_vibration:!0,keyboard_mapping:{A:"Enter",B:"Backspace",X:"x",Y:"y",DPadUp:"ArrowUp",DPadDown:"ArrowDown",DPadLeft:"ArrowLeft",DPadRight:"ArrowRight",LeftShoulder:"[",RightShoulder:"]",LeftThumb:"l",RightThumb:"r",LeftTrigger:"-",RightTrigger:"=",Menu:"m",View:"v",Nexus:"n"},gamepad_mapping:{A:"0",B:"1",X:"2",Y:"3",DPadUp:"12",DPadDown:"13",DPadLeft:"14",DPadRight:"15",LeftShoulder:"4",RightShoulder:"5",LeftThumb:"10",RightThumb:"11",LeftTrigger:"6",RightTrigger:"7",Menu:"9",View:"8",Nexus:"16"},gamepad_axes_mapping:{LeftThumbXAxis:"0",LeftThumbYAxis:"1",RightThumbXAxis:"2",RightThumbYAxis:"3"},gamepad_deadzone:.08,gamepad_force_capture:!1};_listener={keyDown:this.onKeyDown.bind(this),keyUp:this.onKeyUp.bind(this),gamepadConnected:this.onGamepadConnected.bind(this),gamepadDisconnected:this.onGamepadDisconnected.bind(this),windowFocus:this.onWindowFocus.bind(this),windowBlur:this.onWindowBlur.bind(this)};constructor(e,t={}){this._index=e,this._options={...this._options,...t}}attach(e){this._player=e,this._player._channels.control.sendGamepadState(this._index,!0,this),this._options.enable_keyboard===!0&&(window.addEventListener("keydown",this._listener.keyDown),window.addEventListener("keyup",this._listener.keyUp)),this._options.enable_gamepad===!0&&(window.addEventListener("gamepadconnected",this._listener.gamepadConnected),window.addEventListener("gamepaddisconnected",this._listener.gamepadDisconnected)),this._options.enable_gamepad===!0&&this._options.gamepad_force_capture===!1&&(window.addEventListener("blur",this._listener.windowBlur),window.addEventListener("focus",this._listener.windowFocus)),this.detectActiveGamepad()}detach(){if(this._player===void 0){console.log("[Gamepad] Player is not attached. this._player is:",this._player);return}this._player._channels.control.sendGamepadState(this._index,!1),this._physicalGamepadId=-1,this._rumbleInterval!==void 0&&clearInterval(this._rumbleInterval),this._options.enable_keyboard===!0&&(window.removeEventListener("keydown",this._listener.keyDown),window.removeEventListener("keyup",this._listener.keyUp)),this._options.enable_gamepad===!0&&(window.removeEventListener("gamepadconnected",this._listener.gamepadConnected),window.removeEventListener("gamepaddisconnected",this._listener.gamepadDisconnected)),this._options.enable_gamepad===!0&&this._options.gamepad_force_capture===!1&&(window.removeEventListener("blur",this._listener.windowBlur),window.removeEventListener("focus",this._listener.windowFocus))}sendButtonState(e,t){if(this._player===void 0){console.log("[Gamepad] Player is not attached. this._player is:",this._player);return}if(!(e in this.getDefaultFamepadFrame())){console.log("[Gamepad] Invalid button:",e);return}let n=this.getDefaultFamepadFrame();n.GamepadIndex=this._index,this._gamepadOverride.buttons[e]=t}onKeyDown(e){if(this._isFocused!==!1)for(let t in this._options.keyboard_mapping)this._options.keyboard_mapping[t]===e.key&&(this._gamepadOverride.buttons[t]=1,e.preventDefault())}onKeyUp(e){if(this._isFocused!==!1)for(let t in this._options.keyboard_mapping)this._options.keyboard_mapping[t]===e.key&&(this._gamepadOverride.buttons[t]=0,e.preventDefault())}onWindowFocus(){this._isFocused=!0}onWindowBlur(){}getDefaultFamepadFrame(){return{GamepadIndex:0,Nexus:0,Menu:0,View:0,A:0,B:0,X:0,Y:0,DPadUp:0,DPadDown:0,DPadLeft:0,DPadRight:0,LeftShoulder:0,Line truncated
|
||||
|
||||
`+t.ContentText)?this.completeTransaction(e.id,{Result:0}):this.completeTransaction(e.id,{Result:1})}};var M=class extends _{_handshakeCompleted=!1;getChannelName(){return"message"}getChannelConfig(){return{protocol:"messageV1",ordered:!0}}onOpen(){console.log("[MessageChannel] Sending handshake...");let e=JSON.stringify({type:"Handshake",version:"messageV1",id:"be0bfc6d-1e83-4c8a-90ed-fa8601c5a179",cv:"0"});this.send(e)}onMessage(e){let t=JSON.parse(e.data);switch(t.type){case"HandshakeAck":console.log("[MessageChannel] Handshake completed"),this._handshakeCompleted=!0,this.getPlayer()._channels.control.sendAuthorization(),this.getPlayer()._channels.input.start(),this.sendConfig();break;case"TransactionStart":case"Message":new D(this,t);break;default:console.log("[MessageChannel] Unhandled message type:",t.type,t)}}sendConfig(){let e=[],t=[0,2,0],n=JSON.stringify(this.generateMessage("/streaming/systemUi/configuration",{version:t,systemUis:e}));this.send(n);let i=JSON.stringify(this.generateMessage("/streaming/properties/clientappinstallidchanged",{clientAppInstallId:"c97d7ee0-73b2-4239-bf1d-9d805a338429"}));this.send(i);let a=JSON.stringify(this.generateMessage("/streaming/characteristics/orientationchanged",{orientation:0}));this.send(a);let s=JSON.stringify(this.generateMessage("/streaming/characteristics/touchinputenabledchanged",{touchInputEnabled:!1}));this.send(s);let o=JSON.stringify(this.generateMessage("/streaming/characteristics/clientdevicecapabilities",{}));this.send(o);let d=JSON.stringify(this.generateMessage("/streaming/characteristics/dimensionschanged",{horizontal:1920,vertical:1080,preferredWidth:1920,preferredHeight:1080,safeAreaLeft:0,safeAreaTop:0,safeAreaRight:1920,safeAreaBottom:1080,supportsCustomResolution:!0}));this.send(d)}generateMessage(e,t){return{type:"Message",content:JSON.stringify(t),id:Q(),target:e,cv:""}}destroy(){}};var E=class{_address;_ipv4Address;_ipv4Port;constructor(e){this._address=e;let t=this._address.split(":"),n=t[6]+t[7],i=t[5],a=~parseInt(n.substring(0,2),16)&255,s=~parseInt(n.substring(2,4),16)&255,o=~parseInt(n.substring(4,6),16)&255,d=~parseInt(n.substring(6,8),16)&255,u=~parseInt(i.substring(0,4),16)&65535;this._ipv4Address=a+"."+s+"."+o+"."+d,this._ipv4Port=u}getIpv4Address(){return this._ipv4Address}getIpv4Port(){return this._ipv4Port}};var R=class{_peerConnection;_iceCandidates=[];constructor(e){this._peerConnection=e._peerConnection,this._peerConnection.addEventListener("icecandidate",t=>{t.candidate&&this._iceCandidates.push(t.candidate)})}getCandidates(){return this._iceCandidates}setRemoteCandidates(e){e.length===0&&console.warn("Error: No candidates received!");for(let t in e){if(e[t].candidate==="a=end-of-candidates")continue;let n=e[t].candidate.split(" ");if(n.length>4&&n[4].substr(0,4)==="2001"){let i=new E(n[4]);this._peerConnection.addIceCandidate({candidate:"a=candidate:10 1 UDP 1 "+i.getIpv4Address()+" 9002 typ host ",sdpMLineIndex:e[t].sdpMLineIndex,sdpMid:e[t].sdpMid}),this._peerConnection.addIceCandidate({candidate:"a=candidate:11 1 UDP 1 "+i.getIpv4Address()+" "+i.getIpv4Port()+" typ host ",sdpMLineIndex:e[t].sdpMLineIndex,sdpMid:e[t].sdpMid})}this._peerConnection.addIceCandidate({candidate:e[t].candidate,sdpMid:e[t].sdpMid,sdpMLineIndex:e[t].sdpMLineIndex})}}};var I=class{_player;_peerConnection;constructor(e){this._player=e,this._peerConnection=e._peerConnection}getAvailableCodecs(){let e=RTCRtpReceiver.getCapabilities("video")?.codecs;if(e===void 0)return[];let t=[];for(let n in e)t.includes(e[n].mimeType)||t.push(e[n].mimeType);return t}setLocalSDP(e){return console.log("[SDP] setLocalSDP() Setting local SDP:",e),e.sdp=e.sdp?.replace("useinbandfec=1","useinbandfec=1; stereo=1"),e}setRemoteSDP(e){return console.log("[SDP] setRemoteSDP() Setting remote SDP:",e),e}getDefaultCodecPreferences(){let e=RTCRtpReceiver.getCapabilities("video")?.codecs;if(e===void 0)return[];let t=[],n=[],i=[],a=[];for(let o in e)e[o].mimeType.includes("H264")?e[o].sdpFmtpLine?.includes("profile-level-id=4d")?t.push(e[o]):e[o].sdpFmtpLine?.includes("profile-level-id=42e")?n.push(e[o]):e[o].sdpFmtpLine?.includes("profile-level-id=420")&&i.push(e[o]):(e[o].mimeType.includes("ulpfec")||e[o].mimeType.includes("flexfec")||e[o].mimeType.includes("VP9")||e[o].mimeType.includes("VP8"))&&a.push(e[o]);return[...t,...n,...i,...a]}_setBitrate(e,t,n){let i=e.split(`
|
||||
`),a=-1;for(let o=0;o<i.length;o++)if(i[o].indexOf("m="+t)===0){a=o;break}if(a===-1)return console.debug("Could not find the m line for",t),e;for(a++;i[a].indexOf("i=")===0||i[a].indexOf("c=")===0;)a++;if(i[a].indexOf("b")===0)return i[a]="b=AS:"+n,i.join(`
|
||||
`);let s=i.slice(0,a);return s.push("b=AS:"+n),s=s.concat(i.slice(a,i.length)),s.join(`
|
||||
`)}};var P=class{_player;_peerConnection;_videoCodec="";_audioCodec="";_videoWidth=0;_videoHeight=0;_videoFps=0;_rtt=0;_remoteHost="";_remotePort=0;_remoteIsLocal=!1;_remoteIsIpv6=!1;_activeRemoteCandidate="";constructor(e){this._player=e,this._peerConnection=e._peerConnection,setInterval(this.loop.bind(this),1e3)}loop(){this._peerConnection.getStats().then(e=>{e.forEach(t=>{t.type==="inbound-rtp"?this.readInboundRtp(t):t.type==="candidate-pair"&&t.packetsReceived!==void 0&&t.packetsReceived>0?this.readCandidatePair(t):t.type==="remote-candidate"&&this.readRemoteCandidate(t)})})}readInboundRtp(e){e.kind==="video"&&e.codecId&&e.packetsReceived!==void 0&&e.packetsReceived>0?(e.codecId.includes("profile-level-id=4d")?this._videoCodec="H264 (High)":e.codecId.includes("profile-level-id=42e")?this._videoCodec="H264 (Normal)":e.codecId.includes("profile-level-id=420")?this._videoCodec="H264 (Low)":this._videoCodec="Other ("+e.codecId+")",e.frameWidth&&(this._videoWidth=e.frameWidth),e.frameHeight&&(this._videoHeight=e.frameHeight),e.framesPerSecond&&(this._videoFps=e.framesPerSecond)):e.kind==="audio"&&e.codecId&&e.packetsReceived!==void 0&&e.packetsReceived>0&&(this._audioCodec=e.codecId)}readCandidatePair(e){this._activeRemoteCandidate=e.remoteCandidateId,this._rtt=e.currentRoundTripTime}readRemoteCandidate(e){e.id===this._activeRemoteCandidate&&(this.isPrivateIP(e.address)?this._remoteIsLocal=!0:this._remoteIsLocal=!1,this.isIpv6(e.address)?this._remoteIsIpv6=!0:this._remoteIsIpv6=!1,this._remoteHost=e.address,this._remotePort=e.port)}isPrivateIP(e){let t=e.split(".");return t[0]==="10"||t[0]==="172"&&parseInt(t[1],10)>=16&&parseInt(t[1],10)<=31||t[0]==="192"&&t[1]==="168"}isIpv6(e){return e.split(":").length>3}};var G=class{_player;_videoComponent;_overlays={debug:void 0};constructor(e,t){this._videoComponent=e,this._player=t}toggleDebug(){this._overlays.debug===void 0?this.createDebugOverlay():this.destroy()}createDebugOverlay(){this._overlays.debug=document.createElement("div"),this._overlays.debug.id="playerDebugOverlay",this._overlays.debug.style.position="absolute",this._overlays.debug.style.top="0",this._overlays.debug.style.left="0",this._overlays.debug.style.width=this._videoComponent.getElement()?.style.width||"100%",this._overlays.debug.style.height=this._videoComponent.getElement()?.style.height||"auto",this._overlays.debug.style.background="linear-gradient(0deg, rgba(0,0,0, 0) 0%, rgba(0,0,0, 0) 75%, rgba(0,0,0, 0.5) 100%)",this._overlays.debug.style.padding="10px",this._overlays.debug.style.pointerEvents="none",document.getElementById(this._player.getElementId())?.appendChild(this._overlays.debug),setTimeout(()=>{this.refreshDebugOverlay()},500),this.refreshDebugOverlay()}destroy(){this._overlays.debug?.remove(),this._overlays.debug=void 0}refreshDebugOverlay(){if(this._overlays.debug!==void 0){this._overlays.debug.innerHTML="",this._overlays.debug.appendChild(this.createLabel("Local Play",this._player.getStats()._remoteIsLocal?"Local":"Remote","ok")),this._overlays.debug.appendChild(this.createLabel("Resolution",this._player.getStats()._videoWidth+"x"+this._player.getStats()._videoHeight,"ok")),this._overlays.debug.appendChild(this.createLabel("Stream FPS",this._player.getStats()._videoFps.toString(),this._player.getStats()._videoFps>=58?"ok":"warning"));let e=this._videoComponent.getFrameStats?.();e&&(this._overlays.debug.appendChild(this.createLabel("Render FPS",e.renderingFps.toString(),e.renderingFps>=58?"ok":"warning")),this._overlays.debug.appendChild(this.createLabel("Render Delay",e.renderDelayMs.toString()+" ms",e.renderDelayMs<16?"ok":e.renderDelayMs<33?"warning":"error")),this._overlays.debug.appendChild(this.createLabel("Dropped Frames",e.droppedFrames.toString(),e.droppedFrames===0?"ok":e.droppedFrames<30?"warning":"error"))),this._overlays.debug.appendChild(this.createLabel("Connection",this._player.getStats()._remoteIsIpv6?"IPv6":"IPv4","ok")),this._overlays.debug.appendChild(this.createLabel("Video",this._player.getStats()._videoCodec,"ok"));let t=this._player.getStats()._rtt*1e3>75?"error":this._player.getStats()._rtt*1e3>40?"warning":"ok";this._overlays.debug.appendChild(this.createLabel("RTT",(this._player.getStats()._rtt*1e3).toString()+" ms",t)),setTimeout(()=>{this.refreshDebugOverlay()},500)}}createLabel(e,t="",n=""){let i={borderRadius:"5px",background:"linear-gradient(0deg, rgba(28,26,26,1) 0%, rgba(47,45,45,1) 100%)",padding:"10px",fontSize:"12px",marginTop:"3px",marginRight:"10px",marginBottom:"2px",textTransform:"uppercase",color:"white",display:"inline-block"},a=document.createElement("span"),s={error:"rgb(220, 53, 69)",warning:"rgb(255, 193, 7)",ok:"rgb(25, 135, 84)"};t!==""?a.innerHTML=`${e}: <span style="background: ${s[n]}; border-radius: 5px; padding: 4px; padding-left: 8px; padding-right: 8px;">${t}</span>`:a.innerText=e;for(let o in i)a.style[o]=i[o];return a}};var L=class{_player;_element;_overlay;constructor(e){this._player=e,this._overlay=new G(this,this._pLine truncated
|
||||
in vec2 position;
|
||||
out vec2 vUV;
|
||||
void main() { vUV = position * 0.5 + 0.5; gl_Position = vec4(position, 0.0, 1.0); }`,j=`attribute vec2 position;
|
||||
varying vec2 vUV;
|
||||
void main() { vUV = position * 0.5 + 0.5; gl_Position = vec4(position, 0.0, 1.0); }`,Z=`#version 300 es
|
||||
precision mediump float;
|
||||
uniform sampler2D screenTexture;
|
||||
uniform vec2 resolution;
|
||||
uniform int filterId;
|
||||
uniform float sharpenFactor;
|
||||
uniform float brightness;
|
||||
uniform float contrast;
|
||||
uniform float gamma;
|
||||
uniform float saturation;
|
||||
uniform float deband;
|
||||
out vec4 fragColor;
|
||||
const float CAS_CONTRAST_PEAK = 0.8 * -3.0 + 8.0;
|
||||
|
||||
vec3 sharpen(vec2 coord, vec3 e) {
|
||||
vec2 px = 1.0 / resolution;
|
||||
vec3 b = texture(screenTexture, coord + px * vec2(0, 1)).rgb;
|
||||
vec3 d = texture(screenTexture, coord + px * vec2(-1, 0)).rgb;
|
||||
vec3 f = texture(screenTexture, coord + px * vec2(1, 0)).rgb;
|
||||
vec3 h = texture(screenTexture, coord + px * vec2(0, -1)).rgb;
|
||||
vec3 a = texture(screenTexture, coord + px * vec2(-1, 1)).rgb;
|
||||
vec3 c = texture(screenTexture, coord + px * vec2(1, 1)).rgb;
|
||||
vec3 g = texture(screenTexture, coord + px * vec2(-1, -1)).rgb;
|
||||
vec3 i = texture(screenTexture, coord + px * vec2(1, -1)).rgb;
|
||||
if (filterId == 1) {
|
||||
vec3 blur = ((a + c + g + i) + (b + d + f + h) * 2.0 + e * 4.0) / 16.0;
|
||||
return e + (e - blur) * sharpenFactor / 3.0;
|
||||
}
|
||||
vec3 minRgb = min(min(min(d, e), min(f, b)), h) + min(min(a, c), min(g, i));
|
||||
vec3 maxRgb = max(max(max(d, e), max(f, b)), h) + max(max(a, c), max(g, i));
|
||||
vec3 amplify = inversesqrt(clamp(min(minRgb, 2.0 - maxRgb) / maxRgb, 0.0, 1.0));
|
||||
vec3 weight = -(1.0 / (amplify * CAS_CONTRAST_PEAK));
|
||||
vec3 outColor = clamp(((b + d + f + h) * weight + e) / (4.0 * weight + 1.0), 0.0, 1.0);
|
||||
return mix(e, outColor, sharpenFactor / 2.0);
|
||||
}
|
||||
|
||||
float ign(vec2 p) { return fract(52.9829189 * fract(dot(p, vec2(0.06711056, 0.00583715)))); }
|
||||
|
||||
void main() {
|
||||
vec2 uv = gl_FragCoord.xy / resolution;
|
||||
vec3 color = texture(screenTexture, uv).rgb;
|
||||
if (sharpenFactor > 0.0) color = sharpen(uv, color);
|
||||
color = clamp(color + brightness, 0.0, 1.0);
|
||||
color = (color - 0.5) * clamp(contrast + 1.0, 0.5, 2.0) + 0.5;
|
||||
color = mix(vec3(dot(color, vec3(0.2126, 0.7152, 0.0722))), color, saturation);
|
||||
color = pow(max(color, 0.0), vec3(1.0 / gamma));
|
||||
if (deband > 0.0) color += vec3(((ign(gl_FragCoord.xy) + ign(gl_FragCoord.xy + vec2(11.0, 17.0))) - 1.0) * (deband / 255.0));
|
||||
fragColor = vec4(color, 1.0);
|
||||
}`,ee=`precision highp float;
|
||||
#define FXAA_MIN_REDUCE (1.0 / 128.0)
|
||||
#define FXAA_MUL_REDUCE (1.0 / 8.0)
|
||||
#define MAX_SPAN 8.0
|
||||
uniform sampler2D screenTexture;
|
||||
uniform vec2 resolution;
|
||||
const vec3 luma = vec3(0.299, 0.587, 0.114);
|
||||
void main() {
|
||||
vec2 invResolution = 1.0 / resolution;
|
||||
vec3 rgbNW = texture2D(screenTexture, (gl_FragCoord.xy + vec2(-1.0, -1.0)) * invResolution).rgb;
|
||||
vec3 rgbNE = texture2D(screenTexture, (gl_FragCoord.xy + vec2( 1.0, -1.0)) * invResolution).rgb;
|
||||
vec3 rgbSW = texture2D(screenTexture, (gl_FragCoord.xy + vec2(-1.0, 1.0)) * invResolution).rgb;
|
||||
vec3 rgbSE = texture2D(screenTexture, (gl_FragCoord.xy + vec2( 1.0, 1.0)) * invResolution).rgb;
|
||||
vec3 rgbM = texture2D(screenTexture, gl_FragCoord.xy * invResolution).rgb;
|
||||
float lumaNW = dot(rgbNW, luma);
|
||||
float lumaNE = dot(rgbNE, luma);
|
||||
float lumaSW = dot(rgbSW, luma);
|
||||
float lumaSE = dot(rgbSE, luma);
|
||||
float lumaM = dot(rgbM, luma);
|
||||
float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));
|
||||
float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));
|
||||
vec2 dir;
|
||||
dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));
|
||||
dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));
|
||||
float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) * 0.25 * FXAA_MUL_REDUCE, FXAA_MIN_REDUCE);
|
||||
float minDirFactor = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);
|
||||
dir = clamp(dir * minDirFactor, vec2(-MAX_SPAN), vec2(MAX_SPAN)) * invResolution;
|
||||
vec4 rgbA = 0.5 * (
|
||||
texture2D(screenTexture, gl_FragCoord.xy * invResolution + dir * (1.0 / 3.0 - 0.5)) +
|
||||
texture2D(screenTexture, gl_FragCoord.xy * invResolution + dir * (2.0 / 3.0 - 0.5)));
|
||||
vec4 rgbB = rgbA * 0.5 + 0.25 * (
|
||||
texture2D(screenTexture, gl_FragCoord.xy * invResolution + dir * -0.5) +
|
||||
texture2D(screenTexture, gl_FragCoord.xy * invResolution + dir * 0.5));
|
||||
float lumaB = dot(rgbB, vec4(luma, 0.0));
|
||||
gl_FragColor = lumaB < lumaMin || lumaB > lumaMax ? rgbA : rgbB;
|
||||
}`,te=`precision highp float;
|
||||
uniform sampler2D screenTexture;
|
||||
uniform vec2 resolution;
|
||||
void main() {
|
||||
vec2 uv = gl_FragCoord.xy / resolution;
|
||||
float edgeThreshold = 0.2;
|
||||
vec2 offset = vec2(1.0) / resolution;
|
||||
vec3 colorCenter = texture2D(screenTexture, uv).rgb;
|
||||
vec3 colorLeft = texture2D(screenTexture, uv - vec2(offset.x, 0.0)).rgb;
|
||||
vec3 colorRight = texture2D(screenTexture, uv + vec2(offset.x, 0.0)).rgb;
|
||||
vec3 colorUp = texture2D(screenTexture, uv - vec2(0.0, offset.y)).rgb;
|
||||
vec3 colorDown = texture2D(screenTexture, uv + vec2(0.0, offset.y)).rgb;
|
||||
float diffHorizontal = length(colorRight - colorLeft);
|
||||
float diffVertical = length(colorUp - colorDown);
|
||||
float edgeFactor = step(edgeThreshold, diffHorizontal + diffVertical);
|
||||
vec3 outlineColor = mix(colorCenter, vec3(0.0), edgeFactor);
|
||||
gl_FragColor = vec4(outlineColor, 1.0);
|
||||
}`,ne=`precision highp float;
|
||||
#define CA_AMOUNT 1.0025
|
||||
#define SCANLINE_INTENSITY_X 0.125
|
||||
#define SCANLINE_INTENSITY_Y 0.375
|
||||
#define SCANLINE_SIZE 1024.0
|
||||
uniform sampler2D screenTexture;
|
||||
varying vec2 vUV;
|
||||
void main() {
|
||||
vec4 finalColor = texture2D(screenTexture, vUV);
|
||||
finalColor.rgb = vec3(
|
||||
texture2D(screenTexture, (vUV - 0.5) * CA_AMOUNT + 0.5).r,
|
||||
finalColor.g,
|
||||
texture2D(screenTexture, (vUV - 0.5) / CA_AMOUNT + 0.5).b
|
||||
);
|
||||
float scanlineX = abs(sin(vUV.x * SCANLINE_SIZE) * 0.5 * SCANLINE_INTENSITY_X);
|
||||
float scanlineY = abs(sin(vUV.y * SCANLINE_SIZE) * 0.5 * SCANLINE_INTENSITY_Y);
|
||||
gl_FragColor = vec4(mix(finalColor.rgb, vec3(0.0), scanlineX + scanlineY), finalColor.a);
|
||||
}`,ie=`precision highp float;
|
||||
#define PI 3.14159265
|
||||
#define SCANLINE_INTENSITY 0.35
|
||||
#define CHROMA_OFFSET 0.005
|
||||
#define BLUR_RADIUS 0.002
|
||||
#define WARP_AMOUNT 0.01
|
||||
#define SCANLINE_DARKEN 0.5
|
||||
uniform sampler2D screenTexture;
|
||||
uniform int FrameCount;
|
||||
uniform vec2 TextureSize;
|
||||
uniform vec2 resolution;
|
||||
varying vec2 vUV;
|
||||
const mat3 yiq_mat = mat3(
|
||||
0.299, 0.587, 0.114,
|
||||
0.596, -0.275, -0.321,
|
||||
0.212, -0.523, 0.311
|
||||
);
|
||||
const mat3 yiq2rgb_mat = mat3(
|
||||
1.0, 0.956, 0.621,
|
||||
1.0, -0.272, -0.647,
|
||||
1.0, -1.106, 1.705
|
||||
);
|
||||
vec3 applyNTSC(vec2 uv) {
|
||||
vec3 col = texture2D(screenTexture, uv).rgb;
|
||||
vec3 yiq = col * yiq_mat;
|
||||
float chromaPhase = PI * (mod(uv.y * TextureSize.y, 2.0) + float(FrameCount));
|
||||
yiq.y *= cos(chromaPhase * 0.5);
|
||||
yiq.z *= sin(chromaPhase * 0.5);
|
||||
vec3 rgb = yiq * yiq2rgb_mat;
|
||||
vec3 finalColor;
|
||||
finalColor.r = texture2D(screenTexture, uv + vec2(CHROMA_OFFSET, 0.0)).r;
|
||||
finalColor.g = texture2D(screenTexture, uv + vec2(0.0, BLUR_RADIUS)).g;
|
||||
finalColor.b = texture2D(screenTexture, uv - vec2(CHROMA_OFFSET, 0.0)).b;
|
||||
return finalColor;
|
||||
}
|
||||
vec3 applyScanlines(vec2 uv) {
|
||||
vec3 col = texture2D(screenTexture, uv).rgb;
|
||||
float scanline = abs(sin(uv.y * resolution.y * 2.0)) * SCANLINE_INTENSITY;
|
||||
col *= 1.0 - (scanline * SCANLINE_DARKEN);
|
||||
return col;
|
||||
}
|
||||
vec2 applyWarp(vec2 uv) {
|
||||
uv = uv * 2.0 - 1.0;
|
||||
float r = sqrt(uv.x * uv.x + uv.y * uv.y);
|
||||
uv += uv * (r * r) * WARP_AMOUNT;
|
||||
return uv * 0.5 + 0.5;
|
||||
}
|
||||
void main() {
|
||||
vec2 warpedUV = applyWarp(vUV);
|
||||
vec3 ntscColor = applyNTSC(warpedUV);
|
||||
vec3 scanlineColor = applyScanlines(warpedUV);
|
||||
vec3 finalColor = mix(ntscColor, scanlineColor, 0.7);
|
||||
gl_FragColor = vec4(finalColor, 1.0);
|
||||
}`,H=class{constructor(e,t){this.video=e;this.effects=t;this.canvas=document.createElement("canvas"),Object.assign(this.canvas.style,{position:"absolute",inset:"0",width:"100%",height:"100%",objectFit:"contain",zIndex:"1"}),e.parentElement?.appendChild(this.canvas);let n=this.canvas.getContext("webgl2",{alpha:!1,antialias:!1,depth:!1,desynchronized:!0,powerPreference:"high-performance"});if(n===null)throw new Error("WebGL2 unavailable");this.gl=n;let i=n.createBuffer();n.bindBuffer(n.ARRAY_BUFFER,i),n.bufferData(n.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),n.STATIC_DRAW),this.passes.set("base",this.compile(J,Z,["screenTexture","resolution","filterId","sharpenFactor","brightness","contrast","gamma","saturation","deband"])),this.videoTexture=this.texture(),this.schedule()}canvas;gl;passes=new Map;videoTexture;targets=[];width=0;height=0;frame=0;lastDraw=0;stopped=!1;idle=!1;pending=!1;update(e){this.effects=e}pause(){this.idle||this.stopped||(this.idle=!0,this.canvas.style.display="none")}resume(e){this.effects=e,!(!this.idle||this.stopped)&&(this.idle=!1,this.canvas.style.display="",this.schedule())}schedule(){this.pending||(this.pending=!0,this.video.requestVideoFrameCallback(this.onFrame))}compile(e,t,n){let i=this.gl,a=(o,d)=>{let u=i.createShader(o);if(i.shaderSource(u,d),i.compileShader(u),!i.getShaderParameter(u,i.COMPILE_STATUS))throw new Error(`shader: ${i.getShaderInfoLog(u)}`);return u},s=i.createProgram();if(i.attachShader(s,a(i.VERTEX_SHADER,e)),i.attachShader(s,a(i.FRAGMENT_SHADER,t)),i.bindAttribLocation(s,0,"position"),i.linkProgram(s),!i.getProgramParameter(s,i.LINK_STATUS))throw new Error(`program: ${i.getProgramInfoLog(s)}`);return{program:s,uniforms:new Map(n.map(o=>[o,i.getUniformLocation(s,o)]))}}extra(e){let t=this.passes.get(e);if(t===void 0){let n={fxaa:ee,toon:te,crt:ne,ntsc:ie}[e];t=this.compile(j,n,["screenTexture","resolution","TextureSize","FrameCount"]),this.passes.set(e,t)}return t}texture(){let e=this.gl,t=e.createTexture();return e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),t}resize(e,t){let n=this.gl;this.width=e,this.height=t,this.canvas.width=e,this.canvas.height=t;for(let i of this.targets)n.deleteFramebuffer(i.framebuffer),n.deleteTexture(i.texture);this.targets=[0,1].map(()=>{let i=this.texture();n.texImage2D(n.TEXTURE_2D,0,n.RGBA,e,t,0,n.RGBA,n.UNSIGNED_BYTE,null);let a=n.createFramebuffer();return n.bindFramebuffer(n.FRAMEBUFFER,a),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,i,0),{framebuffer:a,texture:i}}),n.bindFramebuffer(n.FRAMEBUFFER,null)}onFrame=e=>{if(this.pending=!1,this.stopped||this.idle)return;this.schedule();let t=this.effects.maxFps;if(!(t>0&&e-this.lastDraw<1e3/t-2)){this.lastDraw=e;try{this.draw()}catch(n){window.DDCloud?.log(`effects: ${String(n).slice(0,200)}`),this.destroy()}}};draw(){let e=this.gl,t=this.effects,n=this.video.videoWidth,i=this.video.videoHeight;if(n===0||i===0)return;(n!==this.width||i!==this.height)&&this.resize(n,i),this.frame++,e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,this.videoTexture),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,this.video);let a=["fxaa","toon","crt","ntsc"].filter(d=>t[d]);e.viewport(0,0,n,i),e.enableVertexAttribArray(0),e.vertexAttribPointer(0,2,e.FLOAT,!1,0,0);let s=this.passes.get("base");e.bindFramebuffer(e.FRAMEBUFFER,a.length>0?this.targets[0].framebuffer:null),e.useProgram(s.program);let o=s.uniforms;e.uniform1i(o.get("screenTexture"),0),e.uniform2f(o.get("resolution"),n,i),e.uniform1i(o.get("filterId"),t.sharpenMode==="usm"?1:2),e.uniform1f(o.get("sharpenFactor"),t.sharpen),e.uniform1f(o.get("brightness"),t.brightness/100),e.uniform1f(o.get("contrast"),t.contrast/100),e.uniform1f(o.get("gamma"),Math.min(5,Math.max(.1,t.gamma))),e.uniform1f(o.get("saturation"),t.saturation/100),e.uniform1f(o.get("deband"),t.deband),e.drawArrays(e.TRIANGLES,0,3),a.forEach((d,u)=>{let h=this.extra(d),g=this.targets[u%2],p=u===a.length-1;e.bindFramebuffer(e.FRAMEBUFFER,p?null:this.targets[(u+1)%2].framebuffer),e.useProgram(h.program),e.bindTexture(e.TEXTURE_2D,g.texture);let c=h.uniforms;e.uniform1i(c.get("screenTexture")??null,0),e.uniform2f(c.get("resolution")??null,n,i),e.uniform2f(c.get("TextureSize")??null,n,i),e.uniform1i(c.get("FrameCount")??null,this.frame),e.drawArrays(e.TRIANGLES,0,3)})}destroy(){this.stopped=!0,this.canvas.remove(),this.gl.getExtension("WEBGL_lose_context")?.loseContext()}};var V=class{constructor(e){this.pc=e;this.element=document.createElement("div"),Object.assign(this.element.style,{position:"absolute",top:"8px",right:"8px",zIndex:"3",padding:"4px 8px",borderRadius:"6px",background:"rgba(0,0,0,0.55)",color:"#e8e8e8",font:"12px monospace",lineHeight:"16px",pointerEvent
Line truncated
|
||||
`:" \xB7 ")}destroy(){this.show(0,this.vertical,this.server,this.left),this.element.remove()}};function z(r,e){let t=e==="high"?"4d":e==="low"?"420":"42e",n=[];for(let d of r.matchAll(/a=fmtp:(\d+).*profile-level-id=([0-9a-f]{6})/g))d[2].startsWith(t)&&n.push(d[1]);if(n.length===0)return r;let i=r.split(`\r
|
||||
`),a=i.findIndex(d=>d.startsWith("m=video"));if(a<0)return r;let s=i[a].trim().split(" "),o=s.slice(3).filter(d=>!n.includes(d));return i[a]=s.slice(0,3).concat(n,o).join(" "),i.join(`\r
|
||||
`)}function K(r,e){let t=r.split(`\r
|
||||
`),n=t.findIndex(a=>a.startsWith("m=video"));if(n<0)return r;let i=`b=AS:${e}`;for(let a=n+1;a<=t.length;a++){let s=t[a];if(s===void 0||s.startsWith("m=")){t.splice(a,0,i);break}if(!(s.startsWith("i=")||s.startsWith("c="))){if(s.startsWith("b=AS:")){t[a]=i;break}t.splice(a,0,i);break}}return t.join(`\r
|
||||
`)}var m=JSON.parse(DDCloud.settings()),ae=RTCPeerConnection.prototype.setLocalDescription;RTCPeerConnection.prototype.setLocalDescription=function(r){return r?.sdp&&((m.codec==="high"||m.codec==="normal"||m.codec==="low")&&(r.sdp=z(r.sdp,m.codec)),m.bitrateMbps>0&&(r.sdp=K(r.sdp,m.bitrateMbps*1e3))),ae.call(this,r)};window.__ddRumble=m.rumble/100;window.addEventListener("error",r=>DDCloud.log(`error: ${r.message} @${r.lineno}`));window.addEventListener("unhandledrejection",r=>DDCloud.log(`rejection: ${String(r.reason).slice(0,200)}`));window.addEventListener("gamepadconnected",r=>DDCloud.log(`controller: ${r.gamepad.id.slice(0,60)} mapping=${r.gamepad.mapping||"none"} buttons=${r.gamepad.buttons.length} axes=${r.gamepad.axes.length}`));var W=new Map,re=1;window.__ddResolve=(r,e,t)=>{let n=W.get(r);W.delete(r),n&&n({status:e,body:t})};function C(r,e=""){return new Promise(t=>{let n=re++;W.set(n,t),DDCloud.call(n,r,typeof e=="string"?e:JSON.stringify(e))})}var B=r=>new Promise(e=>setTimeout(e,r)),se=r=>r.status>=200&&r.status<300;function x(r){let e=document.getElementById("status");e&&(e.textContent=r),DDCloud.status(r)}var T=class extends Error{constructor(t,n){super(t);this.stage=t;this.detail=n}};function k(r,e){if(!se(e))throw new T(r,`${e.status} ${e.body.slice(0,300)}`);return e}function oe(r,e){return new Promise(t=>{if(r.iceGatheringState==="complete")return t();let n=setTimeout(t,e);r.addEventListener("icegatheringstatechange",()=>{r.iceGatheringState==="complete"&&(clearTimeout(n),t())})})}async function de(){x("Starting the game on Xbox Cloud Gaming\u2026"),k("start",await C("start"));let r=!1,e=0;for(;;){let l=k("state",await C("state")),f=JSON.parse(l.body||"{}");if(f.state==="Provisioned")break;if(f.state==="Failed")throw new T("provision",JSON.stringify(f.errorDetails??{}).slice(0,300));f.state==="ReadyToConnect"&&!r?(r=!0,x("Signing in to the cloud console\u2026"),k("connect",await C("connect"))):f.state==="WaitingForResources"?x(`In the queue for a cloud console\u2026 ${Math.round(e/1e3)} s`):x(`Getting a cloud console ready\u2026 ${Math.round(e/1e3)} s`),await B(1e3),e+=1e3}x("Connecting\u2026");let t=new U("player");t.init();let n=t._peerConnection,i=t._channels.input,a=i.queueMetadataFrame.bind(i);i.queueMetadataFrame=l=>{if(m.preventDrops){let f=l.frameRenderedTimeMs-l.frameDecodedTimeMs;l.frameDecodedTimeMs=l.frameSubmittedTimeMs+10,l.frameRenderedTimeMs=l.frameDecodedTimeMs+f}a(l)};let s,o,d=()=>{if(!(o===void 0||s===void 0&&m.volume===100)){if(s===void 0){let l=new AudioContext;s=l.createGain(),l.createMediaStreamSource(o).connect(s).connect(l.destination);let f=document.querySelector("#player audio");f&&(f.muted=!0)}s.gain.value=m.volume/100}};n.addEventListener("track",l=>{l.track.kind==="audio"&&(o=l.streams[0],d())});let u=new V(n),h,g=()=>{let l=t.getVideoElement();if(l!==void 0){if(!X(m)){h?.pause();return}if(h===void 0)try{h=new H(l,m)}catch(f){DDCloud.log(`effects unavailable: ${String(f).slice(0,200)}`)}else h.resume(m)}};window.__ddApply=l=>{m=JSON.parse(l),window.__ddRumble=m.rumble/100,u.show(m.statsLevel,m.statsLayout==="vertical",m.server,m.statsCorner==="left"),d(),g()},n.addEventListener("connectionstatechange",()=>{n.connectionState==="connected"?(x(""),DDCloud.playing(),u.show(m.statsLevel,m.statsLayout==="vertical",m.server,m.statsCorner==="left"),setTimeout(g,500)):n.connectionState==="failed"?DDCloud.failed("webrtc","connection failed"):n.connectionState==="disconnected"&&x("Connection lost\u2026")});let p=await t.createOffer(),c=k("sdp",await C("sdp",p.sdp??"")),O=JSON.parse(JSON.parse(c.body).exchangeResponse);if(O.status&&O.status!=="success")throw new T("sdp-answer",JSON.stringify(O).slice(0,300));await t.setRemoteSDP(O.sdp),await oe(n,3e3);let Y=(await t.getICECandidates()).map(l=>JSON.stringify({candidate:l.candidate,sdpMid:l.sdpMid,sdpMLineIndex:l.sdpMLineIndex,usernameFragment:l.usernameFragment})),$=k("ice",await C("ice",Y));t.setRemoteIceCandidates(JSON.parse(JSON.parse($.body).exchangeResponse));let q=Date.now();for(;!t._channels.message._handshakeCompleted&&Date.now()-q<2e4;)await B(100);DDCloud.log(`handshake ${t._channels.message._handshakeCompleted?"done":"missing"} after ${Date.now()-q} ms`),await B(300);let b=new v(0,{enable_keyboard:!1});b.attach(t),DDCloud.log(`controllers at attach: ${Array.from(navigator.getGamepads()).filter(Boolean).length}`),window.__ddNexus=()=>{b.sendButtonState("Nexus",1),setTimeout(()=>b.sendButtonState("Nexus",0),200)},window.__ddButton=(l,f)=>b.sendButtonState(l,f),window.__ddInput=l=>{l?b.onWindowFocus():b.onWindowBlur()},setInterval(()=>{C("keepalive")},3e4),window.__ddStop=()=>{try{h?.destroy(),u.destroy(),b.detach(),t.destroy()}catch{}}}de().catch(r=>{r instanceof T?DDCloud.failed(r.stage,r.detail):DDCloud.failed("page",String(r).slice(0,300))});})();
|
||||
@@ -8,7 +8,6 @@ set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-z,max-page-size=16384
|
||||
|
||||
add_subdirectory(adrenotools)
|
||||
|
||||
# DXVK's DXBC->SPIR-V translator is zlib licensed (vendored under thirdparty/dxbc).
|
||||
add_subdirectory(thirdparty/dxbc)
|
||||
|
||||
set(DDFG_UPSTREAM "v0.3.0")
|
||||
@@ -37,13 +36,14 @@ target_link_libraries(sdnative log)
|
||||
add_library(deviceinfo SHARED deviceinfo/vkinfo.c)
|
||||
target_link_libraries(deviceinfo dl)
|
||||
|
||||
add_library(gpuclock SHARED gpuclock/kgsl_clock.c gpuclock/kgsl_busy.c)
|
||||
|
||||
add_library(termux SHARED termux/termux.c)
|
||||
|
||||
add_library(ddvenc SHARED venc/venc_server.cpp)
|
||||
target_compile_features(ddvenc PRIVATE cxx_std_17)
|
||||
target_link_libraries(ddvenc mediandk log)
|
||||
|
||||
# The optional proprietary SDK is supplied locally; its headers/libraries are not vendored.
|
||||
if(DROIDDECK_VITURE_SDK_DIR)
|
||||
add_library(droiddeck_viture SHARED viture/sdk_bridge.cpp)
|
||||
target_compile_features(droiddeck_viture PRIVATE cxx_std_17)
|
||||
|
||||
@@ -78,7 +78,6 @@ static constexpr uint8_t GAMEPAD_AXIS_COUNT = 8;
|
||||
static constexpr uint8_t GAMEPAD_BUTTON_COUNT = 11;
|
||||
static constexpr uint32_t FAKE_INPUT_RING_MAGIC = 0x46494252;
|
||||
static constexpr uint32_t FAKE_INPUT_RING_VERSION = 2;
|
||||
// Rings hold the 64-bit input_event layout that the arm64 writers use; 32-bit guests convert on read.
|
||||
struct RingEvent {
|
||||
int64_t sec;
|
||||
int64_t usec;
|
||||
@@ -93,6 +92,7 @@ static constexpr unsigned int FAKE_INPUT_MAJOR = 13;
|
||||
static constexpr unsigned int FAKE_INPUT_EVENT_MINOR_BASE = 64;
|
||||
static constexpr unsigned int FAKE_INPUT_JS_MINOR_BASE = 0;
|
||||
static constexpr int UINPUT_EVENT_BASE = 16;
|
||||
static constexpr int MOUSE_EVENT_SLOT = 4;
|
||||
static constexpr int UINPUT_EVENT_LIMIT = 64;
|
||||
static constexpr uint32_t UINPUT_DESCRIPTION_MAGIC = 0x46495544;
|
||||
|
||||
@@ -121,6 +121,12 @@ static constexpr size_t FAKE_INPUT_RING_HEADER_SIZE =
|
||||
static constexpr size_t FAKE_INPUT_RING_SIZE =
|
||||
FAKE_INPUT_RING_HEADER_SIZE +
|
||||
(FAKE_INPUT_RING_CAPACITY * FAKE_INPUT_EVENT_SIZE);
|
||||
static constexpr size_t DECK_IMU_BLOCK_SIZE = 64;
|
||||
static constexpr size_t FAKE_INPUT_RING_PAD_TYPE_OFFSET = 44;
|
||||
static constexpr uint32_t PAD_TYPE_DECK = 0, PAD_TYPE_STEAM = 1, PAD_TYPE_XBOX = 2, PAD_TYPE_DS4 = 3,
|
||||
PAD_TYPE_DUALSENSE = 4, PAD_TYPE_LAST = PAD_TYPE_DUALSENSE,
|
||||
PAD_TYPE_MOUSE = 5;
|
||||
static constexpr uint32_t PAD_TYPE_SET = 0x80000000u;
|
||||
|
||||
struct UinputDescription {
|
||||
uint32_t magic;
|
||||
@@ -149,6 +155,7 @@ struct FakeController {
|
||||
size_t mapping_size = 0;
|
||||
bool closed = false;
|
||||
bool needs_keyframe = true;
|
||||
bool mouse = false;
|
||||
|
||||
~FakeController() {
|
||||
if (ring) munmap(ring, mapping_size);
|
||||
@@ -383,7 +390,6 @@ send_vibration(int strong, int weak, uint16_t duration_ms, uint16_t slot) {
|
||||
syscall(SYS_close, sock);
|
||||
}
|
||||
|
||||
// Must match RumbleComponent.HOLD_MS: play until the slot's next effect or stop.
|
||||
static constexpr uint16_t RUMBLE_HOLD_MS = 0xffff;
|
||||
|
||||
__attribute__((visibility("hidden"))) static void send_ff_effect(const struct ff_effect &effect, uint16_t slot) {
|
||||
@@ -607,7 +613,7 @@ open_fake_input_ring(const char *event, int flags) {
|
||||
int slot = get_event_number(event);
|
||||
bool virtual_pad = slot >= UINPUT_EVENT_BASE;
|
||||
std::string ring_path = virtual_pad ? uinput_ring_path(slot) : get_ring_path_for_slot(slot);
|
||||
size_t mapping_size = virtual_pad ? UINPUT_FILE_SIZE : FAKE_INPUT_RING_SIZE;
|
||||
size_t mapping_size = virtual_pad ? UINPUT_FILE_SIZE : FAKE_INPUT_RING_SIZE + DECK_IMU_BLOCK_SIZE;
|
||||
if (ring_path.empty()) {
|
||||
Logger::log("No input ring is configured for %s (slot %d)\n", event, slot);
|
||||
errno = ENODEV;
|
||||
@@ -651,9 +657,22 @@ open_fake_input_ring(const char *event, int flags) {
|
||||
controller->uinput = description;
|
||||
controller->mapping_size = mapping_size;
|
||||
controller->generation = ring_generation(ring);
|
||||
if (!virtual_pad) {
|
||||
uint32_t pad_type = __atomic_load_n(
|
||||
reinterpret_cast<volatile uint32_t *>(static_cast<uint8_t *>(mapping) + FAKE_INPUT_RING_SIZE +
|
||||
FAKE_INPUT_RING_PAD_TYPE_OFFSET),
|
||||
__ATOMIC_ACQUIRE);
|
||||
controller->mouse = (pad_type & PAD_TYPE_SET) && (pad_type & ~PAD_TYPE_SET) == PAD_TYPE_MOUSE;
|
||||
}
|
||||
SnapshotState snap;
|
||||
if (read_snapshot(ring, snap) && snap.generation == controller->generation)
|
||||
capture_keyframe(*controller, snap);
|
||||
if (read_snapshot(ring, snap) && snap.generation == controller->generation) {
|
||||
if (controller->mouse) {
|
||||
controller->read_seq = snap.write_seq;
|
||||
controller->needs_keyframe = false;
|
||||
} else {
|
||||
capture_keyframe(*controller, snap);
|
||||
}
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> guard(controller_mutex());
|
||||
controller_map()[fd] = controller;
|
||||
@@ -1156,7 +1175,8 @@ struct DeckImu {
|
||||
uint32_t pad_type;
|
||||
uint32_t latency;
|
||||
};
|
||||
static_assert(offsetof(DeckImu, pad_type) == 44, "DeckImu::pad_type matches FakeInputWriter");
|
||||
static_assert(offsetof(DeckImu, pad_type) == FAKE_INPUT_RING_PAD_TYPE_OFFSET,
|
||||
"DeckImu::pad_type matches FakeInputWriter and the ring reader");
|
||||
static_assert(offsetof(DeckImu, latency) == 48, "DeckImu::latency matches FakeInputWriter");
|
||||
static constexpr uint32_t LATENCY_CONTROLLER = 1, LATENCY_TOUCH = 2;
|
||||
static constexpr int LOW_LATENCY_REPORT_INTERVAL_US = 1000;
|
||||
@@ -1173,7 +1193,6 @@ struct DeckExtras {
|
||||
uint32_t controls = 0;
|
||||
};
|
||||
static constexpr uint32_t DECK_IMU_MAGIC = 0x31554D49;
|
||||
static constexpr size_t DECK_IMU_BLOCK_SIZE = 64;
|
||||
static_assert(sizeof(DeckImu) <= DECK_IMU_BLOCK_SIZE, "the IMU block is 64 bytes in the ring file");
|
||||
|
||||
struct TritonSharedData {
|
||||
@@ -1222,7 +1241,6 @@ static constexpr int TRITON_REPORT_ID_BYTES = 1;
|
||||
static constexpr int TRITON_STATE_BYTES = 45;
|
||||
static constexpr int TRITON_REPORT_INTERVAL_US = 4000;
|
||||
static constexpr int TRITON_FEATURE_TIMEOUT_MS = 500;
|
||||
// The app clears output_length once it has taken a report; a writer waits this long for that before overwriting.
|
||||
static constexpr int TRITON_OUTPUT_TIMEOUT_MS = 50;
|
||||
static constexpr const char *TRITON_NAME = "Steam Controller";
|
||||
static constexpr const char *TRITON_SERIAL = "DROIDDECKSC01";
|
||||
@@ -1270,10 +1288,6 @@ static bool fake_deck_enabled() {
|
||||
return enabled == 1;
|
||||
}
|
||||
|
||||
static constexpr uint32_t PAD_TYPE_DECK = 0, PAD_TYPE_STEAM = 1, PAD_TYPE_XBOX = 2, PAD_TYPE_DS4 = 3,
|
||||
PAD_TYPE_DUALSENSE = 4, PAD_TYPE_LAST = PAD_TYPE_DUALSENSE;
|
||||
static constexpr uint32_t PAD_TYPE_SET = 0x80000000u;
|
||||
|
||||
__attribute__((visibility("hidden"))) static uint32_t session_pad_type() {
|
||||
static int type = -1;
|
||||
if (type < 0) {
|
||||
@@ -1408,6 +1422,12 @@ __attribute__((visibility("hidden"))) static bool is_withdrawn_pad_path(const ch
|
||||
if (strncmp(event, "event", 5) && strncmp(event, "js", 2)) return false;
|
||||
int number = get_event_number(event);
|
||||
if (number < 0 || number >= UINPUT_EVENT_BASE) return false;
|
||||
if (number == MOUSE_EVENT_SLOT && !strncmp(event, "event", 5)) {
|
||||
char *fake = from_real_to_fake_path(pathname);
|
||||
bool exposed = fake && path_exists(fake);
|
||||
free(fake);
|
||||
return !exposed;
|
||||
}
|
||||
return number == 0 || !process_is_steam_client();
|
||||
}
|
||||
|
||||
@@ -2650,9 +2670,6 @@ __attribute__((visibility("hidden"))) static int triton_get_feature(DeckHidraw &
|
||||
static constexpr uint32_t TRITON_HWID = 72;
|
||||
static constexpr uint32_t TRITON_FW_TIMESTAMP = 0x6AC686B3;
|
||||
|
||||
// Steam compares the controller's firmware with TRITON_FW_TS in its bundled hardwareupdater.cfg (and blocks
|
||||
// with a required update below MUST_UPDATE_TRITON_FW_TS), so the emulated pad reports at least the build
|
||||
// Steam ships.
|
||||
static uint32_t triton_fw_timestamp() {
|
||||
static const uint32_t timestamp = [] {
|
||||
std::vector<std::string> roots;
|
||||
@@ -3351,6 +3368,85 @@ static int copy_ioctl_bits(int op, void *destination, const unsigned char (&bits
|
||||
return static_cast<int>(size);
|
||||
}
|
||||
|
||||
static constexpr uint16_t MOUSE_VENDOR_ID = 0x1dd1;
|
||||
static constexpr uint16_t MOUSE_PRODUCT_ID = 0x0004;
|
||||
|
||||
static int ioctl_mouse(int op, void *argp) {
|
||||
int type = (op >> 8 & 0xFF);
|
||||
int number = (op >> 0 & 0xFF);
|
||||
if (type != 0x45) {
|
||||
errno = EINVAL;
|
||||
return -1;
|
||||
}
|
||||
switch (number) {
|
||||
case 0x01: {
|
||||
int version = 65536;
|
||||
memcpy(argp, &version, sizeof(int));
|
||||
return 0;
|
||||
}
|
||||
case 0x02: {
|
||||
struct input_id id;
|
||||
memset(&id, 0, sizeof(id));
|
||||
id.bustype = 0x03;
|
||||
id.vendor = MOUSE_VENDOR_ID;
|
||||
id.product = MOUSE_PRODUCT_ID;
|
||||
id.version = 1;
|
||||
memcpy(argp, &id, sizeof(id));
|
||||
return 0;
|
||||
}
|
||||
case 0x06:
|
||||
if (argp && _IOC_SIZE(op)) snprintf(static_cast<char *>(argp), _IOC_SIZE(op), "DroidDeck Mouse");
|
||||
return 0;
|
||||
case 0x07:
|
||||
if (argp && _IOC_SIZE(op)) snprintf(static_cast<char *>(argp), _IOC_SIZE(op), "usb-droiddeck/mouse");
|
||||
return 0;
|
||||
case 0x08:
|
||||
if (argp && _IOC_SIZE(op)) static_cast<char *>(argp)[0] = '\0';
|
||||
return 0;
|
||||
case 0x09: {
|
||||
unsigned char bitmask[(INPUT_PROP_MAX + 8) / 8] = {};
|
||||
bitmask[INPUT_PROP_POINTER / 8] |= 1 << (INPUT_PROP_POINTER % 8);
|
||||
return copy_ioctl_bits(op, argp, bitmask);
|
||||
}
|
||||
case 0x18: {
|
||||
unsigned char bitmask[(KEY_MAX + 8) / 8] = {};
|
||||
return copy_ioctl_bits(op, argp, bitmask);
|
||||
}
|
||||
case 0x20: {
|
||||
unsigned char bitmask[(EV_MAX + 8) / 8] = {};
|
||||
bitmask[EV_SYN / 8] |= 1 << (EV_SYN % 8);
|
||||
bitmask[EV_KEY / 8] |= 1 << (EV_KEY % 8);
|
||||
bitmask[EV_REL / 8] |= 1 << (EV_REL % 8);
|
||||
bitmask[EV_MSC / 8] |= 1 << (EV_MSC % 8);
|
||||
return copy_ioctl_bits(op, argp, bitmask);
|
||||
}
|
||||
case 0x21: {
|
||||
unsigned char bitmask[(KEY_MAX + 8) / 8] = {};
|
||||
for (int button = BTN_LEFT; button <= BTN_TASK; button++)
|
||||
if (button <= BTN_MIDDLE || button == BTN_SIDE || button == BTN_EXTRA)
|
||||
bitmask[button / 8] |= 1 << (button % 8);
|
||||
return copy_ioctl_bits(op, argp, bitmask);
|
||||
}
|
||||
case 0x22: {
|
||||
unsigned char bitmask[(REL_MAX + 8) / 8] = {};
|
||||
for (uint16_t code : {REL_X, REL_Y, REL_WHEEL, REL_HWHEEL, REL_WHEEL_HI_RES, REL_HWHEEL_HI_RES})
|
||||
bitmask[code / 8] |= 1 << (code % 8);
|
||||
return copy_ioctl_bits(op, argp, bitmask);
|
||||
}
|
||||
case 0x23: {
|
||||
unsigned char bitmask[(ABS_MAX + 8) / 8] = {};
|
||||
return copy_ioctl_bits(op, argp, bitmask);
|
||||
}
|
||||
case 0x35: {
|
||||
unsigned char bitmask[(FF_MAX + 8) / 8] = {};
|
||||
return copy_ioctl_bits(op, argp, bitmask);
|
||||
}
|
||||
default:
|
||||
errno = EINVAL;
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
static bool wait_snapshot(std::shared_ptr<FakeController> fake,
|
||||
std::unique_lock<std::recursive_mutex> &guard,
|
||||
SnapshotState &snap) {
|
||||
@@ -3417,6 +3513,13 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) {
|
||||
int event_number = controller->second->slot;
|
||||
const UinputDescription *made = controller->second->uinput;
|
||||
|
||||
if (controller->second->mouse) {
|
||||
int result = ioctl_mouse(op, argp);
|
||||
if (result >= 0) return result;
|
||||
guard.unlock();
|
||||
return forward_ioctl(fd, op, argp);
|
||||
}
|
||||
|
||||
if (type == 0x45 && number == 0x1) {
|
||||
Logger::log("Hooking ioctl EVIOCGVERSION for event %s\n", event);
|
||||
int version = 65536;
|
||||
@@ -3570,7 +3673,6 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) {
|
||||
Logger::log("Hooking ioctl EVIOCGRAB for event %s\n", event);
|
||||
return 0;
|
||||
} else if (type == 0x6A && !strncmp(event, "event", 5)) {
|
||||
// Older SDL2 builds treat any JSIOCGNAME answer as a joydev node and skip EVIOCGID, then drop the pad as 0000:0000.
|
||||
Logger::log("Rejecting joydev ioctl %d for event %s\n", number, event);
|
||||
guard.unlock();
|
||||
errno = EINVAL;
|
||||
@@ -3680,6 +3782,12 @@ static ssize_t read_input(int fd, void *buf, size_t count) {
|
||||
if (fake.needs_keyframe || snap.resync_seq != fake.resync_seq ||
|
||||
snap.write_seq < fake.read_seq ||
|
||||
snap.write_seq - fake.read_seq > FAKE_INPUT_RING_CAPACITY) {
|
||||
if (fake.mouse) {
|
||||
fake.read_seq = snap.write_seq;
|
||||
fake.resync_seq = snap.resync_seq;
|
||||
fake.needs_keyframe = false;
|
||||
continue;
|
||||
}
|
||||
capture_keyframe(fake, snap);
|
||||
} else {
|
||||
size_t events = std::min<uint64_t>(requested, snap.write_seq - fake.read_seq);
|
||||
|
||||
@@ -184,8 +184,9 @@ bool FrameGen::onResize(VkExtent2D extent, VkFormat , bool force) {
|
||||
VkExtent2D e = levelExtent(extent, l);
|
||||
if (!makeImage(pyrA_[l], e, VK_FORMAT_R32_SFLOAT, lumaUsage)) return false;
|
||||
if (!makeImage(pyrB_[l], e, VK_FORMAT_R32_SFLOAT, lumaUsage)) return false;
|
||||
if (!makeImage(flowLvl_[l], e, VK_FORMAT_R16G16B16A16_SFLOAT, flowUsage)) return false;
|
||||
}
|
||||
for (int l = flowFinest_; l < kLevels; ++l)
|
||||
if (!makeImage(flowLvl_[l], levelExtent(extent, l), VK_FORMAT_R16G16B16A16_SFLOAT, flowUsage)) return false;
|
||||
pyrAs_.resize(kLevels);
|
||||
for (int l = flowFinest_; l < kLevels; ++l)
|
||||
if (!makeImage(pyrAs_[l], levelExtent(extent, l), VK_FORMAT_R32_SFLOAT, lumaUsage)) return false;
|
||||
|
||||
@@ -267,8 +267,6 @@ void FrameGen::record(VkCommandBuffer cmd, VkImageView prevView, VkImageView cur
|
||||
pFlowReg_, flowRegA_, flowRegB_, gmSsbo_, kLevels, cfg_);
|
||||
}
|
||||
|
||||
// Every generation of one real frame is recorded into the same command buffer, so the flow
|
||||
// between prev and curr is computed once and each generation gets its own synth UBO and set.
|
||||
if (reuseFlow && !g_scratch.flowReady) return;
|
||||
if (!reuseFlow) {
|
||||
bool gmEngaged = updateGlobalMotion(gmSlot, extent_);
|
||||
@@ -439,7 +437,7 @@ static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev,
|
||||
makeUbo(dd, dev, mp, sizeof(FlowRegUBO), S.flowRegUbo, S.flowRegUboMem, S.flowRegUboPtr);
|
||||
if (S.flowRegUboPtr) { FlowRegUBO fu{cfg.frDt, cfg.frLambda, cfg.frEdge, cfg.frEps}; std::memcpy(S.flowRegUboPtr, &fu, sizeof(fu)); }
|
||||
S.flowUbo.resize(kLevels); S.flowUboMem.resize(kLevels); S.flowUboPtr.resize(kLevels);
|
||||
for (int l = 0; l < kLevels; ++l) {
|
||||
for (int l = fg->flowFinest(); l < kLevels; ++l) {
|
||||
makeUbo(dd, dev, mp, sizeof(FlowUBO), S.flowUbo[l], S.flowUboMem[l], S.flowUboPtr[l]);
|
||||
if (S.flowUboPtr[l]) { FlowUBO u{cfg.flowScale, (uint32_t)l, 0.6f, 1.6f}; std::memcpy(S.flowUboPtr[l], &u, sizeof(u)); }
|
||||
}
|
||||
@@ -464,13 +462,12 @@ static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev,
|
||||
}
|
||||
|
||||
S.sFlow.resize(kLevels);
|
||||
for (int l = 0; l < kLevels; ++l) {
|
||||
for (int l = fg->flowFinest(); l < kLevels; ++l) {
|
||||
S.sFlow[l] = allocSet(dd, dev, pool, pFlow.setLayout);
|
||||
int pred = (l + 1 < kLevels) ? l + 1 : l;
|
||||
VkImageView currLvl = (l >= fg->flowFinest()) ? pyrAs[l].view : pyrA[l].view;
|
||||
wUbo(dd, dev, S.sFlow[l], 0, S.flowUbo[l], sizeof(FlowUBO));
|
||||
wImg(dd, dev, S.sFlow[l], 32, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, pyrB[l].view, samp, GEN);
|
||||
wImg(dd, dev, S.sFlow[l], 33, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, currLvl, samp, GEN);
|
||||
wImg(dd, dev, S.sFlow[l], 33, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, pyrAs[l].view, samp, GEN);
|
||||
wImg(dd, dev, S.sFlow[l], 34, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, flowLvl[pred].view, samp, GEN);
|
||||
wImg(dd, dev, S.sFlow[l], 48, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, flowLvl[l].view, VK_NULL_HANDLE, GEN);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
// LSFG from Camille LaVey / the Eden Emulator Project, following upstream lsfg-vk (PancakeTAS).
|
||||
// Ported to WinNative and DroidDeck by @maxjivi05. GPL-3.0-or-later.
|
||||
// LSFG from Camille LaVey / the Eden Emulator Project, following upstream lsfg-vk (PancakeTAS). Ported to WinNative and DroidDeck by @maxjivi05. GPL-3.0-or-later.
|
||||
|
||||
#include "lsfg_dll.h"
|
||||
#include "lsfg_dxbc.h"
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
// LSFG from Camille LaVey / the Eden Emulator Project, following upstream lsfg-vk (PancakeTAS).
|
||||
// Ported to WinNative and DroidDeck by @maxjivi05. GPL-3.0-or-later.
|
||||
// LSFG from Camille LaVey / the Eden Emulator Project, following upstream lsfg-vk (PancakeTAS). Ported to WinNative and DroidDeck by @maxjivi05. GPL-3.0-or-later.
|
||||
|
||||
#pragma once
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
#pragma once
|
||||
// DXVK's dxbc subset is zlib licensed; vendored under cpp/thirdparty/dxbc.
|
||||
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
// Whole-GPU busy share without root on Adreno (KGSL) devices whose kgsl sysfs is blocked for apps: a thread
|
||||
// samples the memstore ringbuffer timestamps (kgsl_busy.h) once a millisecond while running.
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <pthread.h>
|
||||
#include <stdatomic.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <sys/mman.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "../adrenotools/src/hook/kgsl.h"
|
||||
#include "kgsl_busy.h"
|
||||
|
||||
#define SAMPLE_NS 1000000L
|
||||
|
||||
struct reader {
|
||||
int fd;
|
||||
void *map;
|
||||
size_t bytes;
|
||||
int first;
|
||||
uint32_t last[KGSL_BUSY_SLOTS];
|
||||
pthread_mutex_t lock;
|
||||
pthread_t thread;
|
||||
int thread_on;
|
||||
atomic_int run;
|
||||
atomic_uint_fast64_t busy, samples, moves;
|
||||
};
|
||||
|
||||
static void *sample_loop(void *arg) {
|
||||
struct reader *r = arg;
|
||||
const struct timespec gap = {0, SAMPLE_NS};
|
||||
while (atomic_load(&r->run)) {
|
||||
int moved = 0;
|
||||
int busy = kgsl_busy_sample(r->map, r->first, r->last, &moved);
|
||||
if (busy) atomic_fetch_add(&r->busy, 1);
|
||||
if (moved) atomic_fetch_add(&r->moves, 1);
|
||||
atomic_fetch_add(&r->samples, 1);
|
||||
nanosleep(&gap, NULL);
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void reader_run(struct reader *r, int on) {
|
||||
pthread_mutex_lock(&r->lock);
|
||||
if (on && !r->thread_on) {
|
||||
atomic_store(&r->run, 1);
|
||||
if (pthread_create(&r->thread, NULL, sample_loop, r) == 0) r->thread_on = 1;
|
||||
else atomic_store(&r->run, 0);
|
||||
} else if (!on && r->thread_on) {
|
||||
atomic_store(&r->run, 0);
|
||||
pthread_join(r->thread, NULL);
|
||||
r->thread_on = 0;
|
||||
}
|
||||
pthread_mutex_unlock(&r->lock);
|
||||
}
|
||||
|
||||
static void reader_close(struct reader *r) {
|
||||
if (!r) return;
|
||||
reader_run(r, 0);
|
||||
if (r->map && r->map != MAP_FAILED) munmap(r->map, r->bytes);
|
||||
if (r->fd >= 0) close(r->fd);
|
||||
pthread_mutex_destroy(&r->lock);
|
||||
free(r);
|
||||
}
|
||||
|
||||
// Returns 0 or a negative errno; *out is set on success.
|
||||
static int reader_open(struct reader **out) {
|
||||
struct reader *r = calloc(1, sizeof(*r));
|
||||
if (!r) return -ENOMEM;
|
||||
pthread_mutex_init(&r->lock, NULL);
|
||||
r->fd = open("/dev/kgsl-3d0", O_RDWR | O_CLOEXEC);
|
||||
if (r->fd < 0) { int e = -errno; reader_close(r); return e; }
|
||||
struct kgsl_shadowprop shadow;
|
||||
memset(&shadow, 0, sizeof(shadow));
|
||||
struct kgsl_device_getproperty prop = {.type = KGSL_PROP_DEVICE_SHADOW, .value = &shadow, .sizebytes = sizeof(shadow)};
|
||||
if (ioctl(r->fd, IOCTL_KGSL_DEVICE_GETPROPERTY, &prop)) { int e = -errno; reader_close(r); return e; }
|
||||
r->bytes = shadow.size;
|
||||
r->first = kgsl_busy_first_slot(shadow.size);
|
||||
if (r->first < 0) { reader_close(r); return -ERANGE; }
|
||||
r->map = mmap(NULL, r->bytes, PROT_READ, MAP_SHARED, r->fd, (off_t)shadow.gpuaddr);
|
||||
if (r->map == MAP_FAILED) { int e = -errno; reader_close(r); return e; }
|
||||
int moved = 0, started = 0;
|
||||
kgsl_busy_sample(r->map, r->first, r->last, &moved);
|
||||
for (int i = 0; i < KGSL_BUSY_SLOTS; i++) started |= r->last[i] != 0;
|
||||
if (!started) { reader_close(r); return -ENODATA; }
|
||||
*out = r;
|
||||
return 0;
|
||||
}
|
||||
|
||||
#ifndef KGSL_BUSY_NO_JNI
|
||||
#include <jni.h>
|
||||
|
||||
JNIEXPORT jlong JNICALL Java_com_droiddeck_launcher_session_KgslBusy_nativeOpen(JNIEnv *env, jclass cls, jintArray error) {
|
||||
struct reader *r = NULL;
|
||||
int e = reader_open(&r);
|
||||
if (e && error && (*env)->GetArrayLength(env, error) > 0) {
|
||||
jint v = e;
|
||||
(*env)->SetIntArrayRegion(env, error, 0, 1, &v);
|
||||
}
|
||||
return e ? 0 : (jlong)(intptr_t)r;
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_com_droiddeck_launcher_session_KgslBusy_nativeRun(JNIEnv *env, jclass cls, jlong handle, jboolean on) {
|
||||
if (handle) reader_run((struct reader *)(intptr_t)handle, on ? 1 : 0);
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL Java_com_droiddeck_launcher_session_KgslBusy_nativeRead(JNIEnv *env, jclass cls, jlong handle, jlongArray out) {
|
||||
if (!handle || !out || (*env)->GetArrayLength(env, out) < 3) return JNI_FALSE;
|
||||
struct reader *r = (struct reader *)(intptr_t)handle;
|
||||
jlong v[3] = {(jlong)atomic_load(&r->busy), (jlong)atomic_load(&r->samples), (jlong)atomic_load(&r->moves)};
|
||||
(*env)->SetLongArrayRegion(env, out, 0, 3, v);
|
||||
return JNI_TRUE;
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_com_droiddeck_launcher_session_KgslBusy_nativeClose(JNIEnv *env, jclass cls, jlong handle) {
|
||||
reader_close((struct reader *)(intptr_t)handle);
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,37 @@
|
||||
#ifndef DROIDDECK_KGSL_BUSY_H
|
||||
#define DROIDDECK_KGSL_BUSY_H
|
||||
// kgsl lets any client map its memstore read-only (KGSL_PROP_DEVICE_SHADOW). The CP writes a ringbuffer's
|
||||
// start-of-pipe timestamp there before each submission's command buffers and its end-of-pipe timestamp after them
|
||||
// (adreno_gen7_ringbuffer.c gen7_ringbuffer_addcmds), so start != end means that ringbuffer has work on the GPU.
|
||||
// Ringbuffer entries start at KGSL_MEMSTORE_MAX: entries - 2 - 4 levels, or entries - 1 - 4 on kernels without the
|
||||
// LPAC slot. Entries - 6 .. entries - 2 cover both; a context entry in that range follows the same start/end rule.
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#define KGSL_BUSY_ENTRY_WORDS 10
|
||||
#define KGSL_BUSY_SOP 0
|
||||
#define KGSL_BUSY_EOP 2
|
||||
#define KGSL_BUSY_SLOTS 5
|
||||
|
||||
static inline int kgsl_busy_first_slot(size_t bytes) {
|
||||
size_t entries = bytes / (KGSL_BUSY_ENTRY_WORDS * sizeof(uint32_t));
|
||||
return entries < 8 ? -1 : (int)(entries - 6);
|
||||
}
|
||||
|
||||
// 1 when a watched slot has a submission between its start and end timestamps. *moved is set when a start
|
||||
// timestamp differs from last[], which then holds the new ones.
|
||||
static inline int kgsl_busy_sample(const volatile uint32_t *memstore, int first, uint32_t last[KGSL_BUSY_SLOTS], int *moved) {
|
||||
int busy = 0;
|
||||
for (int i = 0; i < KGSL_BUSY_SLOTS; i++) {
|
||||
const volatile uint32_t *entry = memstore + (size_t)(first + i) * KGSL_BUSY_ENTRY_WORDS;
|
||||
uint32_t sop = entry[KGSL_BUSY_SOP], eop = entry[KGSL_BUSY_EOP];
|
||||
if (sop != eop) busy = 1;
|
||||
if (sop != last[i]) {
|
||||
*moved = 1;
|
||||
last[i] = sop;
|
||||
}
|
||||
}
|
||||
return busy;
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,156 @@
|
||||
// GPU clock without root on Adreno (KGSL) devices whose kgsl sysfs is blocked for apps.
|
||||
//
|
||||
// kgsl lets any app reserve a performance counter (IOCTL_KGSL_PERFCOUNTER_GET) but refuses to read it back while
|
||||
// /sys/class/kgsl/kgsl-3d0/perfcounter is 0, and clears the counters whenever the GPU switches to another process.
|
||||
// So the counter is read by the GPU itself: a small command buffer copies CP_ALWAYS_ON_COUNTER (19.2 MHz) and the
|
||||
// RBBM ALWAYS_COUNT counter (GPU core cycles) to memory, runs a block of NOP packets, and copies both again.
|
||||
// clock = cycles / always-on ticks * 19.2 MHz. Both reads sit in one command buffer, so a counter clear between
|
||||
// them only happens if the buffer is preempted; such samples fail the range checks and are dropped.
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdint.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <sys/mman.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "../adrenotools/src/hook/kgsl.h"
|
||||
|
||||
#define CP_TYPE7_PKT 0x70000000u
|
||||
#define CP_NOP 0x10u
|
||||
#define CP_REG_TO_MEM 0x3eu
|
||||
#define CP_ALWAYS_ON_COUNTER 0x980u
|
||||
#define RBBM_ALWAYS_COUNT 0u
|
||||
// gen7 CP protection marks registers 0x000-0x4ff readable by command buffers (adreno-gpulist.h); a counter
|
||||
// kgsl places anywhere else is not read.
|
||||
#define READABLE_LAST 0x4ffu
|
||||
#define XO_HZ 19200000.0
|
||||
#define NOP_DWORDS 0x3fffu
|
||||
#define NOP_BLOCKS 4
|
||||
|
||||
struct sampler {
|
||||
int fd;
|
||||
unsigned context;
|
||||
unsigned counter_reg;
|
||||
struct kgsl_gpumem_alloc_id ib, out;
|
||||
uint32_t *ib_map;
|
||||
volatile uint64_t *out_map;
|
||||
size_t ib_bytes;
|
||||
};
|
||||
|
||||
static unsigned odd_parity(unsigned v) {
|
||||
v ^= v >> 16;
|
||||
v ^= v >> 8;
|
||||
v ^= v >> 4;
|
||||
v &= 0xf;
|
||||
return (~0x6996u >> v) & 1u;
|
||||
}
|
||||
|
||||
static uint32_t pkt7(unsigned op, unsigned count) {
|
||||
return CP_TYPE7_PKT | count | odd_parity(count) << 15 | (op & 0x7f) << 16 | odd_parity(op) << 23;
|
||||
}
|
||||
|
||||
static void sampler_close(struct sampler *s) {
|
||||
if (!s) return;
|
||||
if (s->fd >= 0) {
|
||||
if (s->ib_map && s->ib_map != MAP_FAILED) munmap(s->ib_map, s->ib.mmapsize);
|
||||
if (s->out_map && s->out_map != MAP_FAILED) munmap((void *)s->out_map, s->out.mmapsize);
|
||||
if (s->ib.id) { struct kgsl_gpumem_free_id f = {.id = s->ib.id}; ioctl(s->fd, IOCTL_KGSL_GPUMEM_FREE_ID, &f); }
|
||||
if (s->out.id) { struct kgsl_gpumem_free_id f = {.id = s->out.id}; ioctl(s->fd, IOCTL_KGSL_GPUMEM_FREE_ID, &f); }
|
||||
if (s->context) { struct kgsl_drawctxt_destroy d = {.drawctxt_id = s->context}; ioctl(s->fd, IOCTL_KGSL_DRAWCTXT_DESTROY, &d); }
|
||||
if (s->counter_reg) {
|
||||
struct kgsl_perfcounter_put p = {.groupid = KGSL_PERFCOUNTER_GROUP_RBBM, .countable = RBBM_ALWAYS_COUNT};
|
||||
ioctl(s->fd, IOCTL_KGSL_PERFCOUNTER_PUT, &p);
|
||||
}
|
||||
close(s->fd);
|
||||
}
|
||||
free(s);
|
||||
}
|
||||
|
||||
static void emit_reads(struct sampler *s, size_t *n, unsigned pass) {
|
||||
const unsigned regs[2] = {CP_ALWAYS_ON_COUNTER, s->counter_reg};
|
||||
for (unsigned k = 0; k < 2; k++) {
|
||||
uint64_t dst = s->out.gpuaddr + (uint64_t)(pass * 2 + k) * sizeof(uint64_t);
|
||||
s->ib_map[(*n)++] = pkt7(CP_REG_TO_MEM, 3);
|
||||
s->ib_map[(*n)++] = regs[k] | (2u << 18) | (1u << 30); // two dwords, 64-bit read
|
||||
s->ib_map[(*n)++] = (uint32_t)dst;
|
||||
s->ib_map[(*n)++] = (uint32_t)(dst >> 32);
|
||||
}
|
||||
}
|
||||
|
||||
// Returns 0 or a negative errno; *out is set on success.
|
||||
static int sampler_open(struct sampler **out) {
|
||||
struct sampler *s = calloc(1, sizeof(*s));
|
||||
if (!s) return -ENOMEM;
|
||||
s->fd = open("/dev/kgsl-3d0", O_RDWR | O_CLOEXEC);
|
||||
if (s->fd < 0) { int e = -errno; s->fd = -1; sampler_close(s); return e; }
|
||||
struct kgsl_perfcounter_get get = {.groupid = KGSL_PERFCOUNTER_GROUP_RBBM, .countable = RBBM_ALWAYS_COUNT};
|
||||
if (ioctl(s->fd, IOCTL_KGSL_PERFCOUNTER_GET, &get)) { int e = -errno; sampler_close(s); return e; }
|
||||
s->counter_reg = get.offset;
|
||||
if (!get.offset || get.offset > READABLE_LAST) { sampler_close(s); return -ERANGE; }
|
||||
struct kgsl_drawctxt_create ctx = {.flags = KGSL_CONTEXT_NO_GMEM_ALLOC | KGSL_CONTEXT_PREAMBLE};
|
||||
if (ioctl(s->fd, IOCTL_KGSL_DRAWCTXT_CREATE, &ctx)) { int e = -errno; sampler_close(s); return e; }
|
||||
s->context = ctx.drawctxt_id;
|
||||
s->ib_bytes = (16 + NOP_BLOCKS * (NOP_DWORDS + 1)) * sizeof(uint32_t);
|
||||
s->ib.size = (s->ib_bytes + 4095) & ~(size_t)4095;
|
||||
s->out.size = 4096;
|
||||
if (ioctl(s->fd, IOCTL_KGSL_GPUMEM_ALLOC_ID, &s->ib)) { int e = -errno; s->ib.id = 0; sampler_close(s); return e; }
|
||||
if (ioctl(s->fd, IOCTL_KGSL_GPUMEM_ALLOC_ID, &s->out)) { int e = -errno; s->out.id = 0; sampler_close(s); return e; }
|
||||
s->ib_map = mmap(NULL, s->ib.mmapsize, PROT_READ | PROT_WRITE, MAP_SHARED, s->fd, (off_t)s->ib.id << 12);
|
||||
s->out_map = mmap(NULL, s->out.mmapsize, PROT_READ | PROT_WRITE, MAP_SHARED, s->fd, (off_t)s->out.id << 12);
|
||||
if (s->ib_map == MAP_FAILED || s->out_map == MAP_FAILED) { int e = -errno; sampler_close(s); return e; }
|
||||
size_t n = 0;
|
||||
emit_reads(s, &n, 0);
|
||||
for (unsigned b = 0; b < NOP_BLOCKS; b++) {
|
||||
s->ib_map[n++] = pkt7(CP_NOP, NOP_DWORDS);
|
||||
memset(&s->ib_map[n], 0, NOP_DWORDS * sizeof(uint32_t));
|
||||
n += NOP_DWORDS;
|
||||
}
|
||||
emit_reads(s, &n, 1);
|
||||
s->ib_bytes = n * sizeof(uint32_t);
|
||||
*out = s;
|
||||
return 0;
|
||||
}
|
||||
|
||||
// MHz, or a negative value: -errno from kgsl, or -1000 for a sample that failed the range checks.
|
||||
static int sampler_mhz(struct sampler *s) {
|
||||
for (int i = 0; i < 4; i++) s->out_map[i] = 0;
|
||||
struct kgsl_command_object cmd = {.gpuaddr = s->ib.gpuaddr, .size = s->ib_bytes, .flags = KGSL_CMDLIST_IB};
|
||||
struct kgsl_gpu_command submit = {
|
||||
.cmdlist = (uint64_t)(uintptr_t)&cmd, .cmdsize = sizeof(cmd), .numcmds = 1, .context_id = s->context,
|
||||
};
|
||||
if (ioctl(s->fd, IOCTL_KGSL_GPU_COMMAND, &submit)) return -errno;
|
||||
struct kgsl_device_waittimestamp_ctxtid wait = {.context_id = s->context, .timestamp = submit.timestamp, .timeout = 250};
|
||||
if (ioctl(s->fd, IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID, &wait)) return -errno;
|
||||
uint64_t xo0 = s->out_map[0], cyc0 = s->out_map[1], xo1 = s->out_map[2], cyc1 = s->out_map[3];
|
||||
if (xo1 <= xo0 || cyc1 <= cyc0) return -1000;
|
||||
uint64_t xo = xo1 - xo0, cycles = cyc1 - cyc0;
|
||||
// 5 us .. 50 ms of always-on time, and a clock between 50 MHz and 2 GHz.
|
||||
if (xo < 96 || xo > 960000) return -1000;
|
||||
double mhz = (double)cycles / (double)xo * XO_HZ / 1e6;
|
||||
if (mhz < 50 || mhz > 2000) return -1000;
|
||||
return (int)(mhz + 0.5);
|
||||
}
|
||||
|
||||
#ifndef KGSL_CLOCK_NO_JNI
|
||||
#include <jni.h>
|
||||
|
||||
JNIEXPORT jlong JNICALL Java_com_droiddeck_launcher_session_KgslClock_nativeOpen(JNIEnv *env, jclass cls, jintArray error) {
|
||||
struct sampler *s = NULL;
|
||||
int r = sampler_open(&s);
|
||||
if (r && error && (*env)->GetArrayLength(env, error) > 0) {
|
||||
jint e = r;
|
||||
(*env)->SetIntArrayRegion(env, error, 0, 1, &e);
|
||||
}
|
||||
return r ? 0 : (jlong)(intptr_t)s;
|
||||
}
|
||||
|
||||
JNIEXPORT jint JNICALL Java_com_droiddeck_launcher_session_KgslClock_nativeSample(JNIEnv *env, jclass cls, jlong handle) {
|
||||
return handle ? sampler_mhz((struct sampler *)(intptr_t)handle) : -EBADF;
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_com_droiddeck_launcher_session_KgslClock_nativeClose(JNIEnv *env, jclass cls, jlong handle) {
|
||||
sampler_close((struct sampler *)(intptr_t)handle);
|
||||
}
|
||||
#endif
|
||||
@@ -76,7 +76,6 @@ public:
|
||||
}
|
||||
lastFrame_ = frame.header.frame_id;
|
||||
if (state == XrGpuFrameState::Stale) {
|
||||
// No GPU read was submitted, so the producer can safely reclaim a dropped frame.
|
||||
dropped_++;
|
||||
if (!xr_gpu_send(peer_, &frame.header.frame_id, sizeof(frame.header.frame_id))) Disconnect();
|
||||
return false;
|
||||
@@ -88,7 +87,6 @@ public:
|
||||
glBindImageTexture(0, raw_, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA8);
|
||||
glDispatchCompute((width_ + 7) / 8, (height_ + 7) / 8, 1);
|
||||
glMemoryBarrier(GL_TEXTURE_FETCH_BARRIER_BIT | GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
|
||||
// The producer may overwrite this slot only after the native GPU has finished reading it.
|
||||
glFinish();
|
||||
if (glGetError() != GL_NO_ERROR) { rejected_++; Disconnect(); return false; }
|
||||
if (!xr_gpu_send(peer_, &frame.header.frame_id, sizeof(frame.header.frame_id))) Disconnect();
|
||||
|
||||
@@ -3,13 +3,9 @@
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
/* SOCK_SEQPACKET between the guest's Remote Play hooks and the app: the emulated /dev/video-enc0 and
|
||||
* MediaCodec encoder, and remote touches. A config carries the buffer memfds (inputs first) as SCM_RIGHTS;
|
||||
* every frame gets one reply, touches get none. */
|
||||
|
||||
#define VENC_MAX_BUFFERS 16
|
||||
|
||||
enum venc_msg { VENC_CONFIG = 1, VENC_FRAME = 2, VENC_DONE = 3, VENC_BITRATE = 4, VENC_TOUCH = 5 };
|
||||
enum venc_msg { VENC_CONFIG = 1, VENC_FRAME = 2, VENC_DONE = 3, VENC_BITRATE = 4, VENC_TOUCH = 5, VDEC_CONFIG = 6, VDEC_CAPTURE = 7, VDEC_PACKET = 8, VDEC_RESULT = 9 };
|
||||
enum venc_touch_action { VENC_TOUCH_DOWN = 0, VENC_TOUCH_MOVE = 1, VENC_TOUCH_UP = 2 };
|
||||
enum venc_codec { VENC_H264 = 0, VENC_HEVC = 1 };
|
||||
|
||||
@@ -45,11 +41,36 @@ struct venc_bitrate {
|
||||
uint32_t bitrate;
|
||||
};
|
||||
|
||||
/* Remote Play's touch-as-mouse turned back into a touch; x and y are fractions of the screen in 1/65535. */
|
||||
struct venc_touch {
|
||||
uint32_t type;
|
||||
uint32_t action;
|
||||
uint32_t x, y;
|
||||
};
|
||||
|
||||
struct vdec_config {
|
||||
uint32_t type;
|
||||
uint32_t codec;
|
||||
uint32_t width, height;
|
||||
uint32_t stride, rows;
|
||||
uint32_t bitstreams, bitstream_size;
|
||||
};
|
||||
|
||||
struct vdec_capture {
|
||||
uint32_t type;
|
||||
uint32_t index;
|
||||
uint32_t size;
|
||||
};
|
||||
|
||||
struct vdec_packet {
|
||||
uint32_t type;
|
||||
uint32_t input, bytes, capture;
|
||||
int64_t pts_us;
|
||||
};
|
||||
|
||||
struct vdec_result {
|
||||
uint32_t type;
|
||||
int32_t status;
|
||||
uint32_t frame;
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -3,6 +3,7 @@
|
||||
#include <jni.h>
|
||||
#include <media/NdkMediaCodec.h>
|
||||
#include <media/NdkMediaFormat.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/stat.h>
|
||||
@@ -11,6 +12,7 @@
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cerrno>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
@@ -31,8 +33,8 @@ struct Mapping {
|
||||
constexpr int32_t kColorFormatYuv420SemiPlanar = 21;
|
||||
constexpr uint32_t kBufferFlagKeyFrame = 1;
|
||||
constexpr uint32_t kBufferFlagCodecConfig = 2;
|
||||
constexpr int kTouchWidth = 1920, kTouchHeight = 1080; // InputSpace.kt
|
||||
constexpr int kRemoteTouchId = 31; // the compositor's last touch slot (MAX_TOUCH_POINTS 32)
|
||||
constexpr int kTouchWidth = 1920, kTouchHeight = 1080;
|
||||
constexpr int kRemoteTouchId = 31;
|
||||
|
||||
int32_t avc_profile(int32_t v4l2) {
|
||||
switch (v4l2) {
|
||||
@@ -45,6 +47,218 @@ int32_t avc_profile(int32_t v4l2) {
|
||||
}
|
||||
}
|
||||
|
||||
struct DmaBufSync {
|
||||
uint64_t flags;
|
||||
};
|
||||
constexpr unsigned long kDmaBufIoctlSync = _IOW('b', 0, DmaBufSync);
|
||||
constexpr uint64_t kDmaBufSyncWrite = 2, kDmaBufSyncStart = 0, kDmaBufSyncEnd = 4;
|
||||
constexpr int32_t kColorFormatYuv420Planar = 19;
|
||||
|
||||
class Decoder {
|
||||
public:
|
||||
~Decoder() { release(); }
|
||||
|
||||
void release() {
|
||||
if (codec_) {
|
||||
AMediaCodec_stop(codec_);
|
||||
AMediaCodec_delete(codec_);
|
||||
codec_ = nullptr;
|
||||
}
|
||||
if (bitstream_) munmap((void *)bitstream_, bitstream_size_);
|
||||
bitstream_ = nullptr;
|
||||
for (auto &c : captures_) drop(c);
|
||||
}
|
||||
|
||||
bool configure(const vdec_config &c, int fd) {
|
||||
release();
|
||||
if (c.width < 16 || c.height < 16 || c.stride < c.width || c.rows < c.height || c.bitstreams == 0 ||
|
||||
c.bitstreams > VENC_MAX_BUFFERS || c.bitstream_size == 0) {
|
||||
LOG("bad decoder config: %ux%u stride %u rows %u, %u bitstreams", c.width, c.height, c.stride, c.rows,
|
||||
c.bitstreams);
|
||||
return false;
|
||||
}
|
||||
bitstream_size_ = (size_t)c.bitstreams * c.bitstream_size;
|
||||
void *p = mmap(nullptr, bitstream_size_, PROT_READ, MAP_SHARED, fd, 0);
|
||||
if (p == MAP_FAILED) {
|
||||
LOG("could not map the bitstream buffers: %s", strerror(errno));
|
||||
return false;
|
||||
}
|
||||
bitstream_ = (const uint8_t *)p;
|
||||
config_ = c;
|
||||
codec_ = create(c, true);
|
||||
if (!codec_) codec_ = create(c, false);
|
||||
if (!codec_) {
|
||||
LOG("no %s decoder for %ux%u", c.codec == VENC_HEVC ? "HEVC" : "H.264", c.width, c.height);
|
||||
release();
|
||||
return false;
|
||||
}
|
||||
src_stride_ = (int32_t)c.width;
|
||||
src_rows_ = (int32_t)c.height;
|
||||
src_width_ = (int32_t)c.width;
|
||||
src_height_ = (int32_t)c.height;
|
||||
src_planar_ = false;
|
||||
shown_ = false;
|
||||
using GetName = media_status_t (*)(AMediaCodec *, char **);
|
||||
using ReleaseName = void (*)(AMediaCodec *, char *);
|
||||
static auto get_name = (GetName)dlsym(RTLD_DEFAULT, "AMediaCodec_getName");
|
||||
static auto release_name = (ReleaseName)dlsym(RTLD_DEFAULT, "AMediaCodec_releaseName");
|
||||
char *name = nullptr;
|
||||
if (get_name && get_name(codec_, &name) != AMEDIA_OK) name = nullptr;
|
||||
LOG("decoding %s %ux%u with %s", c.codec == VENC_HEVC ? "HEVC" : "H.264", c.width, c.height,
|
||||
name ? name : "MediaCodec");
|
||||
if (name && release_name) release_name(codec_, name);
|
||||
return true;
|
||||
}
|
||||
|
||||
void capture(const vdec_capture &c, int fd) {
|
||||
if (c.index >= VENC_MAX_BUFFERS) {
|
||||
close(fd);
|
||||
return;
|
||||
}
|
||||
Capture &cap = captures_[c.index];
|
||||
drop(cap);
|
||||
void *p = mmap(nullptr, c.size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
|
||||
if (p == MAP_FAILED) {
|
||||
LOG("could not map capture buffer %u: %s", c.index, strerror(errno));
|
||||
close(fd);
|
||||
return;
|
||||
}
|
||||
cap = {fd, (uint8_t *)p, c.size};
|
||||
}
|
||||
|
||||
bool decode(const vdec_packet &p, bool *frame) {
|
||||
*frame = false;
|
||||
if (!codec_ || p.capture >= VENC_MAX_BUFFERS || !captures_[p.capture].data || p.input >= config_.bitstreams ||
|
||||
p.bytes == 0 || p.bytes > config_.bitstream_size)
|
||||
return false;
|
||||
auto start = std::chrono::steady_clock::now();
|
||||
ssize_t in = AMediaCodec_dequeueInputBuffer(codec_, 20000);
|
||||
if (in < 0) return false;
|
||||
size_t capacity = 0;
|
||||
uint8_t *dst = AMediaCodec_getInputBuffer(codec_, (size_t)in, &capacity);
|
||||
if (!dst || capacity < p.bytes) {
|
||||
AMediaCodec_queueInputBuffer(codec_, (size_t)in, 0, 0, 0, 0);
|
||||
return false;
|
||||
}
|
||||
memcpy(dst, bitstream_ + (size_t)p.input * config_.bitstream_size, p.bytes);
|
||||
if (AMediaCodec_queueInputBuffer(codec_, (size_t)in, 0, p.bytes, (uint64_t)std::max<int64_t>(p.pts_us, 0), 0) !=
|
||||
AMEDIA_OK)
|
||||
return false;
|
||||
auto wait = std::chrono::milliseconds(shown_ ? 25 : 250);
|
||||
while (std::chrono::steady_clock::now() - start < wait) {
|
||||
AMediaCodecBufferInfo info;
|
||||
ssize_t o = AMediaCodec_dequeueOutputBuffer(codec_, &info, 2000);
|
||||
if (o == AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED) {
|
||||
read_format();
|
||||
continue;
|
||||
}
|
||||
if (o < 0) continue;
|
||||
size_t size = 0;
|
||||
uint8_t *data = AMediaCodec_getOutputBuffer(codec_, (size_t)o, &size);
|
||||
if (data && info.size > 0 && (size_t)info.offset + (size_t)info.size <= size)
|
||||
*frame = copy(data + info.offset, (size_t)info.size, captures_[p.capture]) || *frame;
|
||||
AMediaCodec_releaseOutputBuffer(codec_, (size_t)o, false);
|
||||
if (info.presentationTimeUs >= p.pts_us) break;
|
||||
}
|
||||
shown_ = shown_ || *frame;
|
||||
return true;
|
||||
}
|
||||
|
||||
private:
|
||||
struct Capture {
|
||||
int fd = -1;
|
||||
uint8_t *data = nullptr;
|
||||
size_t size = 0;
|
||||
};
|
||||
|
||||
static void drop(Capture &c) {
|
||||
if (c.data) munmap(c.data, c.size);
|
||||
if (c.fd >= 0) close(c.fd);
|
||||
c = Capture();
|
||||
}
|
||||
|
||||
AMediaCodec *create(const vdec_config &c, bool low_latency) {
|
||||
const char *mime = c.codec == VENC_HEVC ? "video/hevc" : "video/avc";
|
||||
AMediaCodec *codec = AMediaCodec_createDecoderByType(mime);
|
||||
if (!codec) return nullptr;
|
||||
AMediaFormat *f = AMediaFormat_new();
|
||||
AMediaFormat_setString(f, AMEDIAFORMAT_KEY_MIME, mime);
|
||||
AMediaFormat_setInt32(f, AMEDIAFORMAT_KEY_WIDTH, (int32_t)c.width);
|
||||
AMediaFormat_setInt32(f, AMEDIAFORMAT_KEY_HEIGHT, (int32_t)c.height);
|
||||
AMediaFormat_setInt32(f, AMEDIAFORMAT_KEY_COLOR_FORMAT, kColorFormatYuv420SemiPlanar);
|
||||
AMediaFormat_setInt32(f, AMEDIAFORMAT_KEY_MAX_INPUT_SIZE, (int32_t)c.bitstream_size);
|
||||
if (low_latency) {
|
||||
AMediaFormat_setInt32(f, "low-latency", 1);
|
||||
AMediaFormat_setInt32(f, "vendor.qti-ext-dec-low-latency.enable", 1);
|
||||
AMediaFormat_setInt32(f, "vendor.qti-ext-dec-picture-order.enable", 1);
|
||||
AMediaFormat_setInt32(f, "priority", 0);
|
||||
AMediaFormat_setFloat(f, "operating-rate", 120.0f);
|
||||
}
|
||||
media_status_t s = AMediaCodec_configure(codec, f, nullptr, nullptr, 0);
|
||||
AMediaFormat_delete(f);
|
||||
if (s == AMEDIA_OK) s = AMediaCodec_start(codec);
|
||||
if (s != AMEDIA_OK) {
|
||||
AMediaCodec_delete(codec);
|
||||
return nullptr;
|
||||
}
|
||||
return codec;
|
||||
}
|
||||
|
||||
void read_format() {
|
||||
AMediaFormat *f = AMediaCodec_getOutputFormat(codec_);
|
||||
if (!f) return;
|
||||
int32_t v;
|
||||
if (AMediaFormat_getInt32(f, AMEDIAFORMAT_KEY_WIDTH, &v) && v > 0) src_width_ = v;
|
||||
if (AMediaFormat_getInt32(f, AMEDIAFORMAT_KEY_HEIGHT, &v) && v > 0) src_height_ = v;
|
||||
src_stride_ = AMediaFormat_getInt32(f, "stride", &v) && v >= src_width_ ? v : src_width_;
|
||||
src_rows_ = AMediaFormat_getInt32(f, "slice-height", &v) && v >= src_height_ ? v : src_height_;
|
||||
src_planar_ = AMediaFormat_getInt32(f, AMEDIAFORMAT_KEY_COLOR_FORMAT, &v) && v == kColorFormatYuv420Planar;
|
||||
LOG("decoder output %dx%d stride %d rows %d %s", src_width_, src_height_, src_stride_, src_rows_,
|
||||
src_planar_ ? "planar" : "semi-planar");
|
||||
AMediaFormat_delete(f);
|
||||
}
|
||||
|
||||
bool copy(const uint8_t *src, size_t size, const Capture &cap) {
|
||||
size_t luma = (size_t)src_stride_ * src_rows_;
|
||||
size_t chroma = src_planar_ ? 2 * (size_t)(src_stride_ / 2) * (src_rows_ / 2) : (size_t)src_stride_ * (src_rows_ / 2);
|
||||
if (size < luma + chroma) return false;
|
||||
uint32_t w = std::min<uint32_t>((uint32_t)src_width_, config_.stride);
|
||||
uint32_t h = std::min<uint32_t>((uint32_t)src_height_, config_.rows);
|
||||
if ((size_t)config_.stride * config_.rows * 3 / 2 > cap.size) return false;
|
||||
DmaBufSync sync = {kDmaBufSyncStart | kDmaBufSyncWrite};
|
||||
ioctl(cap.fd, kDmaBufIoctlSync, &sync);
|
||||
uint8_t *y = cap.data, *uv = cap.data + (size_t)config_.stride * config_.rows;
|
||||
for (uint32_t row = 0; row < h; row++)
|
||||
memcpy(y + (size_t)row * config_.stride, src + (size_t)row * src_stride_, w);
|
||||
const uint8_t *su = src + luma;
|
||||
for (uint32_t row = 0; row < h / 2; row++) {
|
||||
uint8_t *d = uv + (size_t)row * config_.stride;
|
||||
if (!src_planar_) {
|
||||
memcpy(d, su + (size_t)row * src_stride_, w & ~1u);
|
||||
continue;
|
||||
}
|
||||
const uint8_t *u = su + (size_t)row * (src_stride_ / 2);
|
||||
const uint8_t *vv = su + (size_t)(src_stride_ / 2) * (src_rows_ / 2) + (size_t)row * (src_stride_ / 2);
|
||||
for (uint32_t x = 0; x < w / 2; x++) {
|
||||
d[2 * x] = u[x];
|
||||
d[2 * x + 1] = vv[x];
|
||||
}
|
||||
}
|
||||
sync.flags = kDmaBufSyncEnd | kDmaBufSyncWrite;
|
||||
ioctl(cap.fd, kDmaBufIoctlSync, &sync);
|
||||
return true;
|
||||
}
|
||||
|
||||
AMediaCodec *codec_ = nullptr;
|
||||
vdec_config config_ = {};
|
||||
const uint8_t *bitstream_ = nullptr;
|
||||
size_t bitstream_size_ = 0;
|
||||
Capture captures_[VENC_MAX_BUFFERS];
|
||||
int32_t src_width_ = 0, src_height_ = 0, src_stride_ = 0, src_rows_ = 0;
|
||||
bool src_planar_ = false;
|
||||
bool shown_ = false;
|
||||
};
|
||||
|
||||
class Session {
|
||||
public:
|
||||
explicit Session(int fd) : fd_(fd) {}
|
||||
@@ -85,6 +299,24 @@ public:
|
||||
memcpy(&b, buf, sizeof b);
|
||||
set_bitrate(b.bitrate);
|
||||
for (int i = 0; i < nfds; i++) close(fds[i]);
|
||||
} else if (type == VDEC_CONFIG && n == (ssize_t)sizeof(vdec_config)) {
|
||||
vdec_config c;
|
||||
memcpy(&c, buf, sizeof c);
|
||||
bool ok = nfds == 1 && decoder_.configure(c, fds[0]);
|
||||
for (int i = 0; i < nfds; i++) close(fds[i]);
|
||||
decoded(ok ? 0 : -1, false);
|
||||
} else if (type == VDEC_CAPTURE && n == (ssize_t)sizeof(vdec_capture)) {
|
||||
vdec_capture c;
|
||||
memcpy(&c, buf, sizeof c);
|
||||
if (nfds == 1) decoder_.capture(c, fds[0]);
|
||||
else for (int i = 0; i < nfds; i++) close(fds[i]);
|
||||
} else if (type == VDEC_PACKET && n == (ssize_t)sizeof(vdec_packet)) {
|
||||
vdec_packet p;
|
||||
memcpy(&p, buf, sizeof p);
|
||||
bool frame = false;
|
||||
bool ok = decoder_.decode(p, &frame);
|
||||
for (int i = 0; i < nfds; i++) close(fds[i]);
|
||||
decoded(ok ? 0 : -1, frame);
|
||||
} else {
|
||||
LOG("unexpected message %u of %zd bytes; closing", type, n);
|
||||
for (int i = 0; i < nfds; i++) close(fds[i]);
|
||||
@@ -117,7 +349,13 @@ private:
|
||||
send(fd_, &d, sizeof d, MSG_NOSIGNAL);
|
||||
}
|
||||
|
||||
void decoded(int32_t status, bool frame) {
|
||||
vdec_result r = {VDEC_RESULT, status, frame ? 1u : 0u};
|
||||
send(fd_, &r, sizeof r, MSG_NOSIGNAL);
|
||||
}
|
||||
|
||||
void release() {
|
||||
decoder_.release();
|
||||
if (codec_) {
|
||||
AMediaCodec_stop(codec_);
|
||||
AMediaCodec_delete(codec_);
|
||||
@@ -292,6 +530,7 @@ private:
|
||||
int32_t dst_stride_ = 0, dst_rows_ = 0;
|
||||
std::vector<Mapping> inputs_, outputs_;
|
||||
std::vector<uint8_t> header_;
|
||||
Decoder decoder_;
|
||||
};
|
||||
|
||||
std::atomic<int> g_listener{-1};
|
||||
@@ -310,7 +549,7 @@ void serve(int listener) {
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
}
|
||||
|
||||
extern "C" JNIEXPORT jboolean JNICALL
|
||||
Java_com_droiddeck_launcher_session_VideoEncodeBridge_nativeStart(JNIEnv *env, jobject, jstring jpath) {
|
||||
|
||||
@@ -1,20 +1,18 @@
|
||||
#pragma once
|
||||
|
||||
// Our controller uses the standard display-mode vocabulary, even for Beast.
|
||||
// Native mode reuses some numbers with different meanings; never pass them through.
|
||||
namespace droiddeck::viture {
|
||||
constexpr int to_native_mode(int standard) {
|
||||
switch (standard) {
|
||||
case 0x31: return 0x31; // 1080p 60
|
||||
case 0x33: return 0x32; // 1080p 90
|
||||
case 0x34: return 0x33; // 1080p 120
|
||||
case 0x32: return 0x37; // 1080p SBS 60
|
||||
case 0x35: return 0x38; // 1080p SBS 90
|
||||
case 0x41: return 0x34; // 1200p 60
|
||||
case 0x43: return 0x35; // 1200p 90
|
||||
case 0x44: return 0x36; // 1200p 120
|
||||
case 0x42: return 0x3a; // 1200p SBS 60
|
||||
case 0x45: return 0x3b; // 1200p SBS 90
|
||||
case 0x31: return 0x31;
|
||||
case 0x33: return 0x32;
|
||||
case 0x34: return 0x33;
|
||||
case 0x32: return 0x37;
|
||||
case 0x35: return 0x38;
|
||||
case 0x41: return 0x34;
|
||||
case 0x43: return 0x35;
|
||||
case 0x44: return 0x36;
|
||||
case 0x42: return 0x3a;
|
||||
case 0x45: return 0x3b;
|
||||
default: return -4;
|
||||
}
|
||||
}
|
||||
@@ -30,7 +28,7 @@ constexpr int from_native_mode(int native) {
|
||||
case 0x36: return 0x44;
|
||||
case 0x3a: return 0x42;
|
||||
case 0x3b: return 0x45;
|
||||
default: return -4; // Ultrawide is not stereo.
|
||||
default: return -4;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,6 @@
|
||||
inline std::size_t mjpeg_payload_size(const uint8_t* bytes, std::size_t size) {
|
||||
if (!bytes || size < 4 || size > 4*1024*1024 || bytes[0] != 0xff || bytes[1] != 0xd8) return 0;
|
||||
std::size_t end = size;
|
||||
// Luma Ultra UVC frames can pad the JPEG to an eight-byte boundary with zeros.
|
||||
while (end > 4 && size-end < 7 && bytes[end-1] == 0) --end;
|
||||
return bytes[end-2] == 0xff && bytes[end-1] == 0xd9 ? end : 0;
|
||||
}
|
||||
@@ -30,7 +30,6 @@
|
||||
#include "stereo_frame_gate.h"
|
||||
|
||||
namespace {
|
||||
// SDK callbacks have no user-data parameter. Only one provider may exist at a time.
|
||||
std::mutex api_mutex;
|
||||
std::mutex pose_mutex;
|
||||
std::array<float, 4> latest_pose{};
|
||||
@@ -64,7 +63,6 @@ void on_pose(float* data, uint64_t) {
|
||||
std::lock_guard<std::mutex> lock(pose_mutex);
|
||||
if (!accepting_pose) return;
|
||||
std::copy_n(data + 3, 4, latest_pose.begin());
|
||||
// SDK device ticks are not Android's elapsed-realtime clock.
|
||||
latest_time = now_ns();
|
||||
}
|
||||
|
||||
@@ -234,8 +232,6 @@ int set_display(Session& s, int standard) {
|
||||
if (mode == 0) {
|
||||
int rc = xr_device_provider_set_display_mode(s.device, standard);
|
||||
if (rc != VITURE_GLASSES_ERROR_NOT_SUPPORTED) return rc;
|
||||
// Older Beast firmware exposes fewer bypass modes. Fall back to its
|
||||
// separate native table only when the SDK explicitly rejects the mode.
|
||||
}
|
||||
const int native = droiddeck::viture::to_native_mode(standard);
|
||||
if (native < 0) return native;
|
||||
|
||||
@@ -8,6 +8,7 @@ add_library(droiddeckwayland SHARED
|
||||
src/sc_layer.c
|
||||
src/ahb_swapchain.c
|
||||
src/waylandcomp_jni.c
|
||||
src/gpu_clock_pin.c
|
||||
src/droiddeck_ext.c
|
||||
src/wl_dmabuf.c
|
||||
src/wl_clipboard.c
|
||||
@@ -17,6 +18,7 @@ add_library(droiddeckwayland SHARED
|
||||
src/wl_color_mgmt.c
|
||||
src/hdr_compose.c
|
||||
src/blend_pass.c
|
||||
src/gpu_busy.c
|
||||
generated/color-management-v1-protocol.c
|
||||
generated/xdg-shell-protocol.c
|
||||
generated/linux-dmabuf-v1-protocol.c
|
||||
@@ -32,6 +34,8 @@ add_library(droiddeckwayland SHARED
|
||||
generated/banner-ahb-v1-protocol.c
|
||||
src/framegen_bridge.c
|
||||
src/framegen_jni.c
|
||||
src/hudframes.c
|
||||
src/hudframes_jni.c
|
||||
)
|
||||
target_compile_options(droiddeckwayland PRIVATE
|
||||
$<$<COMPILE_LANGUAGE:C>:-Wall -Wextra -Wno-unused-parameter -Wno-missing-field-initializers>)
|
||||
@@ -40,6 +44,7 @@ target_include_directories(droiddeckwayland PRIVATE
|
||||
prebuilt/include
|
||||
src
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/../shaders
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/../../../../../tools/gpuload/src
|
||||
)
|
||||
|
||||
set(DROIDDECK_FRAMEGEN_LSFG_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../framegen/lsfg)
|
||||
@@ -94,4 +99,5 @@ target_link_libraries(droiddeckwayland
|
||||
dl
|
||||
log
|
||||
android
|
||||
nativewindow
|
||||
)
|
||||
@@ -371,8 +371,8 @@ void ahb_swapchain_set_mode(int on, int live) {
|
||||
: "; gralloc frames still in flight stay on the layer (or take the copy path) until then");
|
||||
else
|
||||
droiddeck_log("layer", "zero-copy: %s at launch (%s)", on ? "on" : "off",
|
||||
on ? "DROIDDECK_WAYLAND_ZERO_COPY=1: games present their own gralloc buffers on the display layer"
|
||||
: "the drawer's Zero-copy presentation switch turns it on live");
|
||||
on ? "HDR session: games present their own gralloc buffers on the display layer"
|
||||
: "only HDR sessions turn it on");
|
||||
if (live) wl_display_flush_clients(droiddeck_get_display());
|
||||
droiddeck_request_redraw();
|
||||
}
|
||||
|
||||
@@ -34,7 +34,6 @@ void cardboard_clamp(struct cardboard_params *p) {
|
||||
p->screen_width_m = clampf(p->screen_width_m, 0.2f, 60.0f);
|
||||
p->k1 = clampf(p->k1, -1.0f, 2.0f);
|
||||
p->k2 = clampf(p->k2, -1.0f, 2.0f);
|
||||
// Optical vertical FOV on supported glasses can be as low as ~22 degrees.
|
||||
p->fov_deg = clampf(p->fov_deg, 20.0f, 140.0f);
|
||||
p->lens_inset = clampf(p->lens_inset, -0.25f, 0.25f);
|
||||
p->chroma = clampf(p->chroma, 0.0f, 0.05f);
|
||||
@@ -186,6 +185,13 @@ int vkp_cardboard_active(void) {
|
||||
return on;
|
||||
}
|
||||
|
||||
int vkp_cardboard_source(void) {
|
||||
pthread_mutex_lock(&g_lock);
|
||||
const int source = g_set.enabled ? g_set.source : CARDBOARD_SOURCE_SCREEN;
|
||||
pthread_mutex_unlock(&g_lock);
|
||||
return source;
|
||||
}
|
||||
|
||||
int vkp_cardboard_pose_changed(void) {
|
||||
if (!g_changed) return 0;
|
||||
g_changed = 0;
|
||||
|
||||
@@ -27,6 +27,7 @@ void vkp_cardboard_set_render_height(int height);
|
||||
|
||||
void vkp_cardboard_bind_device(VkDevice dev, const VkPhysicalDeviceMemoryProperties *memprops);
|
||||
int vkp_cardboard_active(void);
|
||||
int vkp_cardboard_source(void);
|
||||
int vkp_cardboard_pose_changed(void);
|
||||
void vkp_cardboard_begin_frame(void);
|
||||
VkImage vkp_cardboard_run(VkCommandBuffer cmd, VkImage src, int src_w, int src_h, int out_w, int out_h);
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
// 1115.1.0
|
||||
#pragma once
|
||||
const uint32_t cardboard_frag_code[] = {
|
||||
0x07230203,0x00010000,0x0008000b,0x000001ba,0x00000000,0x00020011,0x00000001,0x0006000b,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -238,7 +238,7 @@ static int ensure_ring(uint32_t w, uint32_t h, VkFormat fmt, uint32_t n) {
|
||||
}
|
||||
g_ring_w = w; g_ring_h = h; g_ring_fmt = fmt;
|
||||
LOGD("framegen: generation ring %ux%u x%u", w, h, n);
|
||||
return 1;
|
||||
return 2;
|
||||
}
|
||||
|
||||
|
||||
@@ -350,6 +350,7 @@ int vkp_framegen_run(VkCommandBuffer cmd, VkImage scene, VkImageView scene_view,
|
||||
fge_configure((uint32_t)mult, (uint32_t)atomic_load(&g_target), flow, hz,
|
||||
atomic_load(&g_model), atomic_load(&g_preset));
|
||||
}
|
||||
const int size_changed = g_built_w != (uint32_t)w || g_built_h != (uint32_t)h || g_built_fmt != fmt;
|
||||
if (!fge_prepare((uint32_t)w, (uint32_t)h, fmt)) {
|
||||
if (fmt != VK_FORMAT_R8G8B8A8_UNORM && fge_unavailable()) {
|
||||
refuse_format(fmt, kind, w, h, "build its chain");
|
||||
@@ -361,20 +362,23 @@ int vkp_framegen_run(VkCommandBuffer cmd, VkImage scene, VkImageView scene_view,
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if (g_built_w != (uint32_t)w || g_built_h != (uint32_t)h || g_built_fmt != fmt) {
|
||||
if (size_changed) {
|
||||
g_built_w = (uint32_t)w; g_built_h = (uint32_t)h; g_built_fmt = fmt;
|
||||
g_generating_logged = 0;
|
||||
}
|
||||
uint32_t want = (uint32_t)(mult - 1);
|
||||
if (!ensure_ring((uint32_t)w, (uint32_t)h, fmt, want)) {
|
||||
const int ring = ensure_ring((uint32_t)w, (uint32_t)h, fmt, want);
|
||||
if (!ring) {
|
||||
if (fmt != VK_FORMAT_R8G8B8A8_UNORM) { refuse_format(fmt, kind, w, h, "make its generation ring"); return 0; }
|
||||
FGLOG("no memory for the generation ring (%dx%d x%u); frame generation stays off", w, h, want);
|
||||
mark_failed(kind);
|
||||
return 0;
|
||||
}
|
||||
if (size_changed || ring == 2) {
|
||||
FGLOG("frame generation catches up at %dx%d; this frame is shown as it is", w, h);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* The pacer's source rate must be the game's, not this loop's: a loop slowed by its own
|
||||
* generations would otherwise read as a slower game and justify even more generations. */
|
||||
++g_source_frames;
|
||||
const uint64_t game_frames = droiddeck_game_frames();
|
||||
uint32_t n_gen = fge_plan(g_ring_n, game_frames ? game_frames : g_source_frames, g_presented_rate);
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
#include "gpu_busy.h"
|
||||
|
||||
#include <jni.h>
|
||||
#include <pthread.h>
|
||||
#include <stdatomic.h>
|
||||
|
||||
#include "gpuload_ring.h"
|
||||
|
||||
static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static struct gpuload_vk g_v;
|
||||
static struct gpuload_ring g_ring;
|
||||
static uint32_t g_family, g_bits;
|
||||
static PFN_vkQueueSubmit g_submit;
|
||||
static int g_was_on;
|
||||
static _Atomic int g_on, g_lost, g_timing;
|
||||
static _Atomic uint64_t g_busy_ns;
|
||||
|
||||
static VkResult VKAPI_CALL timed_submit(VkQueue queue, uint32_t count, const VkSubmitInfo *infos, VkFence fence) {
|
||||
if (!count || !atomic_load(&g_on) || atomic_load(&g_lost)) return g_submit(queue, count, infos, fence);
|
||||
pthread_mutex_lock(&g_lock);
|
||||
if (!atomic_load(&g_on) || atomic_load(&g_lost)) {
|
||||
pthread_mutex_unlock(&g_lock);
|
||||
return g_submit(queue, count, infos, fence);
|
||||
}
|
||||
if (g_ring.state == 0 && gpuload_ring_setup(&g_ring, &g_v, g_family, g_bits)) atomic_store(&g_timing, 1);
|
||||
VkSubmitInfo *mine = NULL;
|
||||
uint32_t used = 0;
|
||||
if (g_ring.state == 1) {
|
||||
uint64_t ns = gpuload_ring_harvest(&g_ring, &g_v);
|
||||
if (g_was_on) atomic_fetch_add(&g_busy_ns, ns); // the first harvest after a pause holds work timed before it
|
||||
g_was_on = 1;
|
||||
mine = gpuload_ring_wrap(&g_ring, count, infos, &used);
|
||||
}
|
||||
VkResult r = g_submit(queue, count, mine ? mine : infos, fence);
|
||||
if (mine && r != VK_SUCCESS) gpuload_ring_unwind(&g_ring, used);
|
||||
pthread_mutex_unlock(&g_lock);
|
||||
free(mine);
|
||||
return r;
|
||||
}
|
||||
|
||||
void vkp_gpu_busy_device(VkPhysicalDevice pd, VkDevice dev, uint32_t family) {
|
||||
pthread_mutex_lock(&g_lock);
|
||||
memset(&g_ring, 0, sizeof(g_ring));
|
||||
g_was_on = 0;
|
||||
atomic_store(&g_timing, 0);
|
||||
atomic_store(&g_lost, 0);
|
||||
PFN_vkGetDeviceProcAddr gdpa = g_vk.GetDeviceProcAddr;
|
||||
g_v = (struct gpuload_vk){
|
||||
.device = dev,
|
||||
.create_pool = g_vk.CreateCommandPool,
|
||||
.destroy_pool = (PFN_vkDestroyCommandPool)gdpa(dev, "vkDestroyCommandPool"),
|
||||
.alloc_cmds = g_vk.AllocateCommandBuffers,
|
||||
.begin = g_vk.BeginCommandBuffer,
|
||||
.end = g_vk.EndCommandBuffer,
|
||||
.cmd_reset = (PFN_vkCmdResetQueryPool)gdpa(dev, "vkCmdResetQueryPool"),
|
||||
.cmd_timestamp = (PFN_vkCmdWriteTimestamp)gdpa(dev, "vkCmdWriteTimestamp"),
|
||||
.create_queries = (PFN_vkCreateQueryPool)gdpa(dev, "vkCreateQueryPool"),
|
||||
.destroy_queries = (PFN_vkDestroyQueryPool)gdpa(dev, "vkDestroyQueryPool"),
|
||||
.results = (PFN_vkGetQueryPoolResults)gdpa(dev, "vkGetQueryPoolResults"),
|
||||
};
|
||||
VkPhysicalDeviceProperties props;
|
||||
g_vk.GetPhysicalDeviceProperties(pd, &props);
|
||||
gpuload_vk_period(&g_v, props.limits.timestampPeriod);
|
||||
VkQueueFamilyProperties families[16];
|
||||
uint32_t n = 16;
|
||||
g_vk.GetPhysicalDeviceQueueFamilyProperties(pd, &n, families);
|
||||
g_family = family;
|
||||
g_bits = family < n ? families[family].timestampValidBits : 0;
|
||||
// vk_loader_load_device has just put the driver's function back.
|
||||
if (g_vk.QueueSubmit != timed_submit) g_submit = g_vk.QueueSubmit;
|
||||
if (g_submit) g_vk.QueueSubmit = timed_submit;
|
||||
pthread_mutex_unlock(&g_lock);
|
||||
}
|
||||
|
||||
void vkp_gpu_busy_device_lost(void) {
|
||||
atomic_store(&g_lost, 1);
|
||||
atomic_store(&g_timing, 0);
|
||||
}
|
||||
|
||||
JNIEXPORT jlong JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeGpuBusyNs(JNIEnv *env, jclass cls) {
|
||||
return atomic_load(&g_timing) ? (jlong)atomic_load(&g_busy_ns) : -1;
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetGpuTiming(JNIEnv *env, jclass cls, jboolean on) {
|
||||
pthread_mutex_lock(&g_lock);
|
||||
if (!on) g_was_on = 0;
|
||||
atomic_store(&g_on, on ? 1 : 0);
|
||||
pthread_mutex_unlock(&g_lock);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
#ifndef GPU_BUSY_H
|
||||
#define GPU_BUSY_H
|
||||
#include "vk_loader.h"
|
||||
|
||||
// Times the compositor's own GPU work for the HUD (tools/gpuload/src/gpuload_ring.h); call after the device and its
|
||||
// functions are loaded. Off until WaylandCompositor.nativeSetGpuTiming(true).
|
||||
void vkp_gpu_busy_device(VkPhysicalDevice pd, VkDevice dev, uint32_t family);
|
||||
void vkp_gpu_busy_device_lost(void);
|
||||
#endif
|
||||
@@ -0,0 +1,168 @@
|
||||
#include "gpu_clock_pin.h"
|
||||
|
||||
#include <android/log.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <pthread.h>
|
||||
#include <stdatomic.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <sys/mman.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "../../adrenotools/src/hook/kgsl.h"
|
||||
|
||||
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static pthread_t worker;
|
||||
static bool joinable;
|
||||
static atomic_bool running;
|
||||
|
||||
struct pin {
|
||||
int fd;
|
||||
unsigned int context;
|
||||
unsigned int memory;
|
||||
unsigned int timestamp;
|
||||
unsigned long gpuaddr;
|
||||
uint32_t nop;
|
||||
void *commands;
|
||||
size_t size;
|
||||
};
|
||||
|
||||
static struct pin pin = { .fd = -1 };
|
||||
|
||||
static void release_pin(void) {
|
||||
if (pin.context) {
|
||||
struct kgsl_drawctxt_destroy destroy = { .drawctxt_id = pin.context };
|
||||
ioctl(pin.fd, IOCTL_KGSL_DRAWCTXT_DESTROY, &destroy);
|
||||
}
|
||||
if (pin.commands) munmap(pin.commands, pin.size);
|
||||
if (pin.memory) {
|
||||
struct kgsl_gpumem_free_id free_memory = { .id = pin.memory };
|
||||
ioctl(pin.fd, IOCTL_KGSL_GPUMEM_FREE_ID, &free_memory);
|
||||
}
|
||||
if (pin.fd >= 0) close(pin.fd);
|
||||
pin = (struct pin) { .fd = -1 };
|
||||
}
|
||||
|
||||
static bool submit_pin(void) {
|
||||
struct kgsl_command_object object = {
|
||||
.gpuaddr = pin.gpuaddr,
|
||||
.size = 2 * sizeof(uint32_t),
|
||||
.flags = KGSL_CMDLIST_IB,
|
||||
.id = pin.memory,
|
||||
};
|
||||
struct kgsl_gpu_command command = {
|
||||
.flags = KGSL_CMDBATCH_PWR_CONSTRAINT,
|
||||
.cmdlist = (uintptr_t)&object,
|
||||
.cmdsize = sizeof(object),
|
||||
.numcmds = 1,
|
||||
.context_id = pin.context,
|
||||
};
|
||||
if (ioctl(pin.fd, IOCTL_KGSL_GPU_COMMAND, &command) < 0) return false;
|
||||
pin.timestamp = command.timestamp;
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool prepare_pin(void) {
|
||||
pin.fd = open("/dev/kgsl-3d0", O_RDWR | O_CLOEXEC);
|
||||
if (pin.fd < 0) return false;
|
||||
struct kgsl_devinfo info = {0};
|
||||
struct kgsl_device_getproperty device_info = {
|
||||
.type = KGSL_PROP_DEVICE_INFO, .value = &info, .sizebytes = sizeof(info),
|
||||
};
|
||||
if (ioctl(pin.fd, IOCTL_KGSL_DEVICE_GETPROPERTY, &device_info) < 0) return false;
|
||||
unsigned int core = info.chip_id >> 24;
|
||||
if (!core) core = info.gpu_id / 100;
|
||||
if (core < 3) { errno = ENODEV; return false; }
|
||||
pin.nop = core >= 5 ? 0x70100001 : 0xc0001000;
|
||||
struct kgsl_drawctxt_create context = {
|
||||
.flags = KGSL_CONTEXT_NO_GMEM_ALLOC | KGSL_CONTEXT_PREAMBLE | KGSL_CONTEXT_PWR_CONSTRAINT,
|
||||
};
|
||||
if (ioctl(pin.fd, IOCTL_KGSL_DRAWCTXT_CREATE, &context) < 0) return false;
|
||||
pin.context = context.drawctxt_id;
|
||||
struct kgsl_device_constraint_pwrlevel level = { .level = KGSL_CONSTRAINT_PWR_MAX };
|
||||
struct kgsl_device_constraint constraint = {
|
||||
.type = KGSL_CONSTRAINT_PWRLEVEL,
|
||||
.context_id = pin.context,
|
||||
.data = &level,
|
||||
.size = sizeof(level),
|
||||
};
|
||||
struct kgsl_device_getproperty property = {
|
||||
.type = KGSL_PROP_PWR_CONSTRAINT,
|
||||
.value = &constraint,
|
||||
.sizebytes = sizeof(constraint),
|
||||
};
|
||||
if (ioctl(pin.fd, IOCTL_KGSL_SETPROPERTY, &property) < 0) return false;
|
||||
struct kgsl_gpumem_alloc_id memory = { .size = 4096 };
|
||||
if (ioctl(pin.fd, IOCTL_KGSL_GPUMEM_ALLOC_ID, &memory) < 0) return false;
|
||||
pin.memory = memory.id;
|
||||
pin.gpuaddr = memory.gpuaddr;
|
||||
pin.size = memory.mmapsize;
|
||||
void *commands = mmap(NULL, pin.size, PROT_READ | PROT_WRITE, MAP_SHARED, pin.fd,
|
||||
(off_t)pin.memory << 12);
|
||||
if (commands == MAP_FAILED) return false;
|
||||
pin.commands = commands;
|
||||
uint32_t *words = commands;
|
||||
words[0] = pin.nop;
|
||||
words[1] = 0;
|
||||
struct kgsl_gpumem_sync_cache sync = { .id = pin.memory, .op = KGSL_GPUMEM_CACHE_CLEAN };
|
||||
if (ioctl(pin.fd, IOCTL_KGSL_GPUMEM_SYNC_CACHE, &sync) < 0) return false;
|
||||
return submit_pin();
|
||||
}
|
||||
|
||||
static void *hold_pin(void *unused) {
|
||||
(void)unused;
|
||||
while (atomic_load(&running)) {
|
||||
struct kgsl_device_waittimestamp_ctxtid wait = {
|
||||
.context_id = pin.context,
|
||||
.timestamp = pin.timestamp,
|
||||
.timeout = 100,
|
||||
};
|
||||
if (ioctl(pin.fd, IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID, &wait) < 0) {
|
||||
if (errno == EINTR || errno == ETIMEDOUT) continue;
|
||||
break;
|
||||
}
|
||||
usleep(25000);
|
||||
if (atomic_load(&running) && !submit_pin()) break;
|
||||
}
|
||||
if (atomic_exchange(&running, false))
|
||||
__android_log_print(ANDROID_LOG_WARN, "GpuClockPin", "constraint stopped: %s", strerror(errno));
|
||||
release_pin();
|
||||
return NULL;
|
||||
}
|
||||
|
||||
bool gpu_clock_pin_set(bool on) {
|
||||
pthread_mutex_lock(&lock);
|
||||
if (joinable) {
|
||||
if (on && atomic_load(&running)) {
|
||||
pthread_mutex_unlock(&lock);
|
||||
return true;
|
||||
}
|
||||
atomic_store(&running, false);
|
||||
pthread_join(worker, NULL);
|
||||
joinable = false;
|
||||
}
|
||||
bool ok = true;
|
||||
if (on) {
|
||||
ok = prepare_pin();
|
||||
if (ok) {
|
||||
atomic_store(&running, true);
|
||||
int error = pthread_create(&worker, NULL, hold_pin, NULL);
|
||||
if (error) {
|
||||
atomic_store(&running, false);
|
||||
errno = error;
|
||||
ok = false;
|
||||
} else {
|
||||
joinable = true;
|
||||
}
|
||||
}
|
||||
if (!ok) {
|
||||
int error = errno;
|
||||
release_pin();
|
||||
errno = error;
|
||||
}
|
||||
}
|
||||
pthread_mutex_unlock(&lock);
|
||||
return ok;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdbool.h>
|
||||
|
||||
bool gpu_clock_pin_set(bool on);
|
||||
@@ -24,7 +24,6 @@ struct droiddeck_headpose {
|
||||
float eye_aspect;
|
||||
uint32_t eye_w, eye_h;
|
||||
float display_hz;
|
||||
// Uses a formerly reserved word; older publishers leave this zero.
|
||||
uint32_t render_height;
|
||||
uint32_t reserved[10];
|
||||
};
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
#include <fcntl.h>
|
||||
#include <stdint.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "hudframes.h"
|
||||
|
||||
#define HUD_FRAMES_MAGIC 0x46484444u
|
||||
#define HUD_FRAMES_HEADER 128u
|
||||
#define HUD_FRAMES_ENTRY 16u
|
||||
|
||||
struct hud_frames {
|
||||
const uint8_t *map;
|
||||
size_t size;
|
||||
uint64_t seen;
|
||||
};
|
||||
|
||||
static uint32_t load32(const uint8_t *p) { return __atomic_load_n((const uint32_t *)p, __ATOMIC_ACQUIRE); }
|
||||
static uint64_t load64(const uint8_t *p) { return __atomic_load_n((const uint64_t *)p, __ATOMIC_ACQUIRE); }
|
||||
|
||||
struct hud_frames *hud_frames_open(const char *path) {
|
||||
int fd = open(path, O_RDONLY | O_CLOEXEC);
|
||||
if (fd < 0) return NULL;
|
||||
struct stat st;
|
||||
void *map = MAP_FAILED;
|
||||
if (fstat(fd, &st) == 0 && st.st_size >= (off_t)HUD_FRAMES_HEADER)
|
||||
map = mmap(NULL, (size_t)st.st_size, PROT_READ, MAP_SHARED, fd, 0);
|
||||
close(fd);
|
||||
if (map == MAP_FAILED) return NULL;
|
||||
struct hud_frames *h = calloc(1, sizeof(*h));
|
||||
if (!h) {
|
||||
munmap(map, (size_t)st.st_size);
|
||||
return NULL;
|
||||
}
|
||||
h->map = map;
|
||||
h->size = (size_t)st.st_size;
|
||||
return h;
|
||||
}
|
||||
|
||||
void hud_frames_close(struct hud_frames *h) {
|
||||
if (!h) return;
|
||||
munmap((void *)h->map, h->size);
|
||||
free(h);
|
||||
}
|
||||
|
||||
static uint32_t capacity(const struct hud_frames *h) {
|
||||
if (load32(h->map) != HUD_FRAMES_MAGIC) return 0;
|
||||
uint32_t cap;
|
||||
memcpy(&cap, h->map + 8, 4);
|
||||
if (cap == 0 || HUD_FRAMES_HEADER + (size_t)cap * HUD_FRAMES_ENTRY > h->size) return 0;
|
||||
return cap;
|
||||
}
|
||||
|
||||
int hud_frames_poll(struct hud_frames *h, int64_t *frametimes, int64_t *times, int max) {
|
||||
uint32_t cap = capacity(h);
|
||||
if (!cap || max <= 0) return -1;
|
||||
uint64_t count = load64(h->map + 16);
|
||||
if (count < h->seen) h->seen = 0;
|
||||
uint64_t from = h->seen;
|
||||
if (count - from > cap) from = count - cap;
|
||||
if (count - from > (uint64_t)max) from = count - (uint64_t)max;
|
||||
int n = 0;
|
||||
for (uint64_t i = from; i < count; i++, n++) {
|
||||
const uint8_t *e = h->map + HUD_FRAMES_HEADER + (i % cap) * HUD_FRAMES_ENTRY;
|
||||
memcpy(&frametimes[n], e, 8);
|
||||
memcpy(×[n], e + 8, 8);
|
||||
}
|
||||
uint64_t after = load64(h->map + 16);
|
||||
uint64_t valid = after > cap ? after - cap : 0;
|
||||
if (from < valid) {
|
||||
int skip = (int)(valid - from < (uint64_t)n ? valid - from : (uint64_t)n);
|
||||
memmove(frametimes, frametimes + skip, (size_t)(n - skip) * sizeof(int64_t));
|
||||
memmove(times, times + skip, (size_t)(n - skip) * sizeof(int64_t));
|
||||
n -= skip;
|
||||
}
|
||||
h->seen = count;
|
||||
return n;
|
||||
}
|
||||
|
||||
int hud_frames_info(const struct hud_frames *h, int32_t *info, char *engine, size_t engine_len) {
|
||||
if (!capacity(h) || engine_len == 0) return 0;
|
||||
for (int tries = 0; tries < 8; tries++) {
|
||||
uint32_t seq = load32(h->map + 24);
|
||||
if (seq & 1u) continue;
|
||||
memcpy(&info[0], h->map + 12, 4);
|
||||
memcpy(&info[1], h->map + 28, 16);
|
||||
size_t n = engine_len - 1 < 40 ? engine_len - 1 : 40;
|
||||
memcpy(engine, h->map + 44, n);
|
||||
engine[n] = '\0';
|
||||
__atomic_thread_fence(__ATOMIC_ACQUIRE);
|
||||
if (__atomic_load_n((const uint32_t *)(h->map + 24), __ATOMIC_RELAXED) == seq) return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
#ifndef DROIDDECK_HUDFRAMES_H
|
||||
#define DROIDDECK_HUDFRAMES_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
struct hud_frames;
|
||||
|
||||
struct hud_frames *hud_frames_open(const char *path);
|
||||
void hud_frames_close(struct hud_frames *h);
|
||||
int hud_frames_poll(struct hud_frames *h, int64_t *frametimes, int64_t *times, int max);
|
||||
int hud_frames_info(const struct hud_frames *h, int32_t *info, char *engine, size_t engine_len);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,55 @@
|
||||
#include <jni.h>
|
||||
#include <stdint.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
#include "hudframes.h"
|
||||
|
||||
JNIEXPORT jlong JNICALL
|
||||
Java_com_droiddeck_launcher_hud_HudFrames_nativeOpen(JNIEnv *env, jclass clazz, jstring path) {
|
||||
(void)clazz;
|
||||
const char *p = path ? (*env)->GetStringUTFChars(env, path, NULL) : NULL;
|
||||
if (!p) return 0;
|
||||
struct hud_frames *h = hud_frames_open(p);
|
||||
(*env)->ReleaseStringUTFChars(env, path, p);
|
||||
return (jlong)(intptr_t)h;
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_hud_HudFrames_nativeClose(JNIEnv *env, jclass clazz, jlong handle) {
|
||||
(void)env; (void)clazz;
|
||||
hud_frames_close((struct hud_frames *)(intptr_t)handle);
|
||||
}
|
||||
|
||||
JNIEXPORT jint JNICALL
|
||||
Java_com_droiddeck_launcher_hud_HudFrames_nativePoll(JNIEnv *env, jclass clazz, jlong handle,
|
||||
jlongArray frametimes, jlongArray times) {
|
||||
(void)clazz;
|
||||
struct hud_frames *h = (struct hud_frames *)(intptr_t)handle;
|
||||
if (!h || !frametimes || !times) return -1;
|
||||
jsize max = (*env)->GetArrayLength(env, frametimes);
|
||||
jsize max2 = (*env)->GetArrayLength(env, times);
|
||||
if (max2 < max) max = max2;
|
||||
if (max <= 0) return -1;
|
||||
int64_t *ft = malloc(sizeof(int64_t) * (size_t)max);
|
||||
int64_t *tm = malloc(sizeof(int64_t) * (size_t)max);
|
||||
int n = ft && tm ? hud_frames_poll(h, ft, tm, max) : -1;
|
||||
if (n > 0) {
|
||||
(*env)->SetLongArrayRegion(env, frametimes, 0, n, (const jlong *)ft);
|
||||
(*env)->SetLongArrayRegion(env, times, 0, n, (const jlong *)tm);
|
||||
}
|
||||
free(ft);
|
||||
free(tm);
|
||||
return n;
|
||||
}
|
||||
|
||||
JNIEXPORT jstring JNICALL
|
||||
Java_com_droiddeck_launcher_hud_HudFrames_nativeInfo(JNIEnv *env, jclass clazz, jlong handle, jintArray info) {
|
||||
(void)clazz;
|
||||
const struct hud_frames *h = (const struct hud_frames *)(intptr_t)handle;
|
||||
if (!h || !info || (*env)->GetArrayLength(env, info) < 5) return NULL;
|
||||
int32_t values[5];
|
||||
char engine[41];
|
||||
if (!hud_frames_info(h, values, engine, sizeof(engine))) return NULL;
|
||||
(*env)->SetIntArrayRegion(env, info, 0, 5, (const jint *)values);
|
||||
return (*env)->NewStringUTF(env, engine);
|
||||
}
|
||||
@@ -3,7 +3,6 @@
|
||||
#include <string.h>
|
||||
#include <strings.h>
|
||||
|
||||
/* Presentation only; this does not select a GPU driver or expand driver support. */
|
||||
static inline int quest_device_matches(const char *model, const char *device, const char *maker) {
|
||||
return !strcasecmp(model, "Quest 2") || !strcasecmp(model, "Quest 3") ||
|
||||
!strcasecmp(model, "Quest 3S") ||
|
||||
|
||||
@@ -291,7 +291,7 @@ int sc_layer_base_black(int width, int height) {
|
||||
ARect src = {0, 0, 16, 16}, dst = {0, 0, width, height};
|
||||
api.setBuffer(tx, g_base_sc, black, -1);
|
||||
api.setBufferTransparency(tx, g_base_sc, ASC_TRANSPARENCY_OPAQUE);
|
||||
api.setZOrder(tx, g_base_sc, 0); /* GAME = 1, OVERLAY = 2 */
|
||||
api.setZOrder(tx, g_base_sc, 0);
|
||||
api.setGeometry(tx, g_base_sc, &src, &dst, 0);
|
||||
api.setVisibility(tx, g_base_sc, ASC_VISIBILITY_SHOW);
|
||||
api.txApply(tx); api.txDelete(tx);
|
||||
@@ -973,7 +973,7 @@ void sc_layer_hide_overlay(void) {
|
||||
}
|
||||
|
||||
void sc_layer_window_gone(void) {
|
||||
base_hide(1); /* the backdrop belongs to the old window, just like GAME and OVERLAY */
|
||||
base_hide(1);
|
||||
if (api.state != 1) return;
|
||||
layers_init();
|
||||
for (int i = SC_LAYER_COUNT - 1; i >= 0; i--) retire_sc(&g_layers[i]);
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
X(BindImageMemory) X(DestroyImage) X(FreeMemory) X(AcquireNextImageKHR) \
|
||||
X(ResetCommandBuffer) X(BeginCommandBuffer) X(CmdPipelineBarrier) X(CmdBlitImage) \
|
||||
X(EndCommandBuffer) X(ResetFences) X(QueueSubmit) X(QueuePresentKHR) X(WaitForFences) \
|
||||
X(QueueWaitIdle) X(GetMemoryFdPropertiesKHR) \
|
||||
X(QueueWaitIdle) X(GetMemoryFdPropertiesKHR) X(GetAndroidHardwareBufferPropertiesANDROID) \
|
||||
X(GetImageSubresourceLayout) X(MapMemory) X(UnmapMemory) X(CmdClearColorImage) \
|
||||
\
|
||||
X(CreateShaderModule) X(DestroyShaderModule) X(CreatePipelineLayout) X(DestroyPipelineLayout) \
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
#include "framegen_bridge.h"
|
||||
#include "hdr_compose.h"
|
||||
#include "blend_pass.h"
|
||||
#include "gpu_busy.h"
|
||||
#include "droiddeck_color.h"
|
||||
#include "quest_device.h"
|
||||
#include <stdio.h>
|
||||
@@ -19,6 +20,7 @@
|
||||
#include <time.h>
|
||||
#include <pthread.h>
|
||||
#include <android/log.h>
|
||||
#include <android/hardware_buffer.h>
|
||||
|
||||
#define TAG "DroidDeckWayland"
|
||||
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__)
|
||||
@@ -39,6 +41,7 @@ struct vkp_image {
|
||||
};
|
||||
|
||||
static ANativeWindow *g_window;
|
||||
static int g_ahb_import;
|
||||
static char *g_driver_path, *g_library_name, *g_native_lib_dir;
|
||||
static int g_dev_state;
|
||||
static VkInstance g_inst;
|
||||
@@ -68,8 +71,6 @@ static int g_first_frame_done;
|
||||
static int g_base_black;
|
||||
|
||||
int vkp_quest_layer_presentation(void) {
|
||||
/* Compositor thread only; this is a process-wide device property, not a session setting.
|
||||
* Quest 2 still needs its separate A6xx driver: this gate only chooses presentation. */
|
||||
static int enabled = -1;
|
||||
if (enabled < 0) {
|
||||
char model[PROP_VALUE_MAX] = {0}, device[PROP_VALUE_MAX] = {0}, maker[PROP_VALUE_MAX] = {0};
|
||||
@@ -382,6 +383,13 @@ int vkp_output_to_scene(double ox, double oy, double *sx, double *sy) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
int vkp_scene_to_output(double sx, double sy, double *ox, double *oy) {
|
||||
if (!g_map.valid || g_map.kx <= 0 || g_map.ky <= 0) return 0;
|
||||
*ox = sx * g_map.kx + g_map.off_x;
|
||||
*oy = sy * g_map.ky + g_map.off_y;
|
||||
return 1;
|
||||
}
|
||||
|
||||
void vkp_output_size(int *w, int *h) {
|
||||
*w = (int)g_extent.width;
|
||||
*h = (int)g_extent.height;
|
||||
@@ -459,17 +467,18 @@ static int dev_init(void) {
|
||||
}
|
||||
g_vk.GetPhysicalDeviceMemoryProperties(g_pd, &g_memprops);
|
||||
|
||||
const char *dev_exts[7] = {VK_KHR_SWAPCHAIN_EXTENSION_NAME, "VK_KHR_external_memory_fd",
|
||||
"VK_EXT_external_memory_dma_buf", "VK_EXT_image_drm_format_modifier",
|
||||
"VK_KHR_image_format_list", NULL, NULL};
|
||||
uint32_t n_dev_exts = 5;
|
||||
static const char *const import_exts[4] = {"VK_KHR_external_memory_fd", "VK_EXT_external_memory_dma_buf",
|
||||
"VK_EXT_image_drm_format_modifier", "VK_KHR_image_format_list"};
|
||||
const char *dev_exts[9] = {VK_KHR_SWAPCHAIN_EXTENSION_NAME};
|
||||
uint32_t n_dev_exts = 1;
|
||||
uint32_t ne = 0;
|
||||
g_vk.EnumerateDeviceExtensionProperties(g_pd, NULL, &ne, NULL);
|
||||
VkExtensionProperties *exts = calloc(ne ? ne : 1, sizeof(*exts));
|
||||
g_vk.EnumerateDeviceExtensionProperties(g_pd, NULL, &ne, exts);
|
||||
for (unsigned i = 0; i < 5; i++)
|
||||
if (!has_ext(exts, ne, dev_exts[i]))
|
||||
LOGE("present: driver MISSING %s (dmabuf import will fail)", dev_exts[i]);
|
||||
for (unsigned i = 0; i < 4; i++) {
|
||||
if (has_ext(exts, ne, import_exts[i])) dev_exts[n_dev_exts++] = import_exts[i];
|
||||
else LOGE("present: driver MISSING %s (dmabuf import will fail)", import_exts[i]);
|
||||
}
|
||||
int want_hdr_md = 0;
|
||||
if (droiddeck_color_requested()) {
|
||||
want_hdr_md = has_ext(exts, ne, VK_EXT_HDR_METADATA_EXTENSION_NAME);
|
||||
@@ -477,6 +486,12 @@ static int dev_init(void) {
|
||||
}
|
||||
const int want_sem_fd = has_ext(exts, ne, VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME);
|
||||
if (want_sem_fd) dev_exts[n_dev_exts++] = VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME;
|
||||
g_ahb_import = has_ext(exts, ne, VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME) &&
|
||||
has_ext(exts, ne, VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME);
|
||||
if (g_ahb_import) {
|
||||
dev_exts[n_dev_exts++] = VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME;
|
||||
dev_exts[n_dev_exts++] = VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME;
|
||||
}
|
||||
free(exts);
|
||||
|
||||
float prio = 1.0f;
|
||||
@@ -499,6 +514,7 @@ static int dev_init(void) {
|
||||
}
|
||||
vk_loader_load_device(g_dev);
|
||||
g_vk.GetDeviceQueue(g_dev, g_qfam, 0, &g_queue);
|
||||
vkp_gpu_busy_device(g_pd, g_dev, g_qfam);
|
||||
if (want_sem_fd) {
|
||||
g_import_sem_fd = (PFN_vkImportSemaphoreFdKHR)g_vk.GetDeviceProcAddr(g_dev, "vkImportSemaphoreFdKHR");
|
||||
VkSemaphoreCreateInfo wsci = {.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO};
|
||||
@@ -987,6 +1003,60 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t
|
||||
return img;
|
||||
}
|
||||
|
||||
void vkp_wait_idle(void) {
|
||||
if (g_dev && g_vk.DeviceWaitIdle) g_vk.DeviceWaitIdle(g_dev);
|
||||
}
|
||||
|
||||
struct vkp_image *vkp_image_from_ahb(AHardwareBuffer *ahb) {
|
||||
if (!ahb || dev_init() != 0) return NULL;
|
||||
if (!g_ahb_import || !g_vk.GetAndroidHardwareBufferPropertiesANDROID) {
|
||||
static int said;
|
||||
if (!said) { said = 1; LOGE("ahb: the driver cannot import AHardwareBuffers (VK_ANDROID_external_memory_android_hardware_buffer)"); }
|
||||
return NULL;
|
||||
}
|
||||
AHardwareBuffer_Desc desc;
|
||||
AHardwareBuffer_describe(ahb, &desc);
|
||||
VkAndroidHardwareBufferFormatPropertiesANDROID fp = {
|
||||
.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_FORMAT_PROPERTIES_ANDROID};
|
||||
VkAndroidHardwareBufferPropertiesANDROID props = {
|
||||
.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID, .pNext = &fp};
|
||||
VkResult pr = g_vk.GetAndroidHardwareBufferPropertiesANDROID(g_dev, ahb, &props);
|
||||
if (pr != VK_SUCCESS || fp.format == VK_FORMAT_UNDEFINED) {
|
||||
LOGE("ahb: %ux%u format %u: properties %s, Vulkan format %d", desc.width, desc.height, desc.format,
|
||||
vk_result_name(pr), (int)fp.format);
|
||||
return NULL;
|
||||
}
|
||||
struct vkp_image *img = calloc(1, sizeof(*img));
|
||||
if (!img) return NULL;
|
||||
img->w = (int)desc.width; img->h = (int)desc.height; img->dmabuf = 1; img->fmt = fp.format; img->sampled = 1;
|
||||
VkExternalMemoryImageCreateInfo ext = {
|
||||
.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
|
||||
.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID};
|
||||
VkImageCreateInfo ici = {
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .pNext = &ext,
|
||||
.imageType = VK_IMAGE_TYPE_2D, .format = fp.format, .extent = {desc.width, desc.height, 1},
|
||||
.mipLevels = 1, .arrayLayers = 1, .samples = VK_SAMPLE_COUNT_1_BIT, .tiling = VK_IMAGE_TILING_OPTIMAL,
|
||||
.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT,
|
||||
.sharingMode = VK_SHARING_MODE_EXCLUSIVE, .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED};
|
||||
VkResult cr = g_vk.CreateImage(g_dev, &ici, NULL, &img->image);
|
||||
if (cr != VK_SUCCESS) { LOGE("ahb: vkCreateImage %ux%u -> %s", desc.width, desc.height, vk_result_name(cr)); free(img); return NULL; }
|
||||
int idx = -1;
|
||||
for (int i = 0; i < 32; i++) if (props.memoryTypeBits & (1u << i)) { idx = i; break; }
|
||||
VkImportAndroidHardwareBufferInfoANDROID imp = {
|
||||
.sType = VK_STRUCTURE_TYPE_IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID, .buffer = ahb};
|
||||
VkMemoryDedicatedAllocateInfo ded = {.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
|
||||
.pNext = &imp, .image = img->image};
|
||||
VkMemoryAllocateInfo mai = {.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, .pNext = &ded,
|
||||
.allocationSize = props.allocationSize, .memoryTypeIndex = (uint32_t)(idx < 0 ? 0 : idx)};
|
||||
VkResult mr = idx < 0 ? VK_ERROR_FEATURE_NOT_PRESENT : g_vk.AllocateMemory(g_dev, &mai, NULL, &img->mem);
|
||||
if (mr != VK_SUCCESS || g_vk.BindImageMemory(g_dev, img->image, img->mem, 0) != VK_SUCCESS) {
|
||||
LOGE("ahb: importing %ux%u -> %s", desc.width, desc.height, vk_result_name(mr));
|
||||
if (img->mem) g_vk.FreeMemory(g_dev, img->mem, NULL);
|
||||
g_vk.DestroyImage(g_dev, img->image, NULL); free(img); return NULL;
|
||||
}
|
||||
return img;
|
||||
}
|
||||
|
||||
static int shm_sampled(void) {
|
||||
static int known;
|
||||
if (!known) {
|
||||
@@ -1239,6 +1309,7 @@ static void device_lost(const char *where) {
|
||||
g_dev_state = -2;
|
||||
g_base_black = 0;
|
||||
vkp_framegen_device_lost();
|
||||
vkp_gpu_busy_device_lost();
|
||||
droiddeck_log("error", "GPU device lost (VK_ERROR_DEVICE_LOST in %s): the compositor has stopped presenting; "
|
||||
"restart the session", where);
|
||||
for (uint32_t i = 0; i < g_nimg; i++) blendp_forget_image(g_images[i]);
|
||||
@@ -1626,6 +1697,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
|
||||
VkImageLayout result_layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
|
||||
if (fx) {
|
||||
int mapped_w = (int)(scene_w * g_map.kx + 0.5f), mapped_h = (int)(scene_h * g_map.ky + 0.5f);
|
||||
if (fg) { mapped_w = scene_w; mapped_h = scene_h; }
|
||||
vkp_effects_set_formats(scene_fmt, scene_fmt);
|
||||
result = vkp_effects_run(cmd, scene_img, scene_w, scene_h, mapped_w, mapped_h, &rw, &rh);
|
||||
result_layout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
|
||||
@@ -1724,9 +1796,6 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
|
||||
|
||||
int vkp_render(int scene_w, int scene_h, const struct vkp_draw *draws, int n) {
|
||||
if (vkp_quest_layer_presentation() && !vkp_framegen_active() && !vkp_cardboard_active()) {
|
||||
/* The desktop (multiple windows), overlays and an empty scene must also avoid WSI.
|
||||
* Merely enabling zero-copy handles only a single fullscreen window and leaves both
|
||||
* the letterbox and every fallback frame going through the corrupted swapchain. */
|
||||
vkp_apply_window_request();
|
||||
sc_layer_hide_overlay();
|
||||
if (n > 0) {
|
||||
@@ -1738,9 +1807,6 @@ int vkp_render(int scene_w, int scene_h, const struct vkp_draw *draws, int n) {
|
||||
} else {
|
||||
sc_layer_hide();
|
||||
}
|
||||
/* sc_layer_present_pass signals only after submitting client content.
|
||||
* A backdrop alone, or a successful no-op while a layer slot is unavailable,
|
||||
* must not dismiss the app's loading UI or mark Steam's window as shown. */
|
||||
return vkp_base_black(scene_w, scene_h);
|
||||
}
|
||||
return render_impl(scene_w, scene_h, draws, n, NULL, NULL);
|
||||
@@ -1777,8 +1843,6 @@ void vkp_signal_first_frame(void) {
|
||||
int vkp_update_map(int scene_w, int scene_h) {
|
||||
if (g_dev_state == -2 || dev_init() != 0 || !g_window || scene_w <= 0 || scene_h <= 0) return -1;
|
||||
if (vkp_quest_layer_presentation()) {
|
||||
/* Layer geometry needs the window size, not a Vulkan swapchain. In particular, do
|
||||
* not create/present a swapchain just to paint black under an otherwise clean layer. */
|
||||
int w = ANativeWindow_getWidth(g_window), h = ANativeWindow_getHeight(g_window);
|
||||
if (w <= 0 || h <= 0) return -1;
|
||||
g_extent = (VkExtent2D){(uint32_t)w, (uint32_t)h};
|
||||
|
||||
@@ -16,6 +16,7 @@ enum vkp_align { VKP_ALIGN_CENTER = 0, VKP_ALIGN_TOP = 1, VKP_ALIGN_BOTTOM = 2,
|
||||
void vk_present_set_scale_mode(int mode, int alignment);
|
||||
int vkp_game_picture_rect(float rect[4]);
|
||||
int vkp_output_to_scene(double ox, double oy, double *sx, double *sy);
|
||||
int vkp_scene_to_output(double sx, double sy, double *ox, double *oy);
|
||||
void vkp_output_size(int *w, int *h);
|
||||
|
||||
struct vkp_image;
|
||||
@@ -34,6 +35,9 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t
|
||||
int vkp_image_is_dmabuf(const struct vkp_image *img);
|
||||
|
||||
struct vkp_image *vkp_image_create_shm(int w, int h);
|
||||
struct AHardwareBuffer;
|
||||
struct vkp_image *vkp_image_from_ahb(struct AHardwareBuffer *ahb);
|
||||
void vkp_wait_idle(void);
|
||||
void vkp_image_upload_shm(struct vkp_image *img, const void *data, int stride);
|
||||
|
||||
int vkp_image_width(const struct vkp_image *img);
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
#include <sys/resource.h>
|
||||
#include <android/log.h>
|
||||
#include <android/native_window_jni.h>
|
||||
#include <android/hardware_buffer_jni.h>
|
||||
#include "vk_present.h"
|
||||
#include "droiddeck_ext.h"
|
||||
#include "ahb_swapchain.h"
|
||||
@@ -16,6 +17,7 @@
|
||||
#include "effects_chain.h"
|
||||
#include "cardboard.h"
|
||||
#include "droiddeck_color.h"
|
||||
#include "gpu_clock_pin.h"
|
||||
|
||||
extern int droiddeck_wayland_run(void);
|
||||
extern void droiddeck_wayland_set_scale_mode(int mode, int alignment);
|
||||
@@ -23,12 +25,21 @@ extern void droiddeck_wayland_send_pointer(int action, int x, int y);
|
||||
extern void droiddeck_wayland_send_touch(int action, int pointer_id, int x, int y);
|
||||
extern int droiddeck_cursor_snapshot(int *out, int cap);
|
||||
extern int droiddeck_cursor_serial(void);
|
||||
extern int droiddeck_hud_frame_times(float *out, int len, int64_t *total);
|
||||
extern void droiddeck_wayland_send_key(int evdev, int state);
|
||||
extern int droiddeck_focus_takes_touch(void);
|
||||
extern int droiddeck_cursor_input_pos(int *x, int *y);
|
||||
extern void droiddeck_wayland_send_scene_input(int type, int a, int b);
|
||||
extern void droiddeck_wayland_set_cursor_composite(int on);
|
||||
extern void droiddeck_wayland_vsync(int64_t frame_time_ns);
|
||||
extern void droiddeck_stream_set(int on);
|
||||
extern void droiddeck_stream_frame(AHardwareBuffer *ahb);
|
||||
extern unsigned droiddeck_stream_frames(void);
|
||||
extern void droiddeck_wayland_output_resized(void);
|
||||
extern void droiddeck_wayland_set_output_refresh_rate(int mhz);
|
||||
extern volatile int g_fps_limit;
|
||||
extern volatile int g_release_unpaced;
|
||||
extern volatile int g_render_on_commit;
|
||||
extern volatile int g_hide_shell;
|
||||
extern volatile int g_zero_copy;
|
||||
extern volatile unsigned g_zero_copy_last;
|
||||
@@ -262,18 +273,58 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCursorSnapshot(
|
||||
return n;
|
||||
}
|
||||
|
||||
JNIEXPORT jlong JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeHudFrameTimes(JNIEnv *env, jclass clazz, jfloatArray out) {
|
||||
(void)clazz;
|
||||
if (!out) return 0;
|
||||
jint cap = (*env)->GetArrayLength(env, out);
|
||||
float *buf = cap > 0 ? malloc(sizeof(float) * (size_t)cap) : NULL;
|
||||
if (!buf) return 0;
|
||||
int64_t total = 0;
|
||||
int n = droiddeck_hud_frame_times(buf, cap, &total);
|
||||
if (n > 0) (*env)->SetFloatArrayRegion(env, out, 0, n, buf);
|
||||
free(buf);
|
||||
return (jlong)total;
|
||||
}
|
||||
|
||||
JNIEXPORT jint JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCursorSerial(JNIEnv *env, jclass clazz) {
|
||||
(void)env; (void)clazz;
|
||||
return droiddeck_cursor_serial();
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetCursorComposite(
|
||||
JNIEnv *env, jclass clazz, jboolean on) {
|
||||
(void)env; (void)clazz;
|
||||
droiddeck_wayland_set_cursor_composite(on ? 1 : 0);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSendKey(
|
||||
JNIEnv *env, jclass clazz, jint evdev, jint state) {
|
||||
droiddeck_wayland_send_key(evdev, state);
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeFocusTakesTouch(
|
||||
JNIEnv *env, jclass clazz) {
|
||||
(void)env; (void)clazz;
|
||||
return droiddeck_focus_takes_touch() ? JNI_TRUE : JNI_FALSE;
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCursorInputPos(
|
||||
JNIEnv *env, jclass clazz, jintArray out) {
|
||||
(void)clazz;
|
||||
if (!out || (*env)->GetArrayLength(env, out) < 2) return JNI_FALSE;
|
||||
int pos[2];
|
||||
if (!droiddeck_cursor_input_pos(&pos[0], &pos[1])) return JNI_FALSE;
|
||||
jint jpos[2] = {pos[0], pos[1]};
|
||||
(*env)->SetIntArrayRegion(env, out, 0, 2, jpos);
|
||||
return JNI_TRUE;
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSendSceneInput(
|
||||
JNIEnv *env, jclass clazz, jint type, jint a, jint b) {
|
||||
@@ -566,9 +617,16 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetLookName(JNIEnv *
|
||||
free(s);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetRenderOnCommit(JNIEnv *env, jclass clazz, jboolean on) {
|
||||
g_render_on_commit = on ? 1 : 0;
|
||||
__android_log_print(ANDROID_LOG_INFO, TAG, "render on commit %s", on ? "on" : "off");
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetFpsLimit(JNIEnv *env, jclass clazz, jint fps) {
|
||||
g_fps_limit = fps > 0 ? fps : 0;
|
||||
g_release_unpaced = fps < 0;
|
||||
__android_log_print(ANDROID_LOG_INFO, TAG, "fps limit %d", fps);
|
||||
}
|
||||
|
||||
@@ -634,8 +692,13 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeTextInputDelete(JNIE
|
||||
extern void adrenotools_set_turbo(bool turbo);
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetGpuTurbo(JNIEnv *env, jclass clazz, jboolean on) {
|
||||
(void)env; (void)clazz;
|
||||
adrenotools_set_turbo(on == JNI_TRUE);
|
||||
(void)clazz;
|
||||
if (!gpu_clock_pin_set(on == JNI_TRUE)) {
|
||||
int saved_errno = errno;
|
||||
jclass error = (*env)->FindClass(env, "java/lang/IllegalStateException");
|
||||
if (error) (*env)->ThrowNew(env, error, strerror(saved_errno));
|
||||
}
|
||||
if (on != JNI_TRUE) adrenotools_set_turbo(false);
|
||||
}
|
||||
|
||||
JNIEXPORT jint JNICALL
|
||||
@@ -660,3 +723,20 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetCardboardSpatialP
|
||||
(*env)->GetFloatArrayRegion(env, pos, 0, 3, p);
|
||||
vkp_cardboard_set_spatial_pose(m, p, live ? 1 : 0);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeStreamMode(JNIEnv *env, jclass clazz, jboolean on) {
|
||||
droiddeck_stream_set(on ? 1 : 0);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeStreamFrame(JNIEnv *env, jclass clazz, jobject hardwareBuffer) {
|
||||
if (!hardwareBuffer) return;
|
||||
AHardwareBuffer *ahb = AHardwareBuffer_fromHardwareBuffer(env, hardwareBuffer);
|
||||
if (ahb) droiddeck_stream_frame(ahb);
|
||||
}
|
||||
|
||||
JNIEXPORT jint JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeStreamFrames(JNIEnv *env, jclass clazz) {
|
||||
return (jint)droiddeck_stream_frames();
|
||||
}
|
||||
@@ -17,7 +17,8 @@ class App : Application() {
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
com.droiddeck.launcher.ui.Themes.loadGradient(this)
|
||||
// Helper processes must not initialize the main USB provider or guest graphics context.
|
||||
com.droiddeck.launcher.ui.BuildWatermark.install(this)
|
||||
HomeApp.trackRecents(this)
|
||||
val process = if (android.os.Build.VERSION.SDK_INT >= 28) Application.getProcessName()
|
||||
else (getSystemService(ACTIVITY_SERVICE) as android.app.ActivityManager)
|
||||
.runningAppProcesses?.firstOrNull { it.pid == android.os.Process.myPid() }?.processName
|
||||
@@ -25,9 +26,20 @@ class App : Application() {
|
||||
if (android.os.Build.VERSION.SDK_INT >= 28) android.webkit.WebView.setDataDirectorySuffix("xbox")
|
||||
return
|
||||
}
|
||||
if (process == "$packageName:vr_recovery" || process == "$packageName:rgb_diagnostic") return
|
||||
if (process == "$packageName:xboxcloud") {
|
||||
if (android.os.Build.VERSION.SDK_INT >= 28) android.webkit.WebView.setDataDirectorySuffix("xboxcloud")
|
||||
return
|
||||
}
|
||||
if (process == "$packageName:xcloudnative") {
|
||||
com.droiddeck.launcher.stores.StoresState.init(this)
|
||||
return
|
||||
}
|
||||
if (process == "$packageName:vr_recovery" || process == "$packageName:rgb_diagnostic" ||
|
||||
process == "$packageName:shortcuts_sync" || process == "$packageName:bottom_desktop") return
|
||||
CrashHandler.install(this)
|
||||
com.droiddeck.launcher.core.SteamIntegration.syncShortcutsListing(this)
|
||||
com.droiddeck.launcher.session.QuestExperimental.initialize(this)
|
||||
com.droiddeck.launcher.session.SessionPrefs.applyNtsyncDefault(this)
|
||||
com.droiddeck.launcher.session.SessionPrefs.settleGpuDriverMode(this)
|
||||
com.droiddeck.launcher.update.AppUpdates.init(this)
|
||||
com.droiddeck.launcher.core.DownloadSource.init(this)
|
||||
@@ -36,6 +48,7 @@ class App : Application() {
|
||||
com.droiddeck.launcher.glasses.Glasses.init(this)
|
||||
com.droiddeck.launcher.glasses.GlassesMenuMirror.initialize(this)
|
||||
BwrapSpawner.start(this)
|
||||
com.droiddeck.launcher.runtime.RootSpawner.start(this)
|
||||
com.droiddeck.launcher.frontend.GameFileSync.start(this)
|
||||
com.droiddeck.launcher.stores.StoresState.init(this)
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.gog.GogBackend)
|
||||
@@ -43,15 +56,16 @@ class App : Application() {
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.amazon.AmazonBackend)
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.itch.ItchBackend)
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.xbox.XboxBackend)
|
||||
com.droiddeck.launcher.sync.Syncthing.init(this)
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.battlenet.BattleNetBackend)
|
||||
}
|
||||
|
||||
/** Fetches the packs an existing setup already relies on, so the first use after an update does not wait. */
|
||||
private fun prefetchAddonPacks() {
|
||||
val app = this
|
||||
Thread({
|
||||
runCatching {
|
||||
if (com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app).isDirectory) {
|
||||
com.droiddeck.launcher.core.AddonPack.PROOT.ensure(app)
|
||||
if (!com.droiddeck.launcher.runtime.LinuxRuntime.patchedProot(app)) com.droiddeck.launcher.core.AddonPack.PROOT.ensure(app)
|
||||
com.droiddeck.launcher.core.AddonPack.DIRECTAUDIO.ensure(app)
|
||||
}
|
||||
if (com.droiddeck.launcher.stores.gog.GogComet.enabled(app)) com.droiddeck.launcher.core.AddonPack.COMET.ensure(app)
|
||||
|
||||
@@ -55,6 +55,8 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
private set
|
||||
private var runtimePending by mutableStateOf(false)
|
||||
private var sessionRunning by mutableStateOf(false)
|
||||
var tpUbwcMode: String by mutableStateOf(SessionPrefs.TP_UBWC_AUTO)
|
||||
private set
|
||||
|
||||
val uiMode: String get() = when (mode) {
|
||||
SessionPrefs.GPU_DRIVERS_AUTO -> GPU_MODE_AUTO
|
||||
@@ -73,8 +75,16 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
mode = uiMode, display = displaySlot(), runtime = runtimeSlot(),
|
||||
canRestart = !sessionRunning,
|
||||
checkedAt = TurnipReleases.cached(activity)?.checkedAt ?: 0L,
|
||||
tpUbwcMode = tpUbwcMode.takeIf { gpu.model == 740 },
|
||||
tpUbwcRestartRequired = com.droiddeck.launcher.gpu.TpUbwcHint.restartRequired(activity),
|
||||
)
|
||||
|
||||
fun chooseTpUbwcMode(mode: String) {
|
||||
if (gpu.model != 740) return
|
||||
SessionPrefs.setTpUbwcMode(activity, mode)
|
||||
tpUbwcMode = mode
|
||||
}
|
||||
|
||||
private fun slotSource(chosenDefault: Boolean, defaultLabel: Int): String = activity.getString(when {
|
||||
uiMode == GPU_MODE_AUTO -> R.string.gpu_src_auto
|
||||
uiMode == GPU_MODE_PAIR && pairRows.any { it.active } -> R.string.gpu_src_pair
|
||||
@@ -124,6 +134,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
var androidSelected by mutableStateOf("")
|
||||
|
||||
fun refreshDrivers() {
|
||||
tpUbwcMode = SessionPrefs.tpUbwcMode(activity)
|
||||
val lm = LinuxVulkanDriverManager(activity)
|
||||
fun origin(id: String) = if (TurnipReleases.isDownloaded(activity, id)) DriverRow.DOWNLOADED else DriverRow.IMPORTED
|
||||
val bundles = DriverBundle.all(activity)
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -13,7 +13,7 @@ class HomeActivity : Activity() {
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
requestedOrientation = com.droiddeck.launcher.session.SessionPrefs.orientation(this)
|
||||
requestedOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
|
||||
routeHome()
|
||||
}
|
||||
|
||||
|
||||
@@ -6,20 +6,41 @@ import android.graphics.Bitmap
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.ApplicationInfo
|
||||
import android.content.pm.LauncherApps
|
||||
import android.content.pm.ShortcutInfo
|
||||
import android.graphics.Rect
|
||||
import android.os.Process
|
||||
import android.os.UserHandle
|
||||
import android.os.UserManager
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.provider.Settings
|
||||
import androidx.core.graphics.drawable.toBitmap
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
object HomeApp {
|
||||
private const val ICON_DP = 72
|
||||
|
||||
data class LaunchableApp(
|
||||
val label: String,
|
||||
val packageName: String,
|
||||
val className: String,
|
||||
val icon: Bitmap?,
|
||||
)
|
||||
val system: Boolean = false,
|
||||
val game: Boolean = false,
|
||||
val installedAt: Long = 0L,
|
||||
val updatedAt: Long = 0L,
|
||||
val user: UserHandle? = null,
|
||||
val userSerial: Long = 0L,
|
||||
) {
|
||||
val component get() = ComponentName(packageName, className)
|
||||
val key get() = "$packageName/$className" + if (userSerial != 0L) "#$userSerial" else ""
|
||||
val work get() = userSerial != 0L
|
||||
}
|
||||
|
||||
fun isHomeScreenEnabled(context: Context): Boolean =
|
||||
context.packageManager.getComponentEnabledSetting(ComponentName(context, HomeActivity::class.java)) ==
|
||||
@@ -69,33 +90,134 @@ object HomeApp {
|
||||
fun settingsIntent(): Intent = Intent(Settings.ACTION_HOME_SETTINGS)
|
||||
|
||||
fun launchableApps(context: Context): List<LaunchableApp> {
|
||||
val launcher = context.getSystemService(LauncherApps::class.java)
|
||||
val users = context.getSystemService(UserManager::class.java)
|
||||
val pm = context.packageManager
|
||||
val launch = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)
|
||||
val apps = pm.queryIntentActivities(launch, 0)
|
||||
.asSequence()
|
||||
.mapNotNull { result ->
|
||||
val activity = result.activityInfo ?: return@mapNotNull null
|
||||
if (!activity.exported || activity.packageName == context.packageName) return@mapNotNull null
|
||||
val label = result.loadLabel(pm)?.toString()?.trim().orEmpty().ifEmpty { activity.packageName }
|
||||
val icon = runCatching { result.loadIcon(pm).toBitmap(48, 48) }.getOrNull()
|
||||
LaunchableApp(label, activity.packageName, activity.name, icon)
|
||||
val own = Process.myUserHandle()
|
||||
val iconPx = (ICON_DP * context.resources.displayMetrics.density).roundToInt()
|
||||
val apps = users.userProfiles.flatMap { user ->
|
||||
val serial = if (user == own) 0L else users.getSerialNumberForUser(user)
|
||||
runCatching { launcher.getActivityList(null, user) }.getOrDefault(emptyList()).mapNotNull { info ->
|
||||
val component = info.componentName
|
||||
if (component.packageName == context.packageName && user == own) return@mapNotNull null
|
||||
val label = info.label?.toString()?.trim().orEmpty().ifEmpty { component.packageName }
|
||||
val icon = runCatching { info.getBadgedIcon(0).toBitmap(iconPx, iconPx) }.getOrNull()
|
||||
val app = info.applicationInfo
|
||||
val updated = if (user == own) runCatching { pm.getPackageInfo(component.packageName, 0).lastUpdateTime }.getOrNull() else null
|
||||
@Suppress("DEPRECATION")
|
||||
val game = app.category == ApplicationInfo.CATEGORY_GAME || app.flags and ApplicationInfo.FLAG_IS_GAME != 0
|
||||
LaunchableApp(
|
||||
label, component.packageName, component.className, icon,
|
||||
system = app.flags and (ApplicationInfo.FLAG_SYSTEM or ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0,
|
||||
game = game,
|
||||
installedAt = info.firstInstallTime,
|
||||
updatedAt = updated ?: info.firstInstallTime,
|
||||
user = user,
|
||||
userSerial = serial,
|
||||
)
|
||||
}
|
||||
.distinctBy { it.packageName }
|
||||
.toList()
|
||||
return apps.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label })
|
||||
}
|
||||
return apps.distinctBy { it.key }.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label })
|
||||
}
|
||||
|
||||
fun launch(context: Context, app: LaunchableApp, displayId: Int? = null) {
|
||||
val intent = Intent(Intent.ACTION_MAIN)
|
||||
.addCategory(Intent.CATEGORY_LAUNCHER)
|
||||
.setComponent(ComponentName(app.packageName, app.className))
|
||||
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
if (displayId == null) {
|
||||
context.startActivity(intent)
|
||||
return
|
||||
fun launch(context: Context, app: LaunchableApp, displayId: Int? = null, bounds: Rect? = null) {
|
||||
val options = displayId?.let { ActivityOptions.makeBasic().setLaunchDisplayId(it).toBundle() }
|
||||
val launcher = context.getSystemService(LauncherApps::class.java)
|
||||
launcher.startMainActivity(app.component, app.user ?: Process.myUserHandle(), bounds, options)
|
||||
}
|
||||
|
||||
fun canUseShortcuts(context: Context): Boolean =
|
||||
runCatching { context.getSystemService(LauncherApps::class.java).hasShortcutHostPermission() }.getOrDefault(false)
|
||||
|
||||
fun shortcuts(context: Context, app: LaunchableApp): List<ShortcutInfo> {
|
||||
if (!canUseShortcuts(context)) return emptyList()
|
||||
val query = LauncherApps.ShortcutQuery()
|
||||
.setPackage(app.packageName)
|
||||
.setActivity(app.component)
|
||||
.setQueryFlags(LauncherApps.ShortcutQuery.FLAG_MATCH_DYNAMIC or LauncherApps.ShortcutQuery.FLAG_MATCH_MANIFEST)
|
||||
return runCatching { context.getSystemService(LauncherApps::class.java).getShortcuts(query, app.user ?: Process.myUserHandle()) }
|
||||
.getOrNull().orEmpty()
|
||||
.filter { it.isEnabled }
|
||||
.sortedWith(compareBy<ShortcutInfo> { if (it.isDeclaredInManifest) 0 else 1 }.thenBy { it.rank })
|
||||
.take(5)
|
||||
}
|
||||
|
||||
fun shortcutIcon(context: Context, info: ShortcutInfo, px: Int = (ICON_DP * context.resources.displayMetrics.density).roundToInt()): Bitmap? = runCatching {
|
||||
context.getSystemService(LauncherApps::class.java)
|
||||
.getShortcutIconDrawable(info, context.resources.displayMetrics.densityDpi)?.toBitmap(px, px)
|
||||
}.getOrNull()
|
||||
|
||||
fun trackRecents(app: android.app.Application) {
|
||||
app.registerActivityLifecycleCallbacks(object : android.app.Application.ActivityLifecycleCallbacks {
|
||||
override fun onActivityCreated(activity: android.app.Activity, savedInstanceState: android.os.Bundle?) = Unit
|
||||
override fun onActivityStarted(activity: android.app.Activity) = Unit
|
||||
override fun onActivityResumed(activity: android.app.Activity) = syncRecents(activity)
|
||||
override fun onActivityPaused(activity: android.app.Activity) { if (activity is FrontEndActivity) syncRecents(activity) }
|
||||
override fun onActivityStopped(activity: android.app.Activity) = Unit
|
||||
override fun onActivitySaveInstanceState(activity: android.app.Activity, outState: android.os.Bundle) = Unit
|
||||
override fun onActivityDestroyed(activity: android.app.Activity) = Unit
|
||||
})
|
||||
}
|
||||
|
||||
private fun syncRecents(activity: android.app.Activity) =
|
||||
keepOutOfRecents(activity, activity is FrontEndActivity && !SessionState.running && isDefault(activity))
|
||||
|
||||
internal enum class RecentsStep { HIDE, SHOW, FORGET, NONE }
|
||||
|
||||
internal fun recentsStep(hidden: Boolean, owned: Boolean, excluded: Boolean): RecentsStep = when {
|
||||
hidden && !excluded -> RecentsStep.HIDE
|
||||
!hidden && owned && excluded -> RecentsStep.SHOW
|
||||
!hidden && owned -> RecentsStep.FORGET
|
||||
else -> RecentsStep.NONE
|
||||
}
|
||||
|
||||
fun keepOutOfRecents(activity: android.app.Activity, hidden: Boolean) {
|
||||
val prefs = activity.getSharedPreferences("home-recents", Context.MODE_PRIVATE)
|
||||
val owned = prefs.getStringSet("tasks", null).orEmpty()
|
||||
val id = activity.taskId.toString()
|
||||
if (!hidden && id !in owned) return
|
||||
runCatching {
|
||||
@Suppress("DEPRECATION")
|
||||
fun idOf(task: android.app.ActivityManager.AppTask) =
|
||||
task.taskInfo?.let { if (Build.VERSION.SDK_INT >= 29) it.taskId else it.persistentId } ?: -1
|
||||
val tasks = activity.getSystemService(android.app.ActivityManager::class.java).appTasks
|
||||
val task = tasks.firstOrNull { idOf(it) == activity.taskId } ?: return
|
||||
val baseIntent = task.taskInfo?.baseIntent ?: return@runCatching
|
||||
val excluded = baseIntent.flags and Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS != 0
|
||||
val step = recentsStep(hidden, id in owned, excluded)
|
||||
if (step == RecentsStep.NONE) return
|
||||
if (step != RecentsStep.FORGET) task.setExcludeFromRecents(step == RecentsStep.HIDE)
|
||||
val live = tasks.map { idOf(it).toString() }.toSet()
|
||||
val next = owned.filter { it in live && it != id }.toMutableSet()
|
||||
if (step == RecentsStep.HIDE) next += id
|
||||
prefs.edit().putStringSet("tasks", next).apply()
|
||||
}
|
||||
val options = ActivityOptions.makeBasic().setLaunchDisplayId(displayId)
|
||||
context.startActivity(intent, options.toBundle())
|
||||
}
|
||||
|
||||
fun startShortcut(context: Context, info: ShortcutInfo) {
|
||||
val task = generateSequence(context) { (it as? android.content.ContextWrapper)?.baseContext }
|
||||
.filterIsInstance<android.app.Activity>().firstOrNull()?.taskId
|
||||
task?.let { com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(it, true) }
|
||||
try {
|
||||
context.getSystemService(LauncherApps::class.java).startShortcut(info, null, null)
|
||||
} catch (e: Exception) {
|
||||
task?.let { com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(it, false) }
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
fun openAppInfo(context: Context, app: LaunchableApp) {
|
||||
context.getSystemService(LauncherApps::class.java)
|
||||
.startAppDetailsActivity(app.component, app.user ?: Process.myUserHandle(), null, null)
|
||||
}
|
||||
|
||||
fun canUninstall(app: LaunchableApp): Boolean = !app.system && !app.work
|
||||
|
||||
fun uninstall(context: Context, app: LaunchableApp) {
|
||||
context.startActivity(
|
||||
Intent(Intent.ACTION_DELETE, Uri.fromParts("package", app.packageName, null))
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
)
|
||||
}
|
||||
|
||||
fun isActiveSteamSession(): Boolean =
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.droiddeck.launcher
|
||||
|
||||
import android.content.Context
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.util.UUID
|
||||
|
||||
object HomeFolders {
|
||||
data class Folder(val id: String, val name: String, val apps: List<String>)
|
||||
|
||||
private const val PREFS = "home_launcher"
|
||||
private const val KEY = "folders"
|
||||
|
||||
var folders by mutableStateOf<List<Folder>>(emptyList())
|
||||
private set
|
||||
private var loaded = false
|
||||
|
||||
fun load(context: Context) {
|
||||
if (loaded) return
|
||||
loaded = true
|
||||
val raw = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY, null) ?: return
|
||||
folders = runCatching {
|
||||
val array = JSONArray(raw)
|
||||
(0 until array.length()).map { i ->
|
||||
val o = array.getJSONObject(i)
|
||||
val apps = o.getJSONArray("apps")
|
||||
Folder(o.getString("id"), o.getString("name"), (0 until apps.length()).map { apps.getString(it) })
|
||||
}
|
||||
}.getOrDefault(emptyList())
|
||||
}
|
||||
|
||||
fun create(context: Context, name: String, appKey: String): Folder {
|
||||
val folder = Folder(UUID.randomUUID().toString(), name, listOf(appKey))
|
||||
update(context, without(appKey) + folder)
|
||||
return folder
|
||||
}
|
||||
|
||||
fun add(context: Context, folderId: String, appKey: String) =
|
||||
update(context, without(appKey).map { if (it.id == folderId) it.copy(apps = it.apps + appKey) else it })
|
||||
|
||||
fun remove(context: Context, appKey: String) = update(context, without(appKey))
|
||||
|
||||
fun rename(context: Context, folderId: String, name: String) =
|
||||
update(context, folders.map { if (it.id == folderId) it.copy(name = name) else it })
|
||||
|
||||
fun delete(context: Context, folderId: String) = update(context, folders.filterNot { it.id == folderId })
|
||||
|
||||
fun migrateMembers(context: Context, keyFor: (String) -> String?) {
|
||||
if (folders.none { f -> f.apps.any { '/' !in it } }) return
|
||||
update(context, folders.map { f -> f.copy(apps = f.apps.map { if ('/' in it) it else keyFor(it) ?: it }.distinct()) })
|
||||
}
|
||||
|
||||
private fun without(appKey: String): List<Folder> =
|
||||
folders.map { it.copy(apps = it.apps - appKey) }.filter { it.apps.isNotEmpty() }
|
||||
|
||||
private fun update(context: Context, next: List<Folder>) {
|
||||
folders = next
|
||||
val array = JSONArray()
|
||||
for (f in next) array.put(JSONObject().put("id", f.id).put("name", f.name).put("apps", JSONArray(f.apps)))
|
||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString(KEY, array.toString()).apply()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.droiddeck.launcher
|
||||
|
||||
import android.content.Context
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
|
||||
object HomeHidden {
|
||||
private const val PREFS = "home_launcher"
|
||||
private const val KEY = "hidden"
|
||||
|
||||
var keys by mutableStateOf<Set<String>>(emptySet())
|
||||
private set
|
||||
private var loaded = false
|
||||
|
||||
fun load(context: Context) {
|
||||
if (loaded) return
|
||||
loaded = true
|
||||
keys = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getStringSet(KEY, emptySet()).orEmpty().toSet()
|
||||
}
|
||||
|
||||
fun set(context: Context, key: String, hidden: Boolean) {
|
||||
keys = if (hidden) keys + key else keys - key
|
||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putStringSet(KEY, keys).apply()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.droiddeck.launcher
|
||||
|
||||
import android.content.Context
|
||||
import android.content.pm.LauncherApps
|
||||
import android.content.pm.ShortcutInfo
|
||||
import android.graphics.Bitmap
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.Process
|
||||
import android.os.UserManager
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
|
||||
object HomePins {
|
||||
class Pinned(val info: ShortcutInfo, val icon: Bitmap?, val appLabel: String, val userSerial: Long) {
|
||||
val key get() = "pin:${info.`package`}/${info.id}" + if (userSerial != 0L) "#$userSerial" else ""
|
||||
val label get() = info.shortLabel?.toString()?.trim().orEmpty().ifEmpty { appLabel }
|
||||
val work get() = userSerial != 0L
|
||||
}
|
||||
|
||||
var pinned by mutableStateOf<List<Pinned>>(emptyList())
|
||||
private set
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
private var listing = 0
|
||||
|
||||
fun refresh(context: Context) {
|
||||
val app = context.applicationContext
|
||||
val seq = ++listing
|
||||
Thread({
|
||||
val list = runCatching { load(app) }.getOrDefault(emptyList())
|
||||
main.post { if (seq == listing) pinned = list }
|
||||
}, "home-pins").start()
|
||||
}
|
||||
|
||||
private fun load(context: Context): List<Pinned> {
|
||||
if (!HomeApp.canUseShortcuts(context)) return emptyList()
|
||||
val launcher = context.getSystemService(LauncherApps::class.java)
|
||||
val users = context.getSystemService(UserManager::class.java)
|
||||
val pm = context.packageManager
|
||||
val own = Process.myUserHandle()
|
||||
val query = LauncherApps.ShortcutQuery().setQueryFlags(LauncherApps.ShortcutQuery.FLAG_MATCH_PINNED)
|
||||
return users.userProfiles.flatMap { user ->
|
||||
val serial = if (user == own) 0L else users.getSerialNumberForUser(user)
|
||||
runCatching { launcher.getShortcuts(query, user) }.getOrNull().orEmpty()
|
||||
.filter { it.isEnabled && it.isPinned }
|
||||
.map { info ->
|
||||
val appLabel = runCatching { pm.getApplicationLabel(pm.getApplicationInfo(info.`package`, 0)).toString() }
|
||||
.getOrDefault(info.`package`)
|
||||
Pinned(info, HomeApp.shortcutIcon(context, info), appLabel, serial)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun accept(context: Context, request: LauncherApps.PinItemRequest): Boolean {
|
||||
val ok = runCatching { request.isValid && request.accept() }.getOrDefault(false)
|
||||
if (ok) refresh(context)
|
||||
return ok
|
||||
}
|
||||
|
||||
fun unpin(context: Context, pinned: Pinned) {
|
||||
val info = pinned.info
|
||||
val launcher = context.getSystemService(LauncherApps::class.java)
|
||||
val query = LauncherApps.ShortcutQuery().setPackage(info.`package`).setQueryFlags(LauncherApps.ShortcutQuery.FLAG_MATCH_PINNED)
|
||||
val unpinned = runCatching {
|
||||
val current = checkNotNull(launcher.getShortcuts(query, info.userHandle))
|
||||
val keep = current.map { it.id } - info.id
|
||||
launcher.pinShortcuts(info.`package`, keep, info.userHandle)
|
||||
}.isSuccess
|
||||
if (!unpinned) return
|
||||
listing++
|
||||
this.pinned = this.pinned.filterNot { it.key == pinned.key }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
package com.droiddeck.launcher
|
||||
|
||||
import android.app.Activity
|
||||
import android.appwidget.AppWidgetHost
|
||||
import android.appwidget.AppWidgetHostView
|
||||
import android.appwidget.AppWidgetManager
|
||||
import android.appwidget.AppWidgetProviderInfo
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.LauncherApps
|
||||
import android.graphics.Bitmap
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.util.SizeF
|
||||
import android.view.HapticFeedbackConstants
|
||||
import android.view.MotionEvent
|
||||
import android.view.ViewConfiguration
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.core.graphics.drawable.toBitmap
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import kotlin.math.hypot
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
object HomeWidgets {
|
||||
data class Placed(val id: Int, val widthDp: Int, val heightDp: Int)
|
||||
|
||||
data class Provider(
|
||||
val info: AppWidgetProviderInfo,
|
||||
val label: String,
|
||||
val appLabel: String,
|
||||
val preview: Bitmap?,
|
||||
val widthDp: Int,
|
||||
val heightDp: Int,
|
||||
)
|
||||
|
||||
private const val HOST_ID = 0x0DDE
|
||||
private const val PREFS = "home_launcher"
|
||||
private const val KEY = "widgets"
|
||||
private const val REQUEST_BIND = 0x0DD1
|
||||
private const val REQUEST_CONFIGURE = 0x0DD2
|
||||
private const val REQUEST_RECONFIGURE = 0x0DD3
|
||||
const val MIN_WIDTH_DP = 96
|
||||
const val MIN_HEIGHT_DP = 56
|
||||
|
||||
var widgets by mutableStateOf<List<Placed>>(emptyList())
|
||||
private set
|
||||
var providers by mutableStateOf<List<Provider>?>(null)
|
||||
private set
|
||||
private var loaded = false
|
||||
private var host: Host? = null
|
||||
private var pending: AppWidgetProviderInfo? = null
|
||||
private var pendingId = AppWidgetManager.INVALID_APPWIDGET_ID
|
||||
private var pinRequest: LauncherApps.PinItemRequest? = null
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
|
||||
private class Host(context: Context) : AppWidgetHost(context, HOST_ID) {
|
||||
override fun onCreateView(context: Context, appWidgetId: Int, appWidget: AppWidgetProviderInfo?): AppWidgetHostView =
|
||||
HomeWidgetView(context)
|
||||
}
|
||||
|
||||
class HomeWidgetView(context: Context) : AppWidgetHostView(context) {
|
||||
var onLongPress: (() -> Unit)? = null
|
||||
private var fired = false
|
||||
private var downX = 0f
|
||||
private var downY = 0f
|
||||
private val slop = ViewConfiguration.get(context).scaledTouchSlop
|
||||
private val longPress = Runnable {
|
||||
fired = true
|
||||
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
|
||||
onLongPress?.invoke()
|
||||
}
|
||||
|
||||
override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
|
||||
when (ev.actionMasked) {
|
||||
MotionEvent.ACTION_DOWN -> {
|
||||
fired = false
|
||||
downX = ev.x
|
||||
downY = ev.y
|
||||
postDelayed(longPress, ViewConfiguration.getLongPressTimeout().toLong())
|
||||
}
|
||||
MotionEvent.ACTION_MOVE -> if (hypot(ev.x - downX, ev.y - downY) > slop) removeCallbacks(longPress)
|
||||
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_POINTER_DOWN -> removeCallbacks(longPress)
|
||||
}
|
||||
return fired
|
||||
}
|
||||
|
||||
override fun onTouchEvent(event: MotionEvent): Boolean {
|
||||
if (fired) {
|
||||
if (event.actionMasked == MotionEvent.ACTION_UP || event.actionMasked == MotionEvent.ACTION_CANCEL) fired = false
|
||||
return true
|
||||
}
|
||||
return super.onTouchEvent(event)
|
||||
}
|
||||
}
|
||||
|
||||
private fun host(context: Context): Host = host ?: Host(context.applicationContext).also { host = it }
|
||||
|
||||
fun load(context: Context) {
|
||||
if (loaded) return
|
||||
loaded = true
|
||||
val raw = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY, null) ?: return
|
||||
val manager = AppWidgetManager.getInstance(context)
|
||||
val parsed = runCatching {
|
||||
val array = JSONArray(raw)
|
||||
(0 until array.length()).map { i ->
|
||||
val o = array.getJSONObject(i)
|
||||
Placed(o.getInt("id"), o.getInt("w"), o.getInt("h"))
|
||||
}
|
||||
}.getOrDefault(emptyList())
|
||||
val live = parsed.filter { manager.getAppWidgetInfo(it.id) != null }
|
||||
parsed.filterNot { it in live }.forEach { host(context).deleteAppWidgetId(it.id) }
|
||||
widgets = live
|
||||
if (live.size != parsed.size) save(context)
|
||||
}
|
||||
|
||||
fun startListening(context: Context) {
|
||||
load(context)
|
||||
runCatching { host(context).startListening() }
|
||||
}
|
||||
|
||||
fun stopListening(context: Context) {
|
||||
runCatching { host(context).stopListening() }
|
||||
}
|
||||
|
||||
fun info(context: Context, id: Int): AppWidgetProviderInfo? = AppWidgetManager.getInstance(context).getAppWidgetInfo(id)
|
||||
|
||||
fun createView(context: Context, id: Int): HomeWidgetView? {
|
||||
val info = info(context, id) ?: return null
|
||||
return host(context).createView(context, id, info) as? HomeWidgetView
|
||||
}
|
||||
|
||||
fun applySize(view: AppWidgetHostView, widthDp: Int, heightDp: Int) {
|
||||
if (Build.VERSION.SDK_INT >= 31) {
|
||||
view.updateAppWidgetSize(Bundle(), listOf(SizeF(widthDp.toFloat(), heightDp.toFloat())))
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
view.updateAppWidgetSize(null, widthDp, heightDp, widthDp, heightDp)
|
||||
}
|
||||
}
|
||||
|
||||
fun loadProviders(context: Context) {
|
||||
if (providers != null) return
|
||||
val app = context.applicationContext
|
||||
Thread({
|
||||
val pm = app.packageManager
|
||||
val manager = AppWidgetManager.getInstance(app)
|
||||
val dpi = app.resources.displayMetrics.densityDpi
|
||||
val list = manager.installedProviders.mapNotNull { info ->
|
||||
runCatching {
|
||||
val appLabel = runCatching { pm.getApplicationLabel(pm.getApplicationInfo(info.provider.packageName, 0)).toString() }
|
||||
.getOrDefault(info.provider.packageName)
|
||||
val drawable = info.loadPreviewImage(app, dpi) ?: info.loadIcon(app, dpi)
|
||||
val preview = drawable?.let { d ->
|
||||
val w = d.intrinsicWidth.takeIf { it > 0 } ?: 192
|
||||
val h = d.intrinsicHeight.takeIf { it > 0 } ?: 192
|
||||
val scale = minOf(1f, 360f / maxOf(w, h))
|
||||
d.toBitmap((w * scale).roundToInt().coerceAtLeast(1), (h * scale).roundToInt().coerceAtLeast(1))
|
||||
}
|
||||
val (w, h) = defaultSize(app, info)
|
||||
Provider(info, info.loadLabel(pm)?.toString()?.trim().orEmpty().ifEmpty { appLabel }, appLabel, preview, w, h)
|
||||
}.getOrNull()
|
||||
}.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER, Provider::appLabel).thenBy(String.CASE_INSENSITIVE_ORDER, Provider::label))
|
||||
main.post { providers = list }
|
||||
}, "widget-providers").start()
|
||||
}
|
||||
|
||||
fun refreshProviders(context: Context) {
|
||||
providers = null
|
||||
loadProviders(context)
|
||||
}
|
||||
|
||||
private fun defaultSize(context: Context, info: AppWidgetProviderInfo): Pair<Int, Int> {
|
||||
val density = context.resources.displayMetrics.density
|
||||
var w = (info.minWidth / density).roundToInt()
|
||||
var h = (info.minHeight / density).roundToInt()
|
||||
if (Build.VERSION.SDK_INT >= 31) {
|
||||
if (info.targetCellWidth > 0) w = maxOf(w, info.targetCellWidth * 80)
|
||||
if (info.targetCellHeight > 0) h = maxOf(h, info.targetCellHeight * 80)
|
||||
}
|
||||
return w.coerceIn(160, 560) to h.coerceIn(MIN_HEIGHT_DP, 360)
|
||||
}
|
||||
|
||||
fun minSize(context: Context, id: Int): Pair<Int, Int> {
|
||||
val info = info(context, id) ?: return MIN_WIDTH_DP to MIN_HEIGHT_DP
|
||||
val density = context.resources.displayMetrics.density
|
||||
val w = (if (info.minResizeWidth > 0) info.minResizeWidth else info.minWidth) / density
|
||||
val h = (if (info.minResizeHeight > 0) info.minResizeHeight else info.minHeight) / density
|
||||
return w.roundToInt().coerceAtLeast(MIN_WIDTH_DP) to h.roundToInt().coerceAtLeast(MIN_HEIGHT_DP)
|
||||
}
|
||||
|
||||
fun add(activity: Activity, provider: Provider) {
|
||||
if (pendingId == AppWidgetManager.INVALID_APPWIDGET_ID) add(activity, provider.info, null)
|
||||
}
|
||||
|
||||
fun addPinned(activity: Activity, request: LauncherApps.PinItemRequest): Boolean {
|
||||
if (pendingId != AppWidgetManager.INVALID_APPWIDGET_ID) return false
|
||||
val info = request.getAppWidgetProviderInfo(activity) ?: return false
|
||||
load(activity)
|
||||
add(activity, info, request)
|
||||
return pending != null
|
||||
}
|
||||
|
||||
private fun add(activity: Activity, info: AppWidgetProviderInfo, request: LauncherApps.PinItemRequest?) {
|
||||
val h = host(activity)
|
||||
val id = h.allocateAppWidgetId()
|
||||
pending = info
|
||||
pendingId = id
|
||||
pinRequest = request
|
||||
val manager = AppWidgetManager.getInstance(activity)
|
||||
val bound = runCatching { manager.bindAppWidgetIdIfAllowed(id, info.profile, info.provider, null) }.getOrDefault(false)
|
||||
if (bound) {
|
||||
bound(activity, id, info)
|
||||
return
|
||||
}
|
||||
val bind = Intent(AppWidgetManager.ACTION_APPWIDGET_BIND)
|
||||
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id)
|
||||
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, info.provider)
|
||||
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER_PROFILE, info.profile)
|
||||
@Suppress("DEPRECATION")
|
||||
runCatching { activity.startActivityForResult(bind, REQUEST_BIND) }.onFailure { abandon(activity) }
|
||||
}
|
||||
|
||||
private fun bound(activity: Activity, id: Int, info: AppWidgetProviderInfo) {
|
||||
val request = pinRequest
|
||||
if (request == null) {
|
||||
configure(activity, id, info)
|
||||
return
|
||||
}
|
||||
val accepted = runCatching { request.isValid && request.accept(Bundle().apply { putInt(AppWidgetManager.EXTRA_APPWIDGET_ID, id) }) }
|
||||
.getOrDefault(false)
|
||||
if (accepted) place(activity, id, info) else abandon(activity)
|
||||
}
|
||||
|
||||
private fun configure(activity: Activity, id: Int, info: AppWidgetProviderInfo) {
|
||||
val optional = Build.VERSION.SDK_INT >= 31 &&
|
||||
info.widgetFeatures and AppWidgetProviderInfo.WIDGET_FEATURE_CONFIGURATION_OPTIONAL != 0
|
||||
if (info.configure == null || optional) {
|
||||
place(activity, id, info)
|
||||
return
|
||||
}
|
||||
runCatching { host(activity).startAppWidgetConfigureActivityForResult(activity, id, 0, REQUEST_CONFIGURE, null) }
|
||||
.onFailure { place(activity, id, info) }
|
||||
}
|
||||
|
||||
fun canReconfigure(context: Context, id: Int): Boolean {
|
||||
val info = info(context, id) ?: return false
|
||||
if (info.configure == null) return false
|
||||
return Build.VERSION.SDK_INT < 28 || info.widgetFeatures and AppWidgetProviderInfo.WIDGET_FEATURE_RECONFIGURABLE != 0
|
||||
}
|
||||
|
||||
fun reconfigure(activity: Activity, id: Int) {
|
||||
runCatching { host(activity).startAppWidgetConfigureActivityForResult(activity, id, 0, REQUEST_RECONFIGURE, null) }
|
||||
}
|
||||
|
||||
fun onActivityResult(activity: Activity, requestCode: Int, resultCode: Int): Boolean {
|
||||
when (requestCode) {
|
||||
REQUEST_BIND -> {
|
||||
val info = pending
|
||||
if (resultCode == Activity.RESULT_OK && info != null) bound(activity, pendingId, info) else abandon(activity)
|
||||
}
|
||||
REQUEST_CONFIGURE -> {
|
||||
val info = pending
|
||||
if (resultCode == Activity.RESULT_OK && info != null) place(activity, pendingId, info) else abandon(activity)
|
||||
}
|
||||
REQUEST_RECONFIGURE -> Unit
|
||||
else -> return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private fun abandon(context: Context) {
|
||||
if (pendingId != AppWidgetManager.INVALID_APPWIDGET_ID) host(context).deleteAppWidgetId(pendingId)
|
||||
pending = null
|
||||
pinRequest = null
|
||||
pendingId = AppWidgetManager.INVALID_APPWIDGET_ID
|
||||
}
|
||||
|
||||
private fun place(context: Context, id: Int, info: AppWidgetProviderInfo) {
|
||||
val (w, h) = defaultSize(context, info)
|
||||
pending = null
|
||||
pinRequest = null
|
||||
pendingId = AppWidgetManager.INVALID_APPWIDGET_ID
|
||||
widgets = widgets + Placed(id, w, h)
|
||||
save(context)
|
||||
}
|
||||
|
||||
fun resize(context: Context, id: Int, widthDp: Int, heightDp: Int) {
|
||||
widgets = widgets.map { if (it.id == id) it.copy(widthDp = widthDp, heightDp = heightDp) else it }
|
||||
save(context)
|
||||
}
|
||||
|
||||
fun move(context: Context, id: Int, by: Int) {
|
||||
val i = widgets.indexOfFirst { it.id == id }
|
||||
val j = i + by
|
||||
if (i < 0 || j !in widgets.indices) return
|
||||
widgets = widgets.toMutableList().apply { add(j, removeAt(i)) }
|
||||
save(context)
|
||||
}
|
||||
|
||||
fun remove(context: Context, id: Int) {
|
||||
host(context).deleteAppWidgetId(id)
|
||||
widgets = widgets.filterNot { it.id == id }
|
||||
save(context)
|
||||
}
|
||||
|
||||
private fun save(context: Context) {
|
||||
val array = JSONArray()
|
||||
for (w in widgets) array.put(JSONObject().put("id", w.id).put("w", w.widthDp).put("h", w.heightDp))
|
||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString(KEY, array.toString()).apply()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
package com.droiddeck.launcher
|
||||
|
||||
import android.app.ActivityOptions
|
||||
import android.app.AppOpsManager
|
||||
import android.app.PictureInPictureParams
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.content.res.Configuration
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.os.Process
|
||||
import android.provider.Settings
|
||||
import android.util.Rational
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.compose.animation.core.LinearEasing
|
||||
import androidx.compose.animation.core.RepeatMode
|
||||
import androidx.compose.animation.core.animateFloat
|
||||
import androidx.compose.animation.core.infiniteRepeatable
|
||||
import androidx.compose.animation.core.rememberInfiniteTransition
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.produceState
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.alpha
|
||||
import androidx.compose.ui.draw.scale
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.droiddeck.launcher.core.AppLanguage
|
||||
import com.droiddeck.launcher.core.GlobalSettings
|
||||
import com.droiddeck.launcher.core.PhantomProcessLimit
|
||||
import com.droiddeck.launcher.core.WirelessAdbPairingService
|
||||
import com.droiddeck.launcher.core.WirelessAdbPairingService.Stage
|
||||
import com.droiddeck.launcher.ui.DroidDeckTheme
|
||||
import com.droiddeck.launcher.ui.LocalPalette
|
||||
import com.droiddeck.launcher.ui.PrimaryButton
|
||||
import com.droiddeck.launcher.ui.SecondaryButton
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
class PairingGuideActivity : ComponentActivity() {
|
||||
enum class Step { BUILD_NUMBER, CHILD_PROCESS, WIRELESS_DEBUGGING, PAIR, CODE, WORKING, DONE, FAILED }
|
||||
|
||||
private var settingsDisplay: Int? = null
|
||||
private var toggleOnly = false
|
||||
private var inPip by mutableStateOf(false)
|
||||
private var launchPending = false
|
||||
|
||||
override fun attachBaseContext(newBase: Context) = super.attachBaseContext(AppLanguage.wrap(newBase))
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
settingsDisplay = intent.getIntExtra(EXTRA_DISPLAY, -1).takeIf { it >= 0 }
|
||||
toggleOnly = intent.getBooleanExtra(EXTRA_TOGGLE_ONLY, false)
|
||||
setContent { DroidDeckTheme { Guide() } }
|
||||
launchPending = savedInstanceState == null
|
||||
}
|
||||
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
setIntent(intent)
|
||||
settingsDisplay = intent.getIntExtra(EXTRA_DISPLAY, -1).takeIf { it >= 0 }
|
||||
toggleOnly = intent.getBooleanExtra(EXTRA_TOGGLE_ONLY, false)
|
||||
launchPending = true
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
if (!launchPending) return
|
||||
if (inPip || settingsDisplay != null) {
|
||||
launchSettings()
|
||||
return
|
||||
}
|
||||
enterPip()
|
||||
if (!inPip) launchSettings()
|
||||
}
|
||||
|
||||
override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean, newConfig: Configuration) {
|
||||
super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig)
|
||||
inPip = isInPictureInPictureMode
|
||||
if (isInPictureInPictureMode && launchPending) launchSettings()
|
||||
}
|
||||
|
||||
private fun launchSettings() {
|
||||
launchPending = false
|
||||
openSettings(stepFor(SettingsState.read(this), WirelessAdbPairingService.stage.value, toggleOnly))
|
||||
}
|
||||
|
||||
private fun enterPip() {
|
||||
inPip = runCatching {
|
||||
enterPictureInPictureMode(PictureInPictureParams.Builder().setAspectRatio(Rational(4, 3)).build())
|
||||
}.getOrDefault(false)
|
||||
}
|
||||
|
||||
private fun openSettings(step: Step) {
|
||||
val intent = if (step == Step.BUILD_NUMBER) {
|
||||
Intent(Settings.ACTION_DEVICE_INFO_SETTINGS).putExtra(HIGHLIGHT_KEY, "build_number")
|
||||
} else {
|
||||
Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS).apply {
|
||||
if (step != Step.CHILD_PROCESS) putExtra(HIGHLIGHT_KEY, "toggle_adb_wireless")
|
||||
}
|
||||
}.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
val display = settingsDisplay
|
||||
runCatching {
|
||||
if (display == null) startActivity(intent)
|
||||
else startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(display).toBundle())
|
||||
}.onFailure {
|
||||
runCatching { startActivity(Intent(Settings.ACTION_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun returnToApp() {
|
||||
startActivity(Intent(this, FrontEndActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT))
|
||||
finish()
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Guide() {
|
||||
val stage by WirelessAdbPairingService.stage.collectAsState()
|
||||
val settingsState by produceState(SettingsState.read(this)) {
|
||||
while (true) {
|
||||
value = SettingsState.read(this@PairingGuideActivity)
|
||||
delay(500)
|
||||
}
|
||||
}
|
||||
val step = stepFor(settingsState, stage, toggleOnly)
|
||||
var previous by remember { mutableStateOf(step) }
|
||||
LaunchedEffect(step) {
|
||||
if (previous == Step.BUILD_NUMBER && (step == Step.WIRELESS_DEBUGGING || step == Step.CHILD_PROCESS)) openSettings(step)
|
||||
previous = step
|
||||
when (step) {
|
||||
Step.DONE -> { delay(1_500); returnToApp() }
|
||||
Step.FAILED -> { delay(3_000); returnToApp() }
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
LaunchedEffect(stage) { if (stage == Stage.Idle && !toggleOnly) finish() }
|
||||
BackHandler(enabled = !inPip && settingsDisplay == null) { enterPip() }
|
||||
|
||||
Box(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background), contentAlignment = Alignment.Center) {
|
||||
if (inPip) CompactStep(step, stage)
|
||||
else FullGuide(step, stage)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CompactStep(step: Step, stage: Stage) {
|
||||
Column(Modifier.fillMaxSize().padding(10.dp), verticalArrangement = Arrangement.SpaceBetween) {
|
||||
Text(
|
||||
instruction(step, stage), style = MaterialTheme.typography.labelLarge, fontWeight = FontWeight.SemiBold,
|
||||
color = MaterialTheme.colorScheme.onBackground, maxLines = 3, overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
StepVisual(step, compact = true)
|
||||
StepDots(step)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FullGuide(step: Step, stage: Stage) {
|
||||
Column(
|
||||
Modifier.widthIn(max = 520.dp).fillMaxWidth().padding(24.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||
) {
|
||||
Text(stringResource(R.string.gate_title), style = MaterialTheme.typography.headlineSmall,
|
||||
fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.onBackground)
|
||||
Text(instruction(step, stage), style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.onBackground)
|
||||
StepVisual(step, compact = false)
|
||||
StepDots(step)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
if (step == Step.DONE || step == Step.FAILED) {
|
||||
PrimaryButton(stringResource(R.string.common_back), onClick = ::returnToApp)
|
||||
} else {
|
||||
PrimaryButton(stringResource(R.string.gate_open_dev), onClick = {
|
||||
if (settingsDisplay == null) enterPip()
|
||||
openSettings(step)
|
||||
})
|
||||
SecondaryButton(stringResource(R.string.common_cancel), onClick = {
|
||||
if (!toggleOnly) WirelessAdbPairingService.cancel(this@PairingGuideActivity)
|
||||
returnToApp()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun instruction(step: Step, stage: Stage): String = when (step) {
|
||||
Step.BUILD_NUMBER -> stringResource(R.string.pairguide_build_number)
|
||||
Step.CHILD_PROCESS -> stringResource(R.string.pairguide_child_process)
|
||||
Step.WIRELESS_DEBUGGING -> stringResource(R.string.pairguide_wireless)
|
||||
Step.PAIR -> stringResource(R.string.pairguide_pair)
|
||||
Step.CODE -> (stage as? Stage.CodeNeeded)?.error ?: stringResource(R.string.gate_step3)
|
||||
Step.WORKING -> (stage as? Stage.Working)?.step ?: stringResource(R.string.adbpair_title_working)
|
||||
Step.DONE -> stringResource(R.string.adbpair_title_done)
|
||||
Step.FAILED -> (stage as? Stage.Failed)?.error ?: stringResource(R.string.adbpair_title_failed)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StepVisual(step: Step, compact: Boolean) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val accent = LocalPalette.current.signal
|
||||
val pulse = rememberInfiniteTransition(label = "guidePulse")
|
||||
val beat by pulse.animateFloat(0f, 1f, infiniteRepeatable(tween(900, easing = LinearEasing), RepeatMode.Restart), label = "beat")
|
||||
val label = when (step) {
|
||||
Step.BUILD_NUMBER -> stringResource(R.string.pairguide_row_build_number)
|
||||
Step.CHILD_PROCESS -> stringResource(R.string.pairguide_row_child_process)
|
||||
Step.WIRELESS_DEBUGGING -> stringResource(R.string.pairguide_row_wireless)
|
||||
Step.PAIR -> stringResource(R.string.pairguide_row_pair)
|
||||
Step.CODE -> stringResource(R.string.adbpair_enter_code)
|
||||
Step.WORKING, Step.DONE, Step.FAILED -> return
|
||||
}
|
||||
val rowHeight = if (compact) 34.dp else 56.dp
|
||||
Row(
|
||||
Modifier.fillMaxWidth().height(rowHeight).background(colors.surfaceVariant, RoundedCornerShape(10.dp))
|
||||
.border(1.dp, accent.copy(alpha = 0.35f), RoundedCornerShape(10.dp)).padding(horizontal = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(label, style = if (compact) MaterialTheme.typography.labelMedium else MaterialTheme.typography.bodyLarge,
|
||||
color = colors.onSurface, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
|
||||
when (step) {
|
||||
Step.WIRELESS_DEBUGGING, Step.CHILD_PROCESS -> Toggle(on = beat > 0.5f, accent = accent, compact = compact)
|
||||
else -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
if (step == Step.BUILD_NUMBER) Text("×7", style = MaterialTheme.typography.labelLarge, color = accent)
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
Box(Modifier.size(if (compact) 18.dp else 26.dp).scale(0.6f + beat * 0.8f).alpha(1f - beat)
|
||||
.background(accent, CircleShape))
|
||||
Box(Modifier.size(if (compact) 8.dp else 12.dp).background(accent, CircleShape))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Toggle(on: Boolean, accent: Color, compact: Boolean) {
|
||||
val width = if (compact) 26.dp else 40.dp
|
||||
val knob = if (compact) 12.dp else 18.dp
|
||||
Box(
|
||||
Modifier.width(width).height(knob + 4.dp)
|
||||
.background(if (on) accent.copy(alpha = 0.6f) else MaterialTheme.colorScheme.outline, CircleShape).padding(2.dp),
|
||||
contentAlignment = if (on) Alignment.CenterEnd else Alignment.CenterStart,
|
||||
) { Box(Modifier.size(knob).background(Color.White, CircleShape)) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StepDots(step: Step) {
|
||||
val accent = LocalPalette.current.signal
|
||||
val shown = if (toggleOnly) listOf(Step.BUILD_NUMBER, Step.CHILD_PROCESS)
|
||||
else listOf(Step.BUILD_NUMBER, Step.WIRELESS_DEBUGGING, Step.PAIR, Step.CODE)
|
||||
val at = shown.indexOf(step).takeIf { it >= 0 } ?: shown.size
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(5.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
shown.forEachIndexed { index, _ ->
|
||||
Box(Modifier.size(if (index == at) 8.dp else 6.dp)
|
||||
.background(if (index <= at) accent else MaterialTheme.colorScheme.outline, CircleShape))
|
||||
}
|
||||
Spacer(Modifier.width(2.dp))
|
||||
}
|
||||
}
|
||||
|
||||
private data class SettingsState(
|
||||
val developerOptions: Boolean,
|
||||
val wirelessDebugging: Boolean,
|
||||
val childProcessBlocked: Boolean,
|
||||
) {
|
||||
companion object {
|
||||
fun read(context: Context) = SettingsState(
|
||||
GlobalSettings.developerOptionsOn(context),
|
||||
GlobalSettings.wirelessDebuggingOn(context),
|
||||
PhantomProcessLimit.blocksSteam(PhantomProcessLimit.read(context)),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val EXTRA_DISPLAY = "settingsDisplay"
|
||||
private const val EXTRA_TOGGLE_ONLY = "toggleOnly"
|
||||
private const val HIGHLIGHT_KEY = ":settings:fragment_args_key"
|
||||
|
||||
private fun stepFor(settings: SettingsState, stage: Stage, toggleOnly: Boolean): Step = if (toggleOnly) when {
|
||||
!settings.developerOptions -> Step.BUILD_NUMBER
|
||||
settings.childProcessBlocked -> Step.CHILD_PROCESS
|
||||
else -> Step.DONE
|
||||
} else when (stage) {
|
||||
is Stage.Working -> Step.WORKING
|
||||
Stage.Done -> Step.DONE
|
||||
is Stage.Failed -> Step.FAILED
|
||||
is Stage.CodeNeeded -> Step.CODE
|
||||
else -> when {
|
||||
!settings.developerOptions -> Step.BUILD_NUMBER
|
||||
!settings.wirelessDebugging -> Step.WIRELESS_DEBUGGING
|
||||
else -> Step.PAIR
|
||||
}
|
||||
}
|
||||
|
||||
fun canFloat(context: Context): Boolean {
|
||||
if (!context.packageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)) return false
|
||||
val ops = context.getSystemService(AppOpsManager::class.java) ?: return true
|
||||
val mode = if (Build.VERSION.SDK_INT >= 29) {
|
||||
ops.unsafeCheckOpNoThrow(AppOpsManager.OPSTR_PICTURE_IN_PICTURE, Process.myUid(), context.packageName)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
ops.checkOpNoThrow(AppOpsManager.OPSTR_PICTURE_IN_PICTURE, Process.myUid(), context.packageName)
|
||||
}
|
||||
return mode == AppOpsManager.MODE_ALLOWED
|
||||
}
|
||||
|
||||
fun start(context: Context, settingsDisplay: Int?, toggleOnly: Boolean = false): Boolean {
|
||||
if (settingsDisplay == null && !canFloat(context)) return false
|
||||
context.startActivity(Intent(context, PairingGuideActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
.putExtra(EXTRA_TOGGLE_ONLY, toggleOnly)
|
||||
.apply { if (settingsDisplay != null) putExtra(EXTRA_DISPLAY, settingsDisplay) })
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package com.droiddeck.launcher
|
||||
|
||||
import android.content.Intent
|
||||
import android.content.pm.LauncherApps
|
||||
import android.graphics.Bitmap
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.core.graphics.drawable.toBitmap
|
||||
import com.droiddeck.launcher.core.AppUiPrefs
|
||||
import com.droiddeck.launcher.ui.DroidDeckTheme
|
||||
import com.droiddeck.launcher.ui.PinRequestPrompt
|
||||
|
||||
class PinRequestActivity : ComponentActivity() {
|
||||
override fun attachBaseContext(newBase: android.content.Context) {
|
||||
super.attachBaseContext(newBase)
|
||||
com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase)
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
val request = runCatching { getSystemService(LauncherApps::class.java).getPinItemRequest(intent) }.getOrNull()
|
||||
if (request == null || !request.isValid) {
|
||||
finish()
|
||||
return
|
||||
}
|
||||
val prompt = when (request.requestType) {
|
||||
LauncherApps.PinItemRequest.REQUEST_TYPE_SHORTCUT -> request.shortcutInfo?.let { info ->
|
||||
val appLabel = appLabel(info.`package`)
|
||||
Triple(info.shortLabel?.toString().orEmpty().ifEmpty { appLabel }, appLabel, HomeApp.shortcutIcon(this, info))
|
||||
}
|
||||
LauncherApps.PinItemRequest.REQUEST_TYPE_APPWIDGET -> request.getAppWidgetProviderInfo(this)?.let { info ->
|
||||
val appLabel = appLabel(info.provider.packageName)
|
||||
val dpi = resources.displayMetrics.densityDpi
|
||||
val icon = runCatching { (info.loadPreviewImage(this, dpi) ?: info.loadIcon(this, dpi))?.let(::scaled) }.getOrNull()
|
||||
Triple(info.loadLabel(packageManager)?.toString().orEmpty().ifEmpty { appLabel }, appLabel, icon)
|
||||
}
|
||||
else -> null
|
||||
}
|
||||
if (prompt == null) {
|
||||
finish()
|
||||
return
|
||||
}
|
||||
val (label, appLabel, icon) = prompt
|
||||
val widget = request.requestType == LauncherApps.PinItemRequest.REQUEST_TYPE_APPWIDGET
|
||||
setContent {
|
||||
DroidDeckTheme(appScale = AppUiPrefs.scale(this)) {
|
||||
PinRequestPrompt(
|
||||
label = label, appLabel = appLabel, icon = icon, wide = widget,
|
||||
onAdd = {
|
||||
if (!widget) {
|
||||
HomePins.accept(this, request)
|
||||
finish()
|
||||
} else if (!HomeWidgets.addPinned(this, request)) finish()
|
||||
},
|
||||
onCancel = { finish() },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Suppress("OVERRIDE_DEPRECATION")
|
||||
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
|
||||
if (HomeWidgets.onActivityResult(this, requestCode, resultCode)) {
|
||||
finish()
|
||||
return
|
||||
}
|
||||
@Suppress("DEPRECATION")
|
||||
super.onActivityResult(requestCode, resultCode, data)
|
||||
}
|
||||
|
||||
private fun appLabel(packageName: String): String =
|
||||
runCatching { packageManager.getApplicationLabel(packageManager.getApplicationInfo(packageName, 0)).toString() }
|
||||
.getOrDefault(packageName)
|
||||
|
||||
private fun scaled(d: android.graphics.drawable.Drawable): Bitmap {
|
||||
val w = d.intrinsicWidth.takeIf { it > 0 } ?: 192
|
||||
val h = d.intrinsicHeight.takeIf { it > 0 } ?: 192
|
||||
val k = minOf(1f, 480f / maxOf(w, h))
|
||||
return d.toBitmap((w * k).toInt().coerceAtLeast(1), (h * k).toInt().coerceAtLeast(1))
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
package com.droiddeck.launcher
|
||||
|
||||
import android.os.Handler
|
||||
import android.util.Log
|
||||
import androidx.annotation.VisibleForTesting
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
@@ -8,31 +10,58 @@ import androidx.compose.runtime.setValue
|
||||
import com.droiddeck.launcher.session.ProtonExtras
|
||||
import com.droiddeck.launcher.ui.ProtonRow
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.session.SessionPhase
|
||||
import com.droiddeck.launcher.frontend.AutoComponents
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller
|
||||
|
||||
internal class ProtonMenu(private val activity: android.app.Activity, private val ui: android.os.Handler) {
|
||||
var protonRows by mutableStateOf<List<ProtonRow>>(emptyList())
|
||||
var protonBusyId by mutableStateOf<String?>(null)
|
||||
var protonStage by mutableStateOf<String?>(null)
|
||||
var protonPercent by mutableIntStateOf(-1)
|
||||
internal class ProtonMenu(
|
||||
private val activity: android.app.Activity,
|
||||
private val ui: Handler,
|
||||
private val idle: () -> Boolean = { true },
|
||||
) {
|
||||
private object Operation {
|
||||
val rows = mutableStateOf<List<ProtonRow>>(emptyList())
|
||||
val busyId = mutableStateOf<String?>(null)
|
||||
val stage = mutableStateOf<String?>(null)
|
||||
val percent = mutableIntStateOf(-1)
|
||||
val problem = mutableStateOf<String?>(null)
|
||||
}
|
||||
var protonRows by Operation.rows
|
||||
var protonBusyId by Operation.busyId
|
||||
var protonStage by Operation.stage
|
||||
var protonPercent by Operation.percent
|
||||
var protonProblem by Operation.problem
|
||||
private val checking = java.util.concurrent.atomic.AtomicBoolean(false)
|
||||
@VisibleForTesting internal var installer: (ProtonExtras.Tool, (String, Int) -> Unit) -> String? =
|
||||
{ tool, progress -> ProtonExtras.install(activity, tool, progress) }
|
||||
|
||||
fun installProton(id: String) {
|
||||
fun installProton(id: String, automatic: Boolean = false) {
|
||||
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
|
||||
if (protonBusyId != null || SessionState.running) return
|
||||
if (protonBusyId != null || ProtonExtras.installInProgress || SessionState.running) return
|
||||
ProtonExtras.unqueue(activity, tool)
|
||||
protonBusyId = id
|
||||
protonProblem = null
|
||||
protonStage = activity.getString(R.string.store_starting)
|
||||
protonPercent = -1
|
||||
Thread({
|
||||
val problem = ProtonExtras.install(activity, tool) { label, value ->
|
||||
ui.post { protonStage = label; protonPercent = value }
|
||||
}
|
||||
val problem = runCatching {
|
||||
installer(tool) { label, value ->
|
||||
ui.post { protonStage = label; protonPercent = value }
|
||||
}
|
||||
}.getOrElse { it.message ?: it.javaClass.simpleName }
|
||||
if (problem == null && !automatic && tool.id == ProtonExtras.OWN) ProtonExtras.setDeclined(activity, false)
|
||||
ui.post {
|
||||
protonProblem = problem
|
||||
protonBusyId = null
|
||||
protonStage = null
|
||||
protonPercent = -1
|
||||
refreshProtons()
|
||||
if (problem != null) android.widget.Toast.makeText(activity, problem, android.widget.Toast.LENGTH_LONG).show()
|
||||
if (problem != null) {
|
||||
if (automatic) Log.w("ProtonMenu", "auto-update ${tool.id}: $problem")
|
||||
else android.widget.Toast.makeText(activity, problem, android.widget.Toast.LENGTH_LONG).show()
|
||||
}
|
||||
if (automatic) ensureAutoUpdates()
|
||||
}
|
||||
}, "install-proton-$id").start()
|
||||
}
|
||||
@@ -41,10 +70,12 @@ internal class ProtonMenu(private val activity: android.app.Activity, private va
|
||||
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
|
||||
if (protonBusyId != null || SessionState.running) return
|
||||
protonBusyId = id
|
||||
protonProblem = null
|
||||
protonStage = activity.getString(R.string.main_removing_named, dir ?: tool.name)
|
||||
protonPercent = -1
|
||||
Thread({
|
||||
if (older) ProtonExtras.removeOlder(activity, tool) else ProtonExtras.remove(activity, tool, dir)
|
||||
if (tool.id == ProtonExtras.OWN && ProtonExtras.installedAll(activity, tool).isEmpty()) ProtonExtras.setDeclined(activity, true)
|
||||
ui.post {
|
||||
protonBusyId = null
|
||||
protonStage = null
|
||||
@@ -64,7 +95,39 @@ internal class ProtonMenu(private val activity: android.app.Activity, private va
|
||||
if (!checking.compareAndSet(false, true)) return
|
||||
Thread({
|
||||
val asked = try { ProtonExtras.checkLatest(activity, force) } catch (_: Throwable) { false } finally { checking.set(false) }
|
||||
if (asked) ui.post { refreshProtons() }
|
||||
ui.post {
|
||||
if (asked) refreshProtons()
|
||||
ensureAutoUpdates()
|
||||
}
|
||||
}, "proton-updates").start()
|
||||
}
|
||||
|
||||
internal fun ensureAutoUpdates(now: Long = System.currentTimeMillis()) {
|
||||
if (activity.isFinishing || activity.isDestroyed || !idle() || protonBusyId != null ||
|
||||
ProtonExtras.installInProgress || SessionState.running || LinuxRuntimeInstaller.isBusy() ||
|
||||
SessionState.phase !in setOf(SessionPhase.IDLE, SessionPhase.FAILED) ||
|
||||
!LinuxRuntime.isInstalled(activity) || !AutoComponents.online(activity) || AutoComponents.unfavourable(activity)) return
|
||||
if (ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).size > 1) {
|
||||
protonBusyId = ProtonExtras.OWN
|
||||
protonProblem = null
|
||||
Thread({
|
||||
ProtonExtras.tidy(activity)
|
||||
val tidied = ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).size <= 1
|
||||
ui.post {
|
||||
protonBusyId = null
|
||||
refreshProtons()
|
||||
if (tidied) ensureAutoUpdates()
|
||||
}
|
||||
}, "proton-tidy").start()
|
||||
return
|
||||
}
|
||||
val attempts = activity.getSharedPreferences("proton-auto-updates", android.content.Context.MODE_PRIVATE)
|
||||
val (tool, update) = ProtonExtras.tools.firstNotNullOfOrNull { tool ->
|
||||
val update = ProtonExtras.update(activity, tool) ?: ProtonExtras.missing(activity, tool) ?: return@firstNotNullOfOrNull null
|
||||
val previous = attempts.getLong("${tool.id}.at", 0L)
|
||||
if (attempts.getString("${tool.id}.tag", null) != update || now - previous !in 0 until 15L * 60 * 1000) tool to update else null
|
||||
} ?: return
|
||||
attempts.edit().putString("${tool.id}.tag", update).putLong("${tool.id}.at", now).apply()
|
||||
installProton(tool.id, automatic = true)
|
||||
}
|
||||
}
|
||||
@@ -71,7 +71,6 @@ class QuestXrActivity : NativeActivity() {
|
||||
}
|
||||
} finally {
|
||||
synchronized(steamVrLock) {
|
||||
// A retiring activity must not stop a replacement's SteamVR session.
|
||||
if (steamVrOwner === this) {
|
||||
if (sessionAlive()) SteamVr.run(this, "stop")
|
||||
steamVrOwner = null
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -29,6 +29,7 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
|
||||
private var pending: AppUpdates.Release? = null
|
||||
private var lastCheck = 0L
|
||||
private var request = 0
|
||||
@Volatile private var session = -1
|
||||
|
||||
fun state() = UpdatesState(catalog, follow, checking, error, stage, percent, askPermission)
|
||||
|
||||
@@ -87,13 +88,14 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
|
||||
if (SessionState.running) { error = activity.getString(R.string.upd_stop_first); return }
|
||||
if (!SelfInstaller.canInstall(activity)) { pending = r; askPermission = true; return }
|
||||
error = null
|
||||
session = -1
|
||||
stage = activity.getString(R.string.upd_stage_downloading)
|
||||
percent = 0
|
||||
Thread({
|
||||
val result = runCatching {
|
||||
val file = SelfInstaller.download(activity, apk) { pct -> ui.post { percent = pct } }
|
||||
ui.post { stage = activity.getString(R.string.upd_stage_installing); percent = -1 }
|
||||
SelfInstaller.install(activity, file)
|
||||
SelfInstaller.install(activity, file) { id -> session = id }
|
||||
}
|
||||
result.onFailure { e -> ui.post { stage = null; error = e.message ?: activity.getString(R.string.upd_failed) } }
|
||||
}, "app-update-install").start()
|
||||
@@ -101,13 +103,15 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
|
||||
|
||||
private val receiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
if (intent.getIntExtra(PackageInstaller.EXTRA_SESSION_ID, -1).let { it < 0 || it != session }) return
|
||||
when (val status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE)) {
|
||||
PackageInstaller.STATUS_PENDING_USER_ACTION -> {
|
||||
val confirm = if (Build.VERSION.SDK_INT >= 33) intent.getParcelableExtra(Intent.EXTRA_INTENT, Intent::class.java)
|
||||
else @Suppress("DEPRECATION") intent.getParcelableExtra(Intent.EXTRA_INTENT)
|
||||
if (confirm == null) { stage = null; error = activity.getString(R.string.upd_not_offered); return }
|
||||
val safe = confirm?.let { SelfInstaller.safeConfirmIntent(activity, it) }
|
||||
if (safe == null) { stage = null; error = activity.getString(R.string.upd_not_offered); return }
|
||||
stage = activity.getString(R.string.upd_stage_confirm)
|
||||
activity.startActivity(confirm.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
if (runCatching { activity.startActivity(safe) }.isFailure) { stage = null; error = activity.getString(R.string.upd_not_offered) }
|
||||
}
|
||||
PackageInstaller.STATUS_SUCCESS -> stage = null
|
||||
else -> {
|
||||
@@ -118,6 +122,7 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
|
||||
}
|
||||
}
|
||||
|
||||
@android.annotation.SuppressLint("UnspecifiedRegisterReceiverFlag")
|
||||
fun start() {
|
||||
catalog = AppUpdates.cached(activity)
|
||||
follow = AppUpdates.follow(activity, catalog)
|
||||
|
||||
@@ -3,9 +3,13 @@ package com.droiddeck.launcher.agent
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.runtime.ProotFastPath
|
||||
import com.droiddeck.launcher.session.SessionPhase
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.security.MessageDigest
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.LinkOption.NOFOLLOW_LINKS
|
||||
import java.nio.file.StandardOpenOption.READ
|
||||
@@ -55,6 +59,9 @@ object AgentEnv {
|
||||
fun override(context: Context, name: String): JSONObject = synchronized(lock) {
|
||||
AgentAccess.requireCommands(context)
|
||||
if (NAME.matchEntire(name) == null || name in setOf(".", "..")) throw AgentException("INVALID_NAME", "Override names are letters, digits, '.', '_' and '-'")
|
||||
if (name == "libblfastpath.so" && (SessionState.running || SessionState.guestPid > 0 || SessionState.phase == SessionPhase.STOPPING)) {
|
||||
throw AgentException("SESSION_ACTIVE", "Stop the session before installing a fast-path library")
|
||||
}
|
||||
val source = File(inbox(context), name)
|
||||
if (Files.isSymbolicLink(source.toPath())) throw AgentException("INVALID_NAME", "The override must be a regular file")
|
||||
if (!source.isFile) throw AgentException("NO_SUCH_FILE", "Push the binary to ${source.path} first")
|
||||
@@ -67,6 +74,10 @@ object AgentEnv {
|
||||
staged.delete()
|
||||
throw AgentException("OVERRIDE_FAILED", "Could not stage the override")
|
||||
}
|
||||
if (name == "libblfastpath.so" && !arm64SharedLibrary(staged)) {
|
||||
staged.delete()
|
||||
throw AgentException("INVALID_LIBRARY", "The fast path must be a 64-bit little-endian ARM64 ELF shared library")
|
||||
}
|
||||
if (!staged.setExecutable(true, false) || !staged.renameTo(target)) {
|
||||
staged.delete()
|
||||
throw AgentException("OVERRIDE_FAILED", "Could not install $name in the rootfs")
|
||||
@@ -76,6 +87,40 @@ object AgentEnv {
|
||||
state.put("pendingOverrides", JSONArray(merge(strings(state.optJSONArray("pendingOverrides")), listOf(name))))
|
||||
save(context, state)
|
||||
state.put("installed", "$GUEST_BIN/$name")
|
||||
if (name == "libblfastpath.so") {
|
||||
val digest = MessageDigest.getInstance("SHA-256")
|
||||
target.inputStream().use { input ->
|
||||
val buffer = ByteArray(65536)
|
||||
while (true) {
|
||||
val count = input.read(buffer)
|
||||
if (count < 0) break
|
||||
digest.update(buffer, 0, count)
|
||||
}
|
||||
}
|
||||
state.put("sha256", digest.digest().joinToString("") { "%02x".format(it) })
|
||||
}
|
||||
state
|
||||
}
|
||||
|
||||
fun fastPathLibrary(context: Context): String = synchronized(lock) {
|
||||
if (!AgentAccess.commandsAllowed(context)) return@synchronized ProotFastPath.LIBRARY
|
||||
if ("libblfastpath.so" !in strings(load(context).optJSONArray("activeOverrides"))) return@synchronized ProotFastPath.LIBRARY
|
||||
val file = File(bin(context), "libblfastpath.so")
|
||||
if (!file.isFile || Files.isSymbolicLink(file.toPath())) return@synchronized ProotFastPath.LIBRARY
|
||||
"$GUEST_BIN/libblfastpath.so"
|
||||
}
|
||||
|
||||
private fun arm64SharedLibrary(file: File): Boolean = file.inputStream().use { input ->
|
||||
val header = ByteArray(20)
|
||||
var count = 0
|
||||
while (count < header.size) {
|
||||
val read = input.read(header, count, header.size - count)
|
||||
if (read < 0) return@use false
|
||||
count += read
|
||||
}
|
||||
header.take(7) == listOf<Byte>(0x7f, 0x45, 0x4c, 0x46, 2, 1, 1) &&
|
||||
header[16] == 3.toByte() && header[17] == 0.toByte() &&
|
||||
header[18] == 183.toByte() && header[19] == 0.toByte()
|
||||
}
|
||||
|
||||
fun beginSession(context: Context): List<String> = synchronized(lock) {
|
||||
@@ -86,13 +131,13 @@ object AgentEnv {
|
||||
val state = load(context)
|
||||
val active = strings(state.optJSONArray("pending"))
|
||||
val overrides = strings(state.optJSONArray("pendingOverrides"))
|
||||
state.put("active", JSONArray(active)).put("pending", JSONArray())
|
||||
state.put("activeOverrides", JSONArray(overrides)).put("pendingOverrides", JSONArray())
|
||||
save(context, state)
|
||||
bin(context).listFiles()
|
||||
?.filter { it.name !in overrides }?.forEach { it.delete() }
|
||||
val lines = strings(state.optJSONArray("persistent")) + active
|
||||
val withPath = if (overrides.isEmpty()) lines else lines + "PATH=$GUEST_BIN:${pathOf(lines)}"
|
||||
val withPath = if (overrides.none { it != "libblfastpath.so" }) lines else lines + "PATH=$GUEST_BIN:${pathOf(lines)}"
|
||||
state.put("active", JSONArray(active)).put("pending", JSONArray())
|
||||
state.put("activeOverrides", JSONArray(overrides)).put("pendingOverrides", JSONArray())
|
||||
save(context, state)
|
||||
if (withPath.isNotEmpty()) Log.i(TAG, "agent environment keys for this session: ${withPath.map { it.substringBefore('=') }}")
|
||||
withPath
|
||||
}
|
||||
|
||||
@@ -22,6 +22,14 @@ object AgentGuest {
|
||||
private set
|
||||
var steamKeyboard by mutableStateOf(false)
|
||||
private set
|
||||
var desktopTextField by mutableStateOf(false)
|
||||
private set
|
||||
var keyboardRequests by mutableIntStateOf(0)
|
||||
private set
|
||||
var keyboardDismissals by mutableIntStateOf(0)
|
||||
private set
|
||||
@Volatile private var keyboardRoute = false
|
||||
@Volatile private var routeDir: File? = null
|
||||
private const val TAG = "AgentGuest"
|
||||
private const val POLL_MS = 50L
|
||||
private val lock = Any()
|
||||
@@ -35,10 +43,12 @@ object AgentGuest {
|
||||
observer?.stopWatching()
|
||||
observer = null
|
||||
lastFocusKey = null
|
||||
main.post { steamKeyboard = false }
|
||||
main.post { steamKeyboard = false; desktopTextField = false }
|
||||
val dir = dir(context)
|
||||
dir.deleteRecursively()
|
||||
dir.mkdirs()
|
||||
routeDir = dir
|
||||
writeKeyboardRoute(dir, keyboardRoute)
|
||||
@Suppress("DEPRECATION")
|
||||
observer = object : FileObserver(dir.path, MOVED_TO or CLOSE_WRITE) {
|
||||
override fun onEvent(event: Int, path: String?) {
|
||||
@@ -48,6 +58,9 @@ object AgentGuest {
|
||||
}
|
||||
"focus.json" -> readJson(File(dir, path))?.let(::recordFocus)
|
||||
"keyboard.json" -> readJson(File(dir, path))?.let { recordKeyboard(this, it) }
|
||||
"ime.json" -> readJson(File(dir, path))?.let { recordTextField(this, it) }
|
||||
"keyboard-request.json" -> readJson(File(dir, path))?.let { recordKeyboardRequest(this) }
|
||||
"keyboard-dismiss.json" -> readJson(File(dir, path))?.let { recordKeyboardDismiss(this) }
|
||||
}
|
||||
}
|
||||
}.also { it.startWatching() }
|
||||
@@ -58,10 +71,46 @@ object AgentGuest {
|
||||
synchronized(lock) {
|
||||
observer?.stopWatching()
|
||||
observer = null
|
||||
main.post { steamKeyboard = false }
|
||||
main.post { steamKeyboard = false; desktopTextField = false }
|
||||
}
|
||||
}
|
||||
|
||||
fun routeKeyboard(context: Context, bottom: Boolean) {
|
||||
synchronized(lock) {
|
||||
if (keyboardRoute == bottom) return
|
||||
keyboardRoute = bottom
|
||||
writeKeyboardRoute(routeDir ?: dir(context), bottom)
|
||||
}
|
||||
}
|
||||
|
||||
private fun writeKeyboardRoute(dir: File, bottom: Boolean) {
|
||||
val file = File(dir, "keyboard-route")
|
||||
runCatching {
|
||||
if (!bottom) file.delete()
|
||||
else if (dir.isDirectory) {
|
||||
val temp = File(dir, "keyboard-route.tmp")
|
||||
temp.writeText("bottom")
|
||||
if (!temp.renameTo(file)) temp.delete()
|
||||
}
|
||||
}.onFailure { Log.w(TAG, "keyboard route not written", it) }
|
||||
}
|
||||
|
||||
private fun recordKeyboardRequest(source: FileObserver) {
|
||||
synchronized(lock) {
|
||||
if (source !== observer) return
|
||||
main.post { keyboardRequests++ }
|
||||
}
|
||||
SessionEvents.record("keyboard.requested", emptyMap())
|
||||
}
|
||||
|
||||
private fun recordKeyboardDismiss(source: FileObserver) {
|
||||
synchronized(lock) {
|
||||
if (source !== observer) return
|
||||
main.post { keyboardDismissals++ }
|
||||
}
|
||||
SessionEvents.record("keyboard.dismissed", emptyMap())
|
||||
}
|
||||
|
||||
private fun recordKeyboard(source: FileObserver, snapshot: JSONObject) {
|
||||
val showing = snapshot.optBoolean("steamKeyboard")
|
||||
synchronized(lock) {
|
||||
@@ -71,6 +120,15 @@ object AgentGuest {
|
||||
SessionEvents.record("keyboard.changed", mapOf("steamKeyboard" to showing, "seq" to snapshot.optInt("seq")))
|
||||
}
|
||||
|
||||
private fun recordTextField(source: FileObserver, snapshot: JSONObject) {
|
||||
val focused = snapshot.optBoolean("textField")
|
||||
synchronized(lock) {
|
||||
if (source !== observer) return
|
||||
main.post { desktopTextField = focused }
|
||||
}
|
||||
SessionEvents.record("ime.changed", mapOf("textField" to focused, "seq" to snapshot.optInt("seq")))
|
||||
}
|
||||
|
||||
private fun recordFocus(snapshot: JSONObject) {
|
||||
val fields = linkedMapOf<String, Any?>(
|
||||
"focusedApp" to snapshot.opt("focusedApp"),
|
||||
|
||||
@@ -23,6 +23,9 @@ class AgentStartActivity : Activity() {
|
||||
Thread({
|
||||
try {
|
||||
AgentBridgeProvider.awaitRecovery()
|
||||
val until = android.os.SystemClock.elapsedRealtime() + RUNTIME_WAIT_MS
|
||||
while (com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.isBusy() && !isFinishing &&
|
||||
android.os.SystemClock.elapsedRealtime() < until) Thread.sleep(RUNTIME_POLL_MS)
|
||||
runOnUiThread {
|
||||
if (!isFinishing) startSession(request)
|
||||
}
|
||||
@@ -51,6 +54,11 @@ class AgentStartActivity : Activity() {
|
||||
}
|
||||
|
||||
private fun startSession(request: JSONObject) {
|
||||
if (com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.isBusy()) {
|
||||
Log.w(TAG, "the Linux runtime is being installed or changed")
|
||||
finish()
|
||||
return
|
||||
}
|
||||
try {
|
||||
AgentAccess.requireStart(this, request)
|
||||
} catch (e: AgentException) {
|
||||
@@ -107,5 +115,7 @@ class AgentStartActivity : Activity() {
|
||||
companion object {
|
||||
const val EXTRA_REQUEST = "request"
|
||||
private const val TAG = "AgentStartActivity"
|
||||
private const val RUNTIME_WAIT_MS = 15 * 60_000L
|
||||
private const val RUNTIME_POLL_MS = 500L
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.audio;
|
||||
import android.os.Process;
|
||||
import android.util.Log;
|
||||
|
||||
import com.droiddeck.launcher.core.FileUtils;
|
||||
import com.droiddeck.launcher.core.SessionPart;
|
||||
import com.droiddeck.launcher.core.HostProcess;
|
||||
|
||||
@@ -19,10 +20,13 @@ public class DirectAudioRelayComponent extends SessionPart {
|
||||
private volatile int pid = -1;
|
||||
private final Object micLock = new Object();
|
||||
private boolean micHot;
|
||||
private final File micControl;
|
||||
public java.util.function.Consumer<Boolean> onMicEnabled;
|
||||
|
||||
public DirectAudioRelayComponent(File socketPath, File micFifoPath) {
|
||||
this.socketPath = socketPath;
|
||||
this.micFifoPath = micFifoPath;
|
||||
this.micControl = micFifoPath == null ? null : new File(micFifoPath.getParentFile(), "mic-enabled");
|
||||
}
|
||||
|
||||
public void setLogFile(File file) {
|
||||
@@ -63,8 +67,13 @@ public class DirectAudioRelayComponent extends SessionPart {
|
||||
StringBuilder command = new StringBuilder(binary.getAbsolutePath());
|
||||
command.append(" --socket ").append(socketPath.getAbsolutePath());
|
||||
command.append(" --log");
|
||||
if (micFifoPath != null) {
|
||||
final boolean withMic = micFifoPath != null && setMicEnabled(true);
|
||||
if (withMic) {
|
||||
command.append(" --mic-fifo ").append(micFifoPath.getAbsolutePath());
|
||||
command.append(" --mic-control ").append(micControl.getAbsolutePath());
|
||||
} else if (micFifoPath != null) {
|
||||
Log.w(TAG, "microphone control unavailable; starting with capture disabled");
|
||||
command.append(" --mic-control /dev/null");
|
||||
}
|
||||
ArrayList<String> env = new ArrayList<>();
|
||||
env.add("HOME=" + app().getFilesDir());
|
||||
@@ -73,7 +82,7 @@ public class DirectAudioRelayComponent extends SessionPart {
|
||||
try {
|
||||
out = new java.io.PrintWriter(new java.io.FileWriter(logFile, true));
|
||||
out.println("== DirectAudio relay helper starting"
|
||||
+ (micFifoPath != null ? " with the microphone" : " (no microphone)"));
|
||||
+ (withMic ? " with the microphone" : " (no microphone)"));
|
||||
out.flush();
|
||||
} catch (Exception e) {
|
||||
Log.w(TAG, "could not open " + logFile, e);
|
||||
@@ -84,14 +93,23 @@ public class DirectAudioRelayComponent extends SessionPart {
|
||||
app().getFilesDir(), null,
|
||||
line -> {
|
||||
Log.i(TAG, line);
|
||||
trackMic(line);
|
||||
if (withMic) trackMic(line);
|
||||
if (log != null) synchronized (log) { log.println(line); log.flush(); }
|
||||
});
|
||||
Log.i(TAG, "started pid=" + pid + " socket=" + socketPath
|
||||
+ (micFifoPath != null ? " mic=" + micFifoPath : " (no microphone)"));
|
||||
+ (withMic ? " mic=" + micFifoPath : " (no microphone)"));
|
||||
}
|
||||
|
||||
public synchronized boolean setMicEnabled(boolean enabled) {
|
||||
if (micControl == null) return false;
|
||||
File next = new File(micControl.getPath() + ".new");
|
||||
return FileUtils.writeString(next, enabled ? "1" : "0") && next.renameTo(micControl);
|
||||
}
|
||||
|
||||
private void trackMic(String line) {
|
||||
if (line.startsWith("DA-Relay: mic enabled=") && onMicEnabled != null) {
|
||||
onMicEnabled.accept(line.equals("DA-Relay: mic enabled=1"));
|
||||
}
|
||||
boolean start = line.startsWith("DA-Relay: mic start ");
|
||||
if (!start && !line.startsWith("DA-Relay: mic stop ")) return;
|
||||
synchronized (micLock) {
|
||||
@@ -100,7 +118,6 @@ public class DirectAudioRelayComponent extends SessionPart {
|
||||
}
|
||||
}
|
||||
|
||||
// Android keeps the input stream's wake lock while a frozen helper still has it started.
|
||||
public boolean awaitMicReleased(long timeoutMs) {
|
||||
long deadline = System.currentTimeMillis() + timeoutMs;
|
||||
synchronized (micLock) {
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.droiddeck.launcher.audio
|
||||
|
||||
import android.media.AudioAttributes
|
||||
import android.media.AudioFormat
|
||||
import android.media.AudioTrack
|
||||
import android.util.Log
|
||||
|
||||
object DirectAudioTiming {
|
||||
private const val TAG = "DirectAudioTiming"
|
||||
const val PERIOD_ENV = "AUDIO_DIRECT_PERIOD_MS"
|
||||
const val BUFFER_ENV = "AUDIO_DIRECT_MS"
|
||||
const val SLOW_OUTPUT_PERIOD_MS = 20
|
||||
const val SLOW_OUTPUT_BUFFER_MS = 60
|
||||
|
||||
fun environment(lowLatencyOutput: Boolean): List<String> =
|
||||
if (lowLatencyOutput) emptyList()
|
||||
else listOf("$PERIOD_ENV=$SLOW_OUTPUT_PERIOD_MS", "$BUFFER_ENV=$SLOW_OUTPUT_BUFFER_MS")
|
||||
|
||||
fun lowLatencyOutput(): Boolean = try {
|
||||
val track = AudioTrack.Builder()
|
||||
.setAudioAttributes(AudioAttributes.Builder()
|
||||
.setUsage(AudioAttributes.USAGE_GAME)
|
||||
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
|
||||
.build())
|
||||
.setAudioFormat(AudioFormat.Builder()
|
||||
.setEncoding(AudioFormat.ENCODING_PCM_FLOAT)
|
||||
.setSampleRate(48000)
|
||||
.setChannelMask(AudioFormat.CHANNEL_OUT_STEREO)
|
||||
.build())
|
||||
.setPerformanceMode(AudioTrack.PERFORMANCE_MODE_LOW_LATENCY)
|
||||
.setTransferMode(AudioTrack.MODE_STREAM)
|
||||
.build()
|
||||
try {
|
||||
track.performanceMode == AudioTrack.PERFORMANCE_MODE_LOW_LATENCY
|
||||
} finally {
|
||||
track.release()
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "audio: could not check for low-latency output; DirectAudio keeps its defaults", e)
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,7 @@ public class PulseAudioComponent extends SessionPart {
|
||||
|
||||
|
||||
private final File workingDir;
|
||||
private final File deviceControls;
|
||||
private File logFile;
|
||||
private final String micFifoPath;
|
||||
private volatile int pid = -1;
|
||||
@@ -36,6 +37,8 @@ public class PulseAudioComponent extends SessionPart {
|
||||
|
||||
public PulseAudioComponent(Context context, String micFifoPath) {
|
||||
this.workingDir = new File(context.getFilesDir(), "pulseaudio");
|
||||
this.deviceControls = com.droiddeck.launcher.runtime.DeviceControlsComponent.directory(
|
||||
com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context));
|
||||
this.micFifoPath = micFifoPath;
|
||||
}
|
||||
|
||||
@@ -94,7 +97,7 @@ public class PulseAudioComponent extends SessionPart {
|
||||
config.add("load-module module-native-protocol-unix auth-anonymous=1 auth-cookie-enabled=0 socket=\""
|
||||
+ socket().getAbsolutePath() + "\"");
|
||||
config.add(".nofail");
|
||||
config.add("load-module module-directaudio-native-sink sink_name=DirectAudio performance_mode=1 adaptive=1 decay=0 limiter=1 watchdog=1 volume=1.0");
|
||||
config.add("load-module module-directaudio-native-sink sink_name=DirectAudio performance_mode=1 adaptive=1 decay=0 limiter=1 watchdog=1 volume=1.0 control_dir=" + deviceControls);
|
||||
config.add("set-default-sink DirectAudio");
|
||||
config.add(".fail");
|
||||
if (micFifoPath != null && !micFifoPath.isEmpty()) {
|
||||
@@ -139,7 +142,7 @@ public class PulseAudioComponent extends SessionPart {
|
||||
} else if (sinks.contains("\tDirectAudio\t") || sinks.startsWith("DirectAudio\t") || sinks.contains("\tDirectAudio\n") || sinks.matches("(?s).*\\bDirectAudio\\b.*")) {
|
||||
line = "== client sink: DirectAudio (module-directaudio-native-sink)";
|
||||
} else {
|
||||
boolean loaded = pactl("load-module", "module-aaudio-sink", "sink_name=AAudioSink", "performance_mode=1", "adaptive=1", "volume=1.0") != null
|
||||
boolean loaded = pactl("load-module", "module-aaudio-sink", "sink_name=AAudioSink", "performance_mode=1", "adaptive=1", "volume=1.0", "control_dir=" + deviceControls) != null
|
||||
&& pactl("set-default-sink", "AAudioSink") != null;
|
||||
line = loaded ? "== client sink: DirectAudio did not come up; FALLBACK to the plain AAudio sink (AAudioSink)"
|
||||
: "== client sink: DirectAudio did not come up and the AAudio fallback failed too - no client sound";
|
||||
|
||||
@@ -13,15 +13,10 @@ import kotlinx.coroutines.launch
|
||||
import java.io.File
|
||||
import java.io.FileInputStream
|
||||
|
||||
/**
|
||||
* A pack built by CI alongside this APK (tools/packs). Main and release builds publish it to
|
||||
* DroidDeck-Components under a content-addressed tag; a PR test build attaches packs that are not there
|
||||
* yet to its pr-N release on DroidDeck-CI. The APK pins the pack's SHA-256, so only the bytes this build
|
||||
* was made with install, whichever host serves them.
|
||||
*/
|
||||
internal class AddonPack(
|
||||
val name: String, private val sha256: String, val size: Long, private val required: List<String>,
|
||||
private val reuseDeviceCopy: Boolean = sha256.isEmpty() && !BuildConfig.CI_BUILD,
|
||||
private val bundle: (Context) -> java.io.InputStream = { it.assets.open("packs/$name.tar.zst") },
|
||||
) {
|
||||
sealed interface State {
|
||||
data object Missing : State
|
||||
@@ -42,13 +37,11 @@ internal class AddonPack(
|
||||
)
|
||||
|
||||
private fun root(context: Context) = File(context.filesDir, "addons/$name")
|
||||
/** App-private and written only after the archive matched the pinned digest. */
|
||||
fun dir(context: Context) = File(root(context), version(context))
|
||||
fun file(context: Context, relative: String) = File(dir(context), relative)
|
||||
|
||||
fun installed(context: Context): Boolean = version(context).isNotEmpty() && File(dir(context), COMPLETE).isFile
|
||||
|
||||
// A build made outside CI pins no packs, so it runs the newest one a CI build already verified and installed.
|
||||
private fun version(context: Context): String = if (!reuseDeviceCopy) sha256 else deviceCopy(context).orEmpty()
|
||||
|
||||
private fun deviceCopy(context: Context): String? = root(context).listFiles().orEmpty()
|
||||
@@ -65,7 +58,6 @@ internal class AddonPack(
|
||||
.also { mutableState.value = it }
|
||||
}
|
||||
|
||||
/** Starts the download in the background unless the pack is already present or on its way. */
|
||||
fun ensure(context: Context, onReady: (Context) -> Unit = {}) {
|
||||
val app = context.applicationContext
|
||||
synchronized(lock) {
|
||||
@@ -80,7 +72,6 @@ internal class AddonPack(
|
||||
}
|
||||
}
|
||||
|
||||
/** Blocks a worker thread until the pack is installed, starting the download if needed. */
|
||||
@JvmOverloads
|
||||
fun await(context: Context, running: () -> Boolean = { true }, onState: (State) -> Unit = {}): Boolean {
|
||||
if (installed(context)) return true
|
||||
@@ -104,7 +95,7 @@ internal class AddonPack(
|
||||
}
|
||||
val root = root(context).apply { mkdirs() }
|
||||
val archive = File(root, "$sha256.tar.zst")
|
||||
val downloaded = urls.any { url ->
|
||||
val downloaded = bundled(context, archive) || urls.any { url ->
|
||||
Downloader.downloadFile(url, archive, true, sha256) { p -> mutableState.value = State.Downloading(p.coerceIn(0f, 1f)) }
|
||||
.also { if (!it) archive.delete() }
|
||||
}
|
||||
@@ -126,6 +117,16 @@ internal class AddonPack(
|
||||
return true
|
||||
}
|
||||
|
||||
internal fun bundled(context: Context, archive: File): Boolean {
|
||||
val copied = runCatching {
|
||||
bundle(context).use { input -> archive.outputStream().use { input.copyTo(it) } }
|
||||
}.isSuccess
|
||||
if (copied && Hashes.sha256(archive).equals(sha256, ignoreCase = true)) return true
|
||||
if (copied) Log.w(TAG, "$name: the bundled pack does not match the pinned digest")
|
||||
archive.delete()
|
||||
return false
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "AddonPack"
|
||||
private const val REPO = "Droid-Deck/DroidDeck-Components"
|
||||
@@ -146,5 +147,7 @@ internal class AddonPack(
|
||||
listOf("version", "xodus-cli", "xodus-service"))
|
||||
val COMET = AddonPack("comet", BuildConfig.PACK_COMET_SHA256, BuildConfig.PACK_COMET_SIZE,
|
||||
listOf("version", "comet"))
|
||||
val BUTLER = AddonPack("butler", BuildConfig.PACK_BUTLER_SHA256, BuildConfig.PACK_BUTLER_SIZE,
|
||||
listOf("version", "butler", "7z.so", "libc7zip.so"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import android.Manifest
|
||||
import android.app.Activity
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.provider.Settings
|
||||
|
||||
object AppPermissions {
|
||||
fun granted(context: Context, permission: String): Boolean =
|
||||
context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
|
||||
|
||||
fun localNetwork(context: Context): Boolean = Build.VERSION.SDK_INT < 37 ||
|
||||
granted(context, Manifest.permission.ACCESS_LOCAL_NETWORK)
|
||||
|
||||
fun startup(activity: Activity): List<String> = buildList {
|
||||
if (Build.VERSION.SDK_INT >= 37 && !localNetwork(activity) &&
|
||||
!activity.getSharedPreferences("runtime-permissions", Context.MODE_PRIVATE).getBoolean("local-network", false)) {
|
||||
add(Manifest.permission.ACCESS_LOCAL_NETWORK)
|
||||
activity.getSharedPreferences("runtime-permissions", Context.MODE_PRIVATE).edit().putBoolean("local-network", true).apply()
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= 33 && !granted(activity, Manifest.permission.POST_NOTIFICATIONS) &&
|
||||
!activity.getSharedPreferences("stores", Context.MODE_PRIVATE).getBoolean("asked_notifications", false)) {
|
||||
add(Manifest.permission.POST_NOTIFICATIONS)
|
||||
activity.getSharedPreferences("stores", Context.MODE_PRIVATE).edit().putBoolean("asked_notifications", true).apply()
|
||||
}
|
||||
}
|
||||
|
||||
fun requestLocalNetwork(activity: Activity, requestCode: Int) {
|
||||
if (Build.VERSION.SDK_INT < 37) return
|
||||
val prefs = activity.getSharedPreferences("runtime-permissions", Context.MODE_PRIVATE)
|
||||
if (localNetwork(activity) || prefs.getBoolean("local-network", false) &&
|
||||
!activity.shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_LOCAL_NETWORK)) {
|
||||
openSettings(activity)
|
||||
} else {
|
||||
prefs.edit().putBoolean("local-network", true).apply()
|
||||
activity.requestPermissions(arrayOf(Manifest.permission.ACCESS_LOCAL_NETWORK), requestCode)
|
||||
}
|
||||
}
|
||||
|
||||
fun openSettings(context: Context) {
|
||||
runCatching {
|
||||
context.startActivity(Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:${context.packageName}"))
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,32 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import android.content.Context
|
||||
import android.content.pm.ActivityInfo
|
||||
import com.droiddeck.launcher.R
|
||||
|
||||
object AppUiPrefs {
|
||||
const val DEFAULT_SCALE = 100
|
||||
val scales = listOf(75, 85, 100, 115, 125, 150)
|
||||
|
||||
val orientationOptions = listOf(
|
||||
ActivityInfo.SCREEN_ORIENTATION_USER to R.string.setup_launcher_orientation_auto,
|
||||
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT to R.string.setup_orientation_portrait,
|
||||
ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE to R.string.setup_orientation_auto,
|
||||
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE to R.string.setup_orientation_landscape,
|
||||
ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE to R.string.setup_orientation_reverse,
|
||||
)
|
||||
|
||||
fun orientation(context: Context): Int =
|
||||
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE)
|
||||
.getInt("orientation", ActivityInfo.SCREEN_ORIENTATION_USER)
|
||||
.takeIf { value -> orientationOptions.any { it.first == value } }
|
||||
?: ActivityInfo.SCREEN_ORIENTATION_USER
|
||||
|
||||
fun setOrientation(context: Context, value: Int) {
|
||||
require(orientationOptions.any { it.first == value })
|
||||
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putInt("orientation", value).apply()
|
||||
}
|
||||
|
||||
internal fun normalizeScale(percent: Int): Int = percent.takeIf { it in scales } ?: DEFAULT_SCALE
|
||||
|
||||
fun scale(context: Context): Int = normalizeScale(
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
object BackgroundAppLimit {
|
||||
private const val TAG = "BackgroundAppLimit"
|
||||
const val OFF = -1
|
||||
val CHOICES = listOf(OFF, 4, 1, 0)
|
||||
private const val KEY = "max_cached_processes"
|
||||
private const val STATE = "background-app-limit"
|
||||
private const val APPLIED = "applied"
|
||||
private const val PREVIOUS = "previous"
|
||||
|
||||
private val worker = Executors.newSingleThreadExecutor { Thread(it, "background-app-limit").apply { isDaemon = true } }
|
||||
|
||||
internal fun readCommand() = "device_config get activity_manager $KEY"
|
||||
internal fun setCommand(limit: Int): String {
|
||||
require(limit in 0..1024)
|
||||
return "device_config put activity_manager $KEY $limit"
|
||||
}
|
||||
internal fun restoreCommand(previous: String?) =
|
||||
if (previous == null) "device_config delete activity_manager $KEY" else "device_config put activity_manager $KEY $previous"
|
||||
|
||||
internal fun parse(output: String): String? = output.trim().takeIf { it.toIntOrNull() != null }
|
||||
|
||||
private fun state(context: Context) = context.applicationContext.getSharedPreferences(STATE, Context.MODE_PRIVATE)
|
||||
|
||||
fun applied(context: Context): Boolean = state(context).getBoolean(APPLIED, false)
|
||||
|
||||
fun applyAsync(context: Context, limit: Int) {
|
||||
val app = context.applicationContext
|
||||
worker.execute {
|
||||
runCatching {
|
||||
if (!applied(app)) {
|
||||
val previous = parse(WirelessAdbFix.shell(app, readCommand()))
|
||||
check(state(app).edit().putBoolean(APPLIED, true).putString(PREVIOUS, previous).commit()) { "previous value not saved" }
|
||||
}
|
||||
WirelessAdbFix.shell(app, setCommand(limit))
|
||||
}.onSuccess { Log.i(TAG, "at most $limit cached app(s) while the session runs") }
|
||||
.onFailure { Log.w(TAG, "limit not set: ${it.message}") }
|
||||
}
|
||||
}
|
||||
|
||||
fun restoreAsync(context: Context) {
|
||||
val app = context.applicationContext
|
||||
worker.execute {
|
||||
if (!applied(app)) return@execute
|
||||
val previous = state(app).getString(PREVIOUS, null)
|
||||
runCatching { WirelessAdbFix.shell(app, restoreCommand(previous)) }
|
||||
.onSuccess {
|
||||
state(app).edit().putBoolean(APPLIED, false).remove(PREVIOUS).commit()
|
||||
Log.i(TAG, "cached-app limit put back (${previous ?: "Android's own"})")
|
||||
}
|
||||
.onFailure { Log.w(TAG, "limit not put back yet: ${it.message}") }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import com.droiddeck.launcher.gpu.GpuInfo
|
||||
import com.droiddeck.launcher.gpu.SocNames
|
||||
|
||||
object CpuAllocationDefaults {
|
||||
data class Allocation(val client: String, val game: String)
|
||||
|
||||
val device: Allocation? by lazy {
|
||||
forDevice(SocNames.model(), GpuInfo.systemProperty("ro.board.platform"),
|
||||
CpuCores.all.associateWith(CpuCores::maxGhz))
|
||||
}
|
||||
|
||||
fun forDevice(model: String, platform: String, frequencies: Map<Int, Double?>): Allocation? {
|
||||
val chip = model.trim().uppercase().substringBefore('-')
|
||||
val gen2 = chip in setOf("SM8550", "QCS8550") ||
|
||||
(chip.isEmpty() && platform.trim().equals("kalama", ignoreCase = true))
|
||||
if (!gen2 || frequencies.size != 8 || frequencies.keys.any { it < 0 } ||
|
||||
frequencies.values.any { it == null || !it.isFinite() || it <= 0.0 }) return null
|
||||
val clusters = frequencies.entries.groupBy { it.value }.toSortedMap(compareBy { it ?: 0.0 }).values.toList()
|
||||
if (clusters.map { it.size } != listOf(3, 4, 1)) return null
|
||||
return Allocation(
|
||||
client = CpuCores.format(clusters[2].map { it.key }.toSet()),
|
||||
game = CpuCores.format(clusters[1].map { it.key }.toSet()),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,11 @@ import java.util.Locale
|
||||
object DeviceReport {
|
||||
private const val TAG = "DeviceReport"
|
||||
|
||||
internal fun cpuFeaturesSummary(cpuInfo: String): String = cpuInfo.lineSequence()
|
||||
.filter { it.substringBefore(':').trim() == "Features" }
|
||||
.map { it.substringAfter(':').trim().split(Regex("\\s+")).filter(String::isNotEmpty).joinToString(" ") }
|
||||
.filter(String::isNotEmpty).distinct().joinToString(" | ").ifEmpty { "not reported" }
|
||||
|
||||
fun write(context: Context, target: File, mode: String) {
|
||||
try {
|
||||
target.writeText(build(context, mode))
|
||||
@@ -37,7 +42,6 @@ object DeviceReport {
|
||||
}
|
||||
}
|
||||
|
||||
/** Name of an ApplicationExitInfo reason code, so a report says "LOW_MEMORY" instead of "3". */
|
||||
internal fun exitReasonName(reason: Int): String = when (reason) {
|
||||
0 -> "UNKNOWN"
|
||||
1 -> "EXIT_SELF"
|
||||
@@ -105,7 +109,7 @@ object DeviceReport {
|
||||
h("App")
|
||||
runCatching {
|
||||
val info = context.packageManager.getPackageInfo(context.packageName, 0)
|
||||
k("Version", "${info.versionName} (${info.longVersionCode})")
|
||||
k("Version", "${info.versionName} (${androidx.core.content.pm.PackageInfoCompat.getLongVersionCode(info)})")
|
||||
}
|
||||
k("Package", context.packageName)
|
||||
k("targetSdk", context.applicationInfo.targetSdkVersion)
|
||||
@@ -141,6 +145,7 @@ object DeviceReport {
|
||||
|
||||
h("CPU and memory")
|
||||
k("Cores", CpuCores.all.size)
|
||||
k("CPU features", cpuFeaturesSummary(FileUtils.readString(File("/proc/cpuinfo")).orEmpty()))
|
||||
b.append("Core ceilings ")
|
||||
b.append(CpuCores.all.joinToString(", ") { c ->
|
||||
"cpu$c " + (CpuCores.maxGhz(c)?.let { String.format(Locale.US, "%.2f GHz", it) } ?: "?")
|
||||
@@ -152,13 +157,17 @@ object DeviceReport {
|
||||
k("RAM total", FileUtils.sizeToString(mi.totalMem))
|
||||
k("RAM available", FileUtils.sizeToString(mi.availMem))
|
||||
}
|
||||
runCatching {
|
||||
val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) k("Thermal status", thermalStatusName(pm.currentThermalStatus))
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
k("Thermal headroom (10 s)", pm.getThermalHeadroom(10).let { if (it.isNaN()) "not reported" else String.format(Locale.US, "%.2f", it) })
|
||||
val pm = runCatching { context.getSystemService(Context.POWER_SERVICE) as? PowerManager }.getOrNull()
|
||||
if (pm != null) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
k("Thermal status", runCatching { thermalStatusName(pm.currentThermalStatus) }.getOrNull())
|
||||
}
|
||||
k("Power saver", pm.isPowerSaveMode)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
k("Thermal headroom (10 s)", runCatching {
|
||||
pm.getThermalHeadroom(10).let { if (it.isNaN()) "not reported" else String.format(Locale.US, "%.2f", it) }
|
||||
}.getOrNull())
|
||||
}
|
||||
k("Power saver", runCatching { pm.isPowerSaveMode }.getOrNull())
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
val rate = runCatching { context.getSystemService(PerformanceHintManager::class.java)?.preferredUpdateRateNanos }.getOrNull()
|
||||
@@ -200,7 +209,12 @@ object DeviceReport {
|
||||
h("Drivers")
|
||||
val gpu = com.droiddeck.launcher.gpu.GpuInfo.detect()
|
||||
k("GPU", "${gpu.name} · ${gpu.family.label} · ${gpu.supportText}" + if (gpu.oneUi8Gen2) " · One UI 8 Gen 2" else "")
|
||||
if (gpu.model == 740) k("TP UBWC hint", com.droiddeck.launcher.gpu.TpUbwcHint.forThisDevice() ?: "driver default")
|
||||
if (gpu.model == 740) {
|
||||
val hint = com.droiddeck.launcher.gpu.TpUbwcHint
|
||||
k("TP UBWC hint", hint.forThisDevice(context) ?: "driver default")
|
||||
k("TP UBWC mode", hint.activeMode ?: SessionPrefs.TP_UBWC_AUTO)
|
||||
if (hint.restartRequired(context)) k("TP UBWC pending", "${SessionPrefs.tpUbwcMode(context)} (restart required)")
|
||||
}
|
||||
k("Driver mode", SessionPrefs.gpuDriverMode(context) +
|
||||
(com.droiddeck.launcher.gpu.DriverPairs.recommendedKey(gpu, com.droiddeck.launcher.gpu.DriverPairs.from(
|
||||
com.droiddeck.launcher.gpu.TurnipReleases.cached(context)), com.droiddeck.launcher.gpu.TurnipReleases.autoPicks(context),
|
||||
@@ -247,8 +261,13 @@ object DeviceReport {
|
||||
EsyncPacks.status(LinuxRuntime.rootDir(context)).let { k("droiddeck-esync packs", "${it.installed} installed, ${it.wanted} wanted") }
|
||||
k("Linux x86 (FEX)", if (com.droiddeck.launcher.runtime.LinuxFex.ready(context)) "ready" else "not set up")
|
||||
k("gamescope realtime", SessionPrefs.gamescopeRealtime(context))
|
||||
k("zRAM: compress Steam during games", SessionPrefs.zramClient(context))
|
||||
k("RAM cap", SessionPrefs.ramCapMb(context).let { if (it > 0) "$it MB" else "off" })
|
||||
k("VRAM cap", SessionPrefs.vramCapMb(context).let { if (it > 0) "$it MB" else "driver default" })
|
||||
k("proot without seccomp", SessionPrefs.prootNoSeccomp(context))
|
||||
k("proot fast path", SessionPrefs.prootFastPath(context))
|
||||
k("proot binary", LinuxRuntime.prootSource(context) + " " + LinuxRuntime.prootBinary(context).path)
|
||||
k("proot fast path (eligible)", com.droiddeck.launcher.runtime.ProotFastPath.enabled(context))
|
||||
k("Guest host name", SessionPrefs.guestHostname(context))
|
||||
k("DirectAudio for games", SessionPrefs.directAudio(context))
|
||||
k("Stretch 16:9 to panel", SessionPrefs.stretch16x9(context))
|
||||
|
||||
@@ -3,6 +3,8 @@ package com.droiddeck.launcher.core
|
||||
import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.InetSocketAddress
|
||||
import java.net.Proxy
|
||||
import java.net.URL
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import java.util.concurrent.CountDownLatch
|
||||
@@ -20,6 +22,7 @@ object DownloadSource {
|
||||
private const val KEY_MODE = "mode"
|
||||
private const val KEY_MIRROR = "mirror"
|
||||
private const val KEY_CUSTOM = "custom"
|
||||
private const val KEY_PROXY = "proxy"
|
||||
private const val KEY_FASTEST = "fastest"
|
||||
|
||||
private const val PROBE = "https://raw.githubusercontent.com/Droid-Deck/DroidDeck/main/README.md"
|
||||
@@ -123,11 +126,9 @@ object DownloadSource {
|
||||
|
||||
fun isGithub(url: String): Boolean = GITHUB_HOSTS.any { url.startsWith("https://$it/") }
|
||||
|
||||
/** Catalogs carry the digests everything else is checked against, so a mirror must never supply one. */
|
||||
fun isCatalog(url: String): Boolean = CATALOGS.any { url.startsWith(it) }
|
||||
|
||||
fun candidates(target: String): List<String> {
|
||||
// GitHub API metadata carries executable URLs and digests; never proxy it.
|
||||
if (isCatalog(target) || target.startsWith("https://api.github.com/")) return listOf(target)
|
||||
val prefs = prefs() ?: return listOf(target)
|
||||
if (!isGithub(target)) return listOf(target)
|
||||
@@ -175,6 +176,21 @@ object DownloadSource {
|
||||
prefs(context)?.edit()?.putString(KEY_CUSTOM, normalizePrefix(prefix))?.apply()
|
||||
}
|
||||
|
||||
fun proxyHostPort(context: Context): String = prefs(context)?.getString(KEY_PROXY, "") ?: ""
|
||||
|
||||
fun setProxy(context: Context, value: String) {
|
||||
prefs(context)?.edit()?.putString(KEY_PROXY, normalizeProxy(value))?.apply()
|
||||
}
|
||||
|
||||
fun httpProxy(): Proxy? = proxyOf(prefs()?.getString(KEY_PROXY, "") ?: "")
|
||||
|
||||
internal fun proxyOf(value: String): Proxy? {
|
||||
val host = value.substringBefore(':')
|
||||
val port = value.substringAfter(':', "").toIntOrNull() ?: return null
|
||||
if (host.isEmpty()) return null
|
||||
return Proxy(Proxy.Type.HTTP, InetSocketAddress(host, port))
|
||||
}
|
||||
|
||||
fun reset(context: Context) {
|
||||
lastGood = null
|
||||
prefs(context)?.edit()?.clear()?.apply()
|
||||
@@ -205,4 +221,11 @@ object DownloadSource {
|
||||
if (trimmed.isEmpty() || trimmed.startsWith("http://")) return ""
|
||||
return if (trimmed.startsWith("https://")) trimmed else "https://$trimmed"
|
||||
}
|
||||
|
||||
internal fun normalizeProxy(value: String): String {
|
||||
val trimmed = value.trim().removePrefix("http://").trimEnd('/')
|
||||
val host = trimmed.substringBefore(':')
|
||||
val port = trimmed.substringAfter(':', "").toIntOrNull() ?: 0
|
||||
return if (host.isNotEmpty() && port in 1..65535) "$host:$port" else ""
|
||||
}
|
||||
}
|
||||
@@ -11,24 +11,87 @@ import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.Proxy;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
public final class Downloader {
|
||||
private static final String TAG = "Downloader";
|
||||
private static final int CONNECT_TIMEOUT_MS = 10_000;
|
||||
private static final int STALL_TIMEOUT_MS = 15_000;
|
||||
private static final int HTTP_RANGE_NOT_SATISFIABLE = 416;
|
||||
private static final java.util.concurrent.ExecutorService CANCEL_EXECUTOR =
|
||||
java.util.concurrent.Executors.newCachedThreadPool(r -> {
|
||||
Thread thread = new Thread(r, "download-cancel");
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
});
|
||||
|
||||
private Downloader() {}
|
||||
|
||||
public static final class Cancellation implements java.util.function.BooleanSupplier {
|
||||
private final AtomicBoolean cancelled = new AtomicBoolean();
|
||||
private final AtomicReference<HttpURLConnection> connection = new AtomicReference<>();
|
||||
private final AtomicReference<InputStream> input = new AtomicReference<>();
|
||||
private final java.util.function.BooleanSupplier external;
|
||||
|
||||
public Cancellation() { this(null); }
|
||||
public Cancellation(java.util.function.BooleanSupplier external) { this.external = external; }
|
||||
|
||||
public void cancel() {
|
||||
cancelled.set(true);
|
||||
HttpURLConnection active = connection.get();
|
||||
if (active != null) disconnectAsync(active);
|
||||
InputStream activeInput = input.get();
|
||||
if (activeInput != null) closeAsync(activeInput);
|
||||
}
|
||||
|
||||
private static void disconnectAsync(HttpURLConnection active) {
|
||||
CANCEL_EXECUTOR.execute(() -> {
|
||||
try { active.disconnect(); } catch (RuntimeException ignored) { }
|
||||
});
|
||||
}
|
||||
|
||||
private static void closeAsync(InputStream active) {
|
||||
CANCEL_EXECUTOR.execute(() -> {
|
||||
try { active.close(); } catch (IOException ignored) { }
|
||||
});
|
||||
}
|
||||
|
||||
@Override public boolean getAsBoolean() {
|
||||
return cancelled.get() || (external != null && external.getAsBoolean());
|
||||
}
|
||||
|
||||
private void attach(HttpURLConnection active) {
|
||||
connection.set(active);
|
||||
if (getAsBoolean()) disconnectAsync(active);
|
||||
}
|
||||
|
||||
private void detach(HttpURLConnection active) { connection.compareAndSet(active, null); }
|
||||
|
||||
private void attach(InputStream active) {
|
||||
input.set(active);
|
||||
if (getAsBoolean()) closeAsync(active);
|
||||
}
|
||||
|
||||
private void detach(InputStream active) { input.compareAndSet(active, null); }
|
||||
}
|
||||
|
||||
public static String downloadString(String url) {
|
||||
return downloadString(url, null);
|
||||
}
|
||||
|
||||
public static String downloadString(String url, java.util.function.BooleanSupplier cancelled) {
|
||||
List<String> sources = DownloadSource.INSTANCE.candidates(url);
|
||||
for (int i = 0; i < sources.size(); i++) {
|
||||
if (isCancelled(cancelled)) return null;
|
||||
if (i > 0) Log.i(TAG, "retrying " + url + " via " + sources.get(i));
|
||||
Fetch fetch = fetch(sources.get(i));
|
||||
Fetch fetch = fetch(sources.get(i), cancelled);
|
||||
if (isCancelled(cancelled)) return null;
|
||||
if (fetch.body != null) {
|
||||
DownloadSource.INSTANCE.succeeded(sources.get(i));
|
||||
return fetch.body;
|
||||
@@ -39,7 +102,6 @@ public final class Downloader {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Fetches without the mirror list, for a URL whose body is a digest the payload is checked against. */
|
||||
public static String downloadDirect(String url) {
|
||||
return fetch(url).body;
|
||||
}
|
||||
@@ -49,35 +111,52 @@ public final class Downloader {
|
||||
return downloadFile(url, destination, resume, null, progress);
|
||||
}
|
||||
|
||||
/** Verify each candidate before accepting it, so a bad mirror can fall back. */
|
||||
public static boolean downloadFile(String url, File destination, boolean resume, String expectedSha256,
|
||||
java.util.function.Consumer<Float> progress) {
|
||||
return downloadFile(url, destination, resume, expectedSha256, null, progress);
|
||||
}
|
||||
|
||||
public static boolean downloadFile(String url, File destination, boolean resume, String expectedSha256,
|
||||
java.util.function.BooleanSupplier cancelled,
|
||||
java.util.function.Consumer<Float> progress) {
|
||||
if (expectedSha256 != null && !expectedSha256.matches("(?i)[0-9a-f]{64}"))
|
||||
throw new IllegalArgumentException("Expected SHA-256 must be 64 hex characters");
|
||||
return downloadCandidates(url, sources(url, expectedSha256), destination, resume, expectedSha256, progress);
|
||||
return downloadCandidates(url, sources(url, expectedSha256), destination, resume, expectedSha256, cancelled, progress);
|
||||
}
|
||||
|
||||
/** A third-party mirror may only serve bytes that can be checked against a digest from a direct source. */
|
||||
static List<String> sources(String url, String expectedSha256) {
|
||||
return expectedSha256 == null ? java.util.Collections.singletonList(url) : DownloadSource.INSTANCE.candidates(url);
|
||||
|
||||
}
|
||||
|
||||
// Package-private for the local multi-source HTTP test.
|
||||
static boolean downloadCandidates(String original, List<String> sources, File destination, boolean resume,
|
||||
String expectedSha256, java.util.function.Consumer<Float> progress) {
|
||||
return downloadCandidates(original, sources, destination, resume, expectedSha256, null, progress);
|
||||
}
|
||||
|
||||
static boolean downloadCandidates(String original, List<String> sources, File destination, boolean resume,
|
||||
String expectedSha256, java.util.function.BooleanSupplier cancelled,
|
||||
java.util.function.Consumer<Float> progress) {
|
||||
Identity identity = loadIdentity(destination, resume, expectedSha256);
|
||||
for (int i = 0; i < sources.size(); i++) {
|
||||
if (Thread.currentThread().isInterrupted()) return false;
|
||||
String source = sources.get(i);
|
||||
if (isCancelled(cancelled)) return false;
|
||||
if (i > 0) Log.i(TAG, "retrying " + original + " via " + source);
|
||||
Outcome outcome = attempt(source, destination, resume, identity, expectedSha256, progress);
|
||||
Outcome outcome = attempt(source, destination, resume, identity, expectedSha256, cancelled, progress);
|
||||
if (outcome == Outcome.CANCELLED) return false;
|
||||
if (Thread.currentThread().isInterrupted()) return false;
|
||||
if (outcome == Outcome.DONE) {
|
||||
if (expectedSha256 != null && !expectedSha256.equalsIgnoreCase(Hashes.sha256(destination))) {
|
||||
Log.w(TAG, "checksum mismatch from " + source + "; trying another source");
|
||||
if (!discardPartial(destination, identity)) return false;
|
||||
continue;
|
||||
if (expectedSha256 != null) {
|
||||
String actualSha256 = Hashes.sha256(destination);
|
||||
if (isCancelled(cancelled)) return false;
|
||||
if (!expectedSha256.equalsIgnoreCase(actualSha256)) {
|
||||
Log.w(TAG, "checksum mismatch from " + source + "; trying another source");
|
||||
if (!discardPartial(destination, identity)) return false;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (isCancelled(cancelled)) return false;
|
||||
resumeFile(destination).delete();
|
||||
DownloadSource.INSTANCE.succeeded(source);
|
||||
if (progress != null) progress.accept(1f);
|
||||
@@ -89,7 +168,11 @@ public final class Downloader {
|
||||
return false;
|
||||
}
|
||||
|
||||
private enum Outcome { DONE, RETRY, FATAL }
|
||||
private enum Outcome { DONE, RETRY, FATAL, CANCELLED }
|
||||
|
||||
private static boolean isCancelled(java.util.function.BooleanSupplier cancelled) {
|
||||
return cancelled != null && cancelled.getAsBoolean();
|
||||
}
|
||||
|
||||
private static final class Identity {
|
||||
private String source;
|
||||
@@ -104,7 +187,6 @@ public final class Downloader {
|
||||
return value != null && !value.isEmpty() && !value.startsWith("W/");
|
||||
}
|
||||
|
||||
/** Only reuse saved bytes when we persisted a strong validator and their source. */
|
||||
private static Identity loadIdentity(File dest, boolean resume, String expectedSha256) {
|
||||
Identity identity = new Identity();
|
||||
File marker = resumeFile(dest);
|
||||
@@ -125,7 +207,6 @@ public final class Downloader {
|
||||
return identity;
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// Legacy partials or interrupted metadata writes have no trustworthy identity.
|
||||
}
|
||||
if (!discardPartial(dest, identity)) Log.w(TAG, "could not discard unidentified partial " + dest);
|
||||
return identity;
|
||||
@@ -151,22 +232,24 @@ public final class Downloader {
|
||||
try (FileOutputStream out = new FileOutputStream(marker)) {
|
||||
p.store(out, "DroidDeck partial download validator");
|
||||
} catch (IOException e) {
|
||||
marker.delete(); // No valid metadata means no future resume.
|
||||
marker.delete();
|
||||
Log.w(TAG, "cannot persist download validator", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static Outcome attempt(String url, File destination, boolean resume, Identity identity,
|
||||
String expectedSha256, java.util.function.Consumer<Float> progress) {
|
||||
String expectedSha256, java.util.function.BooleanSupplier cancelled,
|
||||
java.util.function.Consumer<Float> progress) {
|
||||
if (isCancelled(cancelled)) return Outcome.CANCELLED;
|
||||
HttpURLConnection connection = null;
|
||||
long have = resume && destination.isFile() ? destination.length() : 0;
|
||||
try {
|
||||
if (have > 0 && (!url.equals(identity.source) || !strongETag(identity.etag))) {
|
||||
// A new source or unvalidated bytes must restart from byte zero.
|
||||
if (!discardPartial(destination, identity)) return Outcome.RETRY;
|
||||
have = 0;
|
||||
}
|
||||
connection = open(url, STALL_TIMEOUT_MS);
|
||||
if (cancelled instanceof Cancellation) ((Cancellation) cancelled).attach(connection);
|
||||
if (have > 0) {
|
||||
connection.setRequestProperty("Range", "bytes=" + have + "-");
|
||||
connection.setRequestProperty("If-Range", identity.etag);
|
||||
@@ -175,7 +258,7 @@ public final class Downloader {
|
||||
if (have > 0 && code == HTTP_RANGE_NOT_SATISFIABLE) {
|
||||
connection.disconnect();
|
||||
if (!discardPartial(destination, identity)) return Outcome.RETRY;
|
||||
return attempt(url, destination, false, identity, expectedSha256, progress);
|
||||
return attempt(url, destination, false, identity, expectedSha256, cancelled, progress);
|
||||
}
|
||||
if (code / 100 != 2) {
|
||||
Log.w(TAG, url + " -> HTTP " + code);
|
||||
@@ -186,16 +269,15 @@ public final class Downloader {
|
||||
if (appending && !rangeStartsAt(connection.getHeaderField("Content-Range"), have)) {
|
||||
connection.disconnect();
|
||||
if (!discardPartial(destination, identity)) return Outcome.RETRY;
|
||||
return attempt(url, destination, false, identity, expectedSha256, progress);
|
||||
return attempt(url, destination, false, identity, expectedSha256, cancelled, progress);
|
||||
}
|
||||
String etag = connection.getHeaderField("ETag");
|
||||
if (have > 0 && appending && (!strongETag(etag) || !etag.equals(identity.etag))) {
|
||||
connection.disconnect();
|
||||
if (!discardPartial(destination, identity)) return Outcome.RETRY;
|
||||
return attempt(url, destination, false, identity, expectedSha256, progress);
|
||||
return attempt(url, destination, false, identity, expectedSha256, cancelled, progress);
|
||||
}
|
||||
if (!appending && have > 0) {
|
||||
// If-Range may legitimately return full 200 when representation changed.
|
||||
if (!discardPartial(destination, identity)) return Outcome.RETRY;
|
||||
have = 0;
|
||||
}
|
||||
@@ -209,7 +291,9 @@ public final class Downloader {
|
||||
identity.etag = strongETag(etag) ? etag : null;
|
||||
saveIdentity(destination, identity, expectedSha256);
|
||||
long written = have;
|
||||
try (InputStream in = new BufferedInputStream(connection.getInputStream(), 1 << 16);
|
||||
InputStream input = connection.getInputStream();
|
||||
if (cancelled instanceof Cancellation) ((Cancellation) cancelled).attach(input);
|
||||
try (InputStream in = new BufferedInputStream(input, 1 << 16);
|
||||
OutputStream out = new FileOutputStream(destination, appending)) {
|
||||
byte[] buffer = new byte[1 << 16];
|
||||
long lastReport = 0;
|
||||
@@ -217,30 +301,36 @@ public final class Downloader {
|
||||
if (Thread.currentThread().isInterrupted()) return Outcome.RETRY;
|
||||
out.write(buffer, 0, read);
|
||||
written += read;
|
||||
if (isCancelled(cancelled)) return Outcome.CANCELLED;
|
||||
if (progress != null && written - lastReport > (1 << 20)) {
|
||||
lastReport = written;
|
||||
progress.accept(total > 0 ? written / (float) total : -1f);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (cancelled instanceof Cancellation) ((Cancellation) cancelled).detach(input);
|
||||
}
|
||||
if (isCancelled(cancelled)) return Outcome.CANCELLED;
|
||||
if (total > 0 && written < total) return Outcome.RETRY;
|
||||
return Outcome.DONE;
|
||||
} catch (Exception e) {
|
||||
if (isCancelled(cancelled)) return Outcome.CANCELLED;
|
||||
Log.w(TAG, "download " + url, e);
|
||||
return Outcome.RETRY;
|
||||
} finally {
|
||||
if (connection != null) connection.disconnect();
|
||||
if (connection != null) {
|
||||
if (cancelled instanceof Cancellation) ((Cancellation) cancelled).detach(connection);
|
||||
connection.disconnect();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** True when a `Content-Range: bytes START-END/TOTAL` header starts exactly at {@code start}. */
|
||||
static boolean rangeStartsAt(String contentRange, long start) {
|
||||
if (contentRange == null) return false;
|
||||
java.util.regex.Matcher m = java.util.regex.Pattern.compile("^\\s*bytes\\s+(\\d+)-\\d+/(?:\\d+|\\*)\\s*$").matcher(contentRange);
|
||||
return m.matches() && Long.parseLong(m.group(1)) == start;
|
||||
}
|
||||
|
||||
/** The complete length in a `Content-Range` header, or -1 when the header leaves it unknown. */
|
||||
static long rangeTotal(String contentRange) {
|
||||
if (contentRange == null) return -1;
|
||||
java.util.regex.Matcher m = java.util.regex.Pattern.compile("^\\s*bytes\\s+\\d+-\\d+/(\\d+)\\s*$").matcher(contentRange);
|
||||
@@ -258,9 +348,15 @@ public final class Downloader {
|
||||
}
|
||||
|
||||
private static Fetch fetch(String url) {
|
||||
return fetch(url, null);
|
||||
}
|
||||
|
||||
private static Fetch fetch(String url, java.util.function.BooleanSupplier cancelled) {
|
||||
HttpURLConnection connection = null;
|
||||
Cancellation token = cancelled instanceof Cancellation ? (Cancellation) cancelled : null;
|
||||
try {
|
||||
connection = open(url, STALL_TIMEOUT_MS);
|
||||
if (token != null) token.attach(connection);
|
||||
int code = connection.getResponseCode();
|
||||
if (code / 100 != 2) {
|
||||
Log.w(TAG, url + " -> HTTP " + code);
|
||||
@@ -272,15 +368,21 @@ public final class Downloader {
|
||||
return new Fetch(new String(out.toByteArray(), StandardCharsets.UTF_8), false);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
if (isCancelled(cancelled)) return new Fetch(null, false);
|
||||
Log.w(TAG, "GET " + url, e);
|
||||
return new Fetch(null, false);
|
||||
} finally {
|
||||
if (connection != null) connection.disconnect();
|
||||
if (connection != null) {
|
||||
if (token != null) token.detach(connection);
|
||||
connection.disconnect();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static HttpURLConnection open(String url, int readTimeoutMs) throws java.io.IOException {
|
||||
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
|
||||
Proxy proxy = DownloadSource.INSTANCE.httpProxy();
|
||||
HttpURLConnection connection = (HttpURLConnection) (proxy != null
|
||||
? new URL(url).openConnection(proxy) : new URL(url).openConnection());
|
||||
connection.setConnectTimeout(CONNECT_TIMEOUT_MS);
|
||||
connection.setReadTimeout(readTimeoutMs);
|
||||
connection.setInstanceFollowRedirects(true);
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import android.app.Notification
|
||||
import android.app.Service
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
|
||||
object ForegroundServices {
|
||||
fun start(service: Service, id: Int, notification: Notification, types: Int = 0): Boolean = try {
|
||||
if (Build.VERSION.SDK_INT >= 29 && types != 0) service.startForeground(id, notification, types)
|
||||
else service.startForeground(id, notification)
|
||||
true
|
||||
} catch (error: RuntimeException) {
|
||||
if (Build.VERSION.SDK_INT < 31 || error !is android.app.ForegroundServiceStartNotAllowedException) throw error
|
||||
Log.w("ForegroundServices", "Foreground work cannot start in the current lifecycle", error)
|
||||
false
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,8 @@ object GameEnvironmentOptions {
|
||||
Option("MESA_SHADER_CACHE_MAX_SIZE", "1G", R.string.game_env_cache_size, Type.CHOICE, listOf("512M", "1G", "2G", "4G")),
|
||||
Option("PROTON_LOG", "1", R.string.game_env_proton_log, Type.TOGGLE, listOf("0", "1")),
|
||||
Option("PROTON_USE_WINED3D", "1", R.string.game_env_wined3d, Type.TOGGLE, listOf("0", "1")),
|
||||
Option("PROTON_DXVK_D3D8", "1", R.string.game_env_dxvk_d3d8, Type.TOGGLE, listOf("0", "1")),
|
||||
Option("WINE_D3D_CONFIG", "renderer=vulkan", R.string.game_env_wined3d_renderer, Type.CHOICE, listOf("renderer=vulkan", "renderer=gl")),
|
||||
Option("PROTON_USE_XALIA", "0", R.string.game_env_xalia, Type.TOGGLE, listOf("0", "1")),
|
||||
Option("PROTON_NO_NTSYNC", "1", R.string.game_env_no_ntsync, Type.TOGGLE, listOf("0", "1")),
|
||||
Option("PROTON_NO_ESYNC", "1", R.string.game_env_no_esync, Type.TOGGLE, listOf("0", "1")),
|
||||
@@ -32,6 +34,9 @@ object GameEnvironmentOptions {
|
||||
Option("MESA_EXTENSION_MAX_YEAR", "", 0, Type.TEXT),
|
||||
Option("MESA_GL_VERSION_OVERRIDE", "", 0, Type.TEXT),
|
||||
Option("PULSE_LATENCY_MSEC", "", 0, Type.NUMBER),
|
||||
Option("AUDIO_DIRECT_MS", "", 0, Type.NUMBER),
|
||||
Option("AUDIO_DIRECT_PERIOD_MS", "", 0, Type.NUMBER),
|
||||
Option("DROIDDECK_GAME_CORES", "", R.string.game_env_cores, Type.TEXT),
|
||||
Option("DROIDDECK_ANTICHEAT_OFFLINE", "1", R.string.game_env_anticheat_offline, Type.TOGGLE, listOf("0", "1")),
|
||||
Option("WINE_LARGE_ADDRESS_AWARE", "0", 0, Type.TOGGLE, listOf("0", "1")),
|
||||
Option("WINEDLLOVERRIDES", "", 0, Type.TEXT),
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.provider.Settings
|
||||
|
||||
object GlobalSettings {
|
||||
fun read(context: Context, name: String): String? {
|
||||
val uri = Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
|
||||
context.contentResolver.query(uri, arrayOf(Settings.NameValueTable.VALUE), null, null, null)?.use { cursor ->
|
||||
return if (cursor.moveToFirst()) cursor.getString(0) else null
|
||||
}
|
||||
return Settings.Global.getString(context.contentResolver, name)
|
||||
}
|
||||
|
||||
fun isOn(context: Context, name: String): Boolean =
|
||||
runCatching { read(context, name)?.trim() == "1" }.getOrDefault(false)
|
||||
|
||||
fun developerOptionsOn(context: Context): Boolean = isOn(context, Settings.Global.DEVELOPMENT_SETTINGS_ENABLED)
|
||||
|
||||
fun wirelessDebuggingOn(context: Context): Boolean = isOn(context, "adb_wifi_enabled")
|
||||
}
|
||||
@@ -10,7 +10,11 @@ object HostProcess {
|
||||
private const val TAG = "HostProcess"
|
||||
|
||||
@JvmStatic
|
||||
fun start(command: String, env: Array<String>?, dir: File?, onExit: Consumer<Int>?, onLine: Consumer<String>?): Int {
|
||||
fun start(command: String, env: Array<String>?, dir: File?, onExit: Consumer<Int>?, onLine: Consumer<String>?): Int =
|
||||
start(command, env, dir, onExit, onLine, null)
|
||||
|
||||
@JvmStatic
|
||||
fun start(command: String, env: Array<String>?, dir: File?, onExit: Consumer<Int>?, onLine: Consumer<String>?, outputFile: File?): Int {
|
||||
val argv = split(command)
|
||||
if (argv.isEmpty()) return -1
|
||||
return try {
|
||||
@@ -21,7 +25,10 @@ object HostProcess {
|
||||
if (eq > 0) builder.environment()[line.substring(0, eq)] = line.substring(eq + 1)
|
||||
}
|
||||
builder.redirectErrorStream(true)
|
||||
if (onLine == null) builder.redirectOutput(File("/dev/null"))
|
||||
if (onLine == null) {
|
||||
if (outputFile == null) builder.redirectOutput(File("/dev/null"))
|
||||
else builder.redirectOutput(ProcessBuilder.Redirect.appendTo(outputFile))
|
||||
}
|
||||
val process = builder.start()
|
||||
val pid = pidOf(process)
|
||||
Log.i(TAG, "started pid $pid: ${argv.first()} (${argv.size - 1} arguments)")
|
||||
@@ -48,14 +55,17 @@ object HostProcess {
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun pidOf(process: Process): Int = try {
|
||||
val field = process.javaClass.getDeclaredField("pid")
|
||||
field.isAccessible = true
|
||||
val pid = field.getInt(process)
|
||||
field.isAccessible = false
|
||||
pid
|
||||
} catch (e: Exception) {
|
||||
-1
|
||||
fun pidOf(process: Process): Int {
|
||||
Regex("""\bpid=(\d+)\b""").find(process.toString())?.groupValues?.get(1)?.toIntOrNull()?.let { return it }
|
||||
return try {
|
||||
val field = process.javaClass.getDeclaredField("pid")
|
||||
field.isAccessible = true
|
||||
val pid = field.getInt(process)
|
||||
field.isAccessible = false
|
||||
pid
|
||||
} catch (e: Exception) {
|
||||
-1
|
||||
}
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
|
||||
@@ -1,21 +1,58 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
object LogRedactor {
|
||||
private val EMAIL = Regex("[A-Za-z0-9._%+\\-]+@[A-Za-z0-9.\\-]+\\.[A-Za-z]{2,}")
|
||||
private val HIDL_SHARED_LIBRARY = Regex(
|
||||
"(?:android\\.(?:hardware|frameworks|hidl|system)|vendor\\.[A-Za-z0-9_]+\\.hardware)" +
|
||||
"(?:\\.[A-Za-z0-9_]+)+@[0-9]+\\.[0-9]+(?:-[A-Za-z0-9_]+)*\\.so"
|
||||
)
|
||||
private val hidlMatcher = object : ThreadLocal<java.util.regex.Matcher>() {
|
||||
override fun initialValue(): java.util.regex.Matcher = HIDL_SHARED_LIBRARY.toPattern().matcher("")
|
||||
internal const val MAX_LINE_LENGTH = 64 * 1024
|
||||
internal const val OVERSIZED_LINE = "<oversized log line withheld>"
|
||||
|
||||
private data class MatcherKey(val pattern: String, val options: Set<RegexOption>)
|
||||
|
||||
private class MatcherCache : LinkedHashMap<MatcherKey, java.util.regex.Matcher>(32, 0.75f, true) {
|
||||
override fun removeEldestEntry(eldest: MutableMap.MutableEntry<MatcherKey, java.util.regex.Matcher>?): Boolean =
|
||||
size > 32
|
||||
}
|
||||
|
||||
private fun isHidlLoaderDiagnostic(input: String, match: MatchResult): Boolean {
|
||||
val matcher = hidlMatcher.get()!!
|
||||
val isLibrary = try { matcher.reset(match.value).matches() } finally { matcher.reset("") }
|
||||
if (!isLibrary) return false
|
||||
val start = match.range.first
|
||||
val end = match.range.last + 1
|
||||
private val matchers = object : ThreadLocal<MatcherCache>() {
|
||||
override fun initialValue(): MatcherCache = MatcherCache()
|
||||
}
|
||||
|
||||
private fun <T> withMatcher(
|
||||
regex: Regex,
|
||||
input: CharSequence,
|
||||
action: (java.util.regex.Matcher) -> T,
|
||||
): T {
|
||||
val key = MatcherKey(regex.pattern, regex.options)
|
||||
val matcher = matchers.get()!!.getOrPut(key) { regex.toPattern().matcher("") }
|
||||
return try {
|
||||
action(matcher.reset(input))
|
||||
} finally {
|
||||
matcher.reset("")
|
||||
}
|
||||
}
|
||||
|
||||
private fun replaceMatches(input: String, regex: Regex, replacement: String): String =
|
||||
replaceMatches(input, regex) { replacement }
|
||||
|
||||
private fun replaceMatches(
|
||||
input: String,
|
||||
regex: Regex,
|
||||
replacement: (java.util.regex.Matcher) -> String,
|
||||
): String = withMatcher(regex, input) { matcher ->
|
||||
if (!matcher.find()) return@withMatcher input
|
||||
val out = StringBuffer(input.length)
|
||||
do {
|
||||
matcher.appendReplacement(out, java.util.regex.Matcher.quoteReplacement(replacement(matcher)))
|
||||
} while (matcher.find())
|
||||
matcher.appendTail(out)
|
||||
out.toString()
|
||||
}
|
||||
|
||||
private fun matchesEntire(input: String, regex: Regex): Boolean =
|
||||
withMatcher(regex, input) { it.matches() }
|
||||
|
||||
private fun isHidlLoaderDiagnostic(input: String, match: java.util.regex.Matcher): Boolean {
|
||||
if (!matchesEntire(match.group(), HIDL_SHARED_LIBRARY)) return false
|
||||
val start = match.start()
|
||||
val end = match.end()
|
||||
val prefix = "library \""
|
||||
val suffix = "\" not found"
|
||||
val earliestQuote = (start - 4096).coerceAtLeast(0)
|
||||
@@ -39,6 +76,12 @@ object LogRedactor {
|
||||
(suffixEnd == input.length || !(input[suffixEnd].isLetterOrDigit() || input[suffixEnd] == '_'))
|
||||
}
|
||||
|
||||
private val EMAIL = Regex("[A-Za-z0-9._%+\\-]+@[A-Za-z0-9.\\-]+\\.[A-Za-z]{2,}")
|
||||
private val HIDL_SHARED_LIBRARY = Regex(
|
||||
"(?:android\\.(?:hardware|frameworks|hidl|system)|vendor\\.[A-Za-z0-9_]+\\.hardware)" +
|
||||
"(?:\\.[A-Za-z0-9_]+)+@[0-9]+\\.[0-9]+(?:-[A-Za-z0-9_]+)*\\.so"
|
||||
)
|
||||
|
||||
private val JWT_LABELLED = Regex("(?i)(\\bJWT[\\s=:]+)(\\d{8,})")
|
||||
private val JWT_BASE64 = Regex("ey[A-Za-z0-9_\\-]{6,}\\.[A-Za-z0-9_\\-]{6,}\\.[A-Za-z0-9_\\-]{6,}")
|
||||
private val GUID = Regex("\\b[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}\\b")
|
||||
@@ -76,7 +119,7 @@ object LogRedactor {
|
||||
|
||||
private const val ACCOUNT_VALUE = "(\"[^\"<\\r\\n]+\"|'[^'<\\r\\n]+'|[^\\s\"'<>&;,}]+)"
|
||||
private val ACCOUNT_KV = Regex(
|
||||
"(?i)(?<![A-Za-z0-9_])(account[_-]?name|user[_-]?name|epicusername)" +
|
||||
"(?i)(?<![A-Za-z0-9_])(account[_-]?name|account[_-]?id|user[_-]?name|epicusername)" +
|
||||
"([\"']?\\s*[=:]\\s*|[\"']\\s+)" + ACCOUNT_VALUE
|
||||
)
|
||||
private val LOGIN_KV = Regex(
|
||||
@@ -101,7 +144,6 @@ object LogRedactor {
|
||||
val needs = name.lowercase().takeIf { name.all { it.code < 0x80 } }
|
||||
Learned(Regex("(?i)(?<![A-Za-z0-9_])" + Regex.escape(name) + "(?![A-Za-z0-9_])"), needs)
|
||||
}
|
||||
// A file that could not be read keeps the names learned from it before.
|
||||
accounts = if (unread) (accounts + learned).distinctBy { it.regex.pattern } else learned
|
||||
}
|
||||
|
||||
@@ -111,6 +153,7 @@ object LogRedactor {
|
||||
java.io.File(root, "root/.local/share/Steam/config/loginusers.vdf"),
|
||||
java.io.File(root, "root/.droiddeck-x64/.local/share/Steam/config/loginusers.vdf"),
|
||||
)
|
||||
matchers.remove()
|
||||
}
|
||||
|
||||
@Volatile
|
||||
@@ -178,12 +221,11 @@ object LogRedactor {
|
||||
}
|
||||
|
||||
fun describeAddresses(text: String): String {
|
||||
var out = IPV6.replace(text) { m -> kind(m.value)?.let { "<$it>" } ?: m.value }
|
||||
out = IPV4.replace(out) { m -> kind(m.value)?.let { "<$it>" } ?: m.value }
|
||||
var out = replaceMatches(text, IPV6) { m -> kind(m.group())?.let { "<$it>" } ?: m.group() }
|
||||
out = replaceMatches(out, IPV4) { m -> kind(m.group())?.let { "<$it>" } ?: m.group() }
|
||||
return out
|
||||
}
|
||||
|
||||
/** The at-rest rewrite reads a file into memory twice; larger logs are only scrubbed on the way out. */
|
||||
const val IN_MEMORY_SCRUB_MAX = 64L * 1024 * 1024
|
||||
|
||||
fun isBinary(file: java.io.File): Boolean = try {
|
||||
@@ -196,31 +238,34 @@ object LogRedactor {
|
||||
true
|
||||
}
|
||||
|
||||
fun isText(file: java.io.File): Boolean = file.isFile && file.length() < IN_MEMORY_SCRUB_MAX && !isBinary(file)
|
||||
|
||||
const val RULES_VERSION = 3
|
||||
|
||||
private val LAN_IPV4 = Regex(
|
||||
"(?<![\\d.])(?:10\\.\\d{1,3}|192\\.168|172\\.(?:1[6-9]|2\\d|3[01])|169\\.254)\\.\\d{1,3}\\.\\d{1,3}(?!\\.?\\d)"
|
||||
)
|
||||
|
||||
fun scrubTo(src: java.io.File, out: java.io.Writer) {
|
||||
src.forEachLine { line -> out.write(redact(line)); out.write("\n") }
|
||||
}
|
||||
fun scrubTo(
|
||||
src: java.io.File,
|
||||
out: java.io.Writer,
|
||||
shouldStop: () -> Boolean = { false },
|
||||
): Boolean = scrubLines(src, out, ::redact, shouldStop)
|
||||
|
||||
fun redactForShare(line: String): String {
|
||||
if (line.isEmpty()) return line
|
||||
if (line.length > MAX_LINE_LENGTH) return OVERSIZED_LINE
|
||||
return try {
|
||||
val out = SecretScrub.scrub(redact(line), SecretScrub.Urls.KEEP_PATH, "<redacted:token>")
|
||||
LAN_IPV4.replace(out, "<lan-address>")
|
||||
replaceMatches(out, LAN_IPV4, "<lan-address>")
|
||||
} catch (t: Throwable) {
|
||||
"<redaction failed; line withheld>"
|
||||
}
|
||||
}
|
||||
|
||||
private const val SHARE_LINE_MAX = 64 * 1024
|
||||
|
||||
fun scrubForShare(src: java.io.File, out: java.io.Writer) {
|
||||
fun scrubForShare(
|
||||
src: java.io.File,
|
||||
out: java.io.Writer,
|
||||
shouldStop: () -> Boolean = { false },
|
||||
): Boolean {
|
||||
src.inputStream().buffered().use { input ->
|
||||
input.mark(2)
|
||||
val first = input.read()
|
||||
@@ -228,27 +273,30 @@ object LogRedactor {
|
||||
input.reset()
|
||||
if ((first == 0xff && second == 0xfe) || (first == 0xfe && second == 0xff)) {
|
||||
out.write("<unsupported encoding; file withheld>\n")
|
||||
return
|
||||
return true
|
||||
}
|
||||
val decoder = Charsets.UTF_8.newDecoder()
|
||||
.onMalformedInput(java.nio.charset.CodingErrorAction.REPORT)
|
||||
.onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT)
|
||||
java.io.InputStreamReader(input, decoder).use { reader ->
|
||||
val buffer = CharArray(8192)
|
||||
val line = StringBuilder()
|
||||
var withheld = false
|
||||
val line = StringBuilder(4096)
|
||||
var withheld: String? = null
|
||||
var afterCr = false
|
||||
fun emit() {
|
||||
out.write(if (withheld) "<unsupported or oversized line withheld>" else redactForShare(line.toString()))
|
||||
out.write(withheld ?: redactForShare(line.toString()))
|
||||
out.write("\n")
|
||||
line.setLength(0)
|
||||
withheld = false
|
||||
withheld = null
|
||||
}
|
||||
try {
|
||||
while (true) {
|
||||
if (shouldStop()) return false
|
||||
val size = reader.read(buffer)
|
||||
if (size < 0) break
|
||||
if (shouldStop()) return false
|
||||
for (i in 0 until size) {
|
||||
if (shouldStop()) return false
|
||||
val ch = buffer[i]
|
||||
if (afterCr) {
|
||||
afterCr = false
|
||||
@@ -257,23 +305,79 @@ object LogRedactor {
|
||||
if (ch == '\r' || ch == '\n') {
|
||||
emit()
|
||||
afterCr = ch == '\r'
|
||||
} else if (!withheld) {
|
||||
// Splitting a line can separate a credential from its label.
|
||||
if (ch == '\u0000' || line.length == SHARE_LINE_MAX) {
|
||||
withheld = true
|
||||
} else if (withheld == null) {
|
||||
if (ch == '\u0000' || line.length == MAX_LINE_LENGTH) {
|
||||
withheld = if (ch == '\u0000') "<unsupported or oversized line withheld>" else OVERSIZED_LINE
|
||||
line.setLength(0)
|
||||
} else {
|
||||
line.append(ch)
|
||||
}
|
||||
} else line.append(ch)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (withheld || line.isNotEmpty()) emit()
|
||||
if (withheld != null || line.isNotEmpty()) emit()
|
||||
} catch (_: java.nio.charset.CharacterCodingException) {
|
||||
out.write("<unsupported encoding; file withheld>\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
private fun scrubLines(
|
||||
src: java.io.File,
|
||||
out: java.io.Writer,
|
||||
scrub: (String) -> String,
|
||||
shouldStop: () -> Boolean,
|
||||
): Boolean {
|
||||
src.bufferedReader().use { input ->
|
||||
val chunk = CharArray(8192)
|
||||
val line = StringBuilder(4096)
|
||||
var oversized = false
|
||||
var pendingContent = false
|
||||
var pendingCarriageReturn = false
|
||||
|
||||
fun emit() {
|
||||
out.write(if (oversized) OVERSIZED_LINE else scrub(line.toString()))
|
||||
out.write("\n")
|
||||
line.setLength(0)
|
||||
oversized = false
|
||||
pendingContent = false
|
||||
}
|
||||
|
||||
while (true) {
|
||||
if (shouldStop()) return false
|
||||
val count = input.read(chunk)
|
||||
if (count < 0) break
|
||||
if (shouldStop()) return false
|
||||
for (i in 0 until count) {
|
||||
val char = chunk[i]
|
||||
if (pendingCarriageReturn) {
|
||||
emit()
|
||||
pendingCarriageReturn = false
|
||||
if (char == '\n') continue
|
||||
}
|
||||
when (char) {
|
||||
'\r' -> pendingCarriageReturn = true
|
||||
'\n' -> emit()
|
||||
else -> {
|
||||
pendingContent = true
|
||||
if (!oversized) {
|
||||
if (line.length < MAX_LINE_LENGTH) line.append(char)
|
||||
else {
|
||||
line.setLength(0)
|
||||
oversized = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (pendingCarriageReturn || pendingContent) {
|
||||
if (shouldStop()) return false
|
||||
emit()
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private fun quoted(value: String): String {
|
||||
@@ -315,45 +419,51 @@ object LogRedactor {
|
||||
|
||||
fun redact(line: String): String {
|
||||
if (line.isEmpty()) return line
|
||||
if (line.length > MAX_LINE_LENGTH) return OVERSIZED_LINE
|
||||
return try {
|
||||
val out = Line(line)
|
||||
if (out.has("mac")) out.set(MAC_FIELD.replace(out.text) { "${it.groupValues[1]}<redacted:mac>" })
|
||||
if (out.holds(':', 5) || out.holds('-', 5)) out.set(MAC.replace(out.text, "<redacted:mac>"))
|
||||
if (out.has("serial", "android")) out.set(DEVICE_IDENTIFIER.replace(out.text) {
|
||||
val value = it.groupValues[2]
|
||||
if (out.has("mac")) out.set(replaceMatches(out.text, MAC_FIELD) { "${it.group(1)}<redacted:mac>" })
|
||||
if (out.holds(':', 5) || out.holds('-', 5)) out.set(replaceMatches(out.text, MAC, "<redacted:mac>"))
|
||||
if (out.has("serial", "android")) out.set(replaceMatches(out.text, DEVICE_IDENTIFIER) {
|
||||
val value = it.group(2)
|
||||
val quote = value.first().takeIf { char -> char == '\"' || char == '\'' }?.toString().orEmpty()
|
||||
"${it.groupValues[1]}${quote}<redacted:serial>${quote}"
|
||||
"${it.group(1)}${quote}<redacted:serial>${quote}"
|
||||
})
|
||||
if (out.holds('-', 4)) out.set(GUID.replace(out.text, "<redacted:guid>"))
|
||||
if (out.has("jwt")) out.set(JWT_LABELLED.replace(out.text) { "${it.groupValues[1]}<redacted:jwt>" })
|
||||
if ("ey" in out.text) out.set(JWT_BASE64.replace(out.text, "<redacted:jwt>"))
|
||||
if (out.holds('-', 4)) out.set(replaceMatches(out.text, GUID, "<redacted:guid>"))
|
||||
if (out.has("jwt")) out.set(replaceMatches(out.text, JWT_LABELLED) { "${it.group(1)}<redacted:jwt>" })
|
||||
if ("ey" in out.text) out.set(replaceMatches(out.text, JWT_BASE64, "<redacted:jwt>"))
|
||||
if (out.has("token", "auth", "ticket", "sessionid", "steamloginsecure", "api", "machine", "pass", "pwd", "secret")) {
|
||||
out.set(SECRET_KV.replace(out.text) { "${it.groupValues[1]}${it.groupValues[2]}<redacted:token>${it.groupValues[2]}" })
|
||||
out.set(replaceMatches(out.text, SECRET_KV) {
|
||||
val quote = it.group(2).orEmpty()
|
||||
"${it.group(1)}${quote}<redacted:token>${quote}"
|
||||
})
|
||||
|
||||
}
|
||||
if (out.has("guard", "factor", "2fa")) out.set(GUARD_CODE.replace(out.text) { "${it.groupValues[1]}<redacted:code>" })
|
||||
if (out.hasRun(32, ::isHex)) out.set(WEBAPI_KEY.replace(out.text, "<redacted:key>"))
|
||||
if ("76561" in out.text) out.set(STEAMID64.replace(out.text) { "${it.groupValues[1]}********${it.groupValues[3]}" })
|
||||
if ("[U:1:" in out.text) out.set(STEAMID3.replace(out.text) { m ->
|
||||
val id = m.groupValues[1]
|
||||
if (out.has("guard", "factor", "2fa")) out.set(replaceMatches(out.text, GUARD_CODE) { "${it.group(1)}<redacted:code>" })
|
||||
if (out.hasRun(32, ::isHex)) out.set(replaceMatches(out.text, WEBAPI_KEY, "<redacted:key>"))
|
||||
if ("76561" in out.text) out.set(replaceMatches(out.text, STEAMID64) { "${it.group(1)}********${it.group(3)}" })
|
||||
if ("[U:1:" in out.text) out.set(replaceMatches(out.text, STEAMID3) { m ->
|
||||
val id = m.group(1)
|
||||
"[U:1:${if (id.length > 4) "*".repeat(id.length - 4) + id.takeLast(4) else id}]"
|
||||
})
|
||||
if (out.has("external")) out.set(EXTERNAL_ADDR.replace(out.text) { "${it.groupValues[1]}<redacted:ip>" })
|
||||
for (r in own) if (r.needs == null || out.has(r.needs)) out.set(r.regex.replace(out.text, "<redacted:ip>"))
|
||||
if (out.has("onloginstatechange")) out.set(LOGIN_STATE.replace(out.text) { "${it.groupValues[1]}<redacted:account>" })
|
||||
if ("OnLoginUsersChanged " in out.text) out.set(LOGIN_USERS.replace(out.text) { "${it.groupValues[1]}<redacted:account>" })
|
||||
if (out.has("external")) out.set(replaceMatches(out.text, EXTERNAL_ADDR) { "${it.group(1)}<redacted:ip>" })
|
||||
for (r in own) if (r.needs == null || out.has(r.needs)) out.set(replaceMatches(out.text, r.regex, "<redacted:ip>"))
|
||||
if (out.has("onloginstatechange")) out.set(replaceMatches(out.text, LOGIN_STATE) { "${it.group(1)}<redacted:account>" })
|
||||
if ("OnLoginUsersChanged " in out.text) out.set(replaceMatches(out.text, LOGIN_USERS) { "${it.group(1)}<redacted:account>" })
|
||||
if (out.has("account", "user")) {
|
||||
out.set(ACCOUNT_KV.replace(out.text) { "${it.groupValues[1]}${it.groupValues[2]}${quoted(it.groupValues[3])}" })
|
||||
out.set(replaceMatches(out.text, ACCOUNT_KV) { "${it.group(1)}${it.group(2)}${quoted(it.group(3))}" })
|
||||
}
|
||||
if (out.has("login")) out.set(LOGIN_KV.replace(out.text) { "${it.groupValues[1]}${it.groupValues[2]}${quoted(it.groupValues[3])}" })
|
||||
for (r in accounts) if (r.needs == null || out.has(r.needs)) out.set(r.regex.replace(out.text, "<redacted:account>"))
|
||||
if ('@' in out.text) out.set(EMAIL.replace(out.text) { m ->
|
||||
m.value.takeIf { isHidlLoaderDiagnostic(out.text, m) } ?: "<redacted:email>"
|
||||
if (out.has("login")) out.set(replaceMatches(out.text, LOGIN_KV) { "${it.group(1)}${it.group(2)}${quoted(it.group(3))}" })
|
||||
for (r in accounts) if (r.needs == null || out.has(r.needs)) out.set(replaceMatches(out.text, r.regex, "<redacted:account>"))
|
||||
if ('@' in out.text) out.set(replaceMatches(out.text, EMAIL) { m ->
|
||||
m.group().takeIf { isHidlLoaderDiagnostic(out.text, m) } ?: "<redacted:email>"
|
||||
|
||||
})
|
||||
if (out.has("jwt", "token", "ticket", "sessionid", "steamloginsecure", "machineauth")) {
|
||||
out.set(RESIDUAL.replace(out.text) { "${it.groupValues[1]}=<redacted:token>" })
|
||||
out.set(replaceMatches(out.text, RESIDUAL) { "${it.group(1)}=<redacted:token>" })
|
||||
}
|
||||
if (out.hasRun(88) { it in 'a'..'z' || it in 'A'..'Z' || it in '0'..'9' || it == '_' || it == '-' }) {
|
||||
out.set(LONG_TOKEN.replace(out.text, "<redacted:token>"))
|
||||
out.set(replaceMatches(out.text, LONG_TOKEN, "<redacted:token>"))
|
||||
}
|
||||
out.text
|
||||
} catch (t: Throwable) {
|
||||
|
||||
@@ -60,14 +60,14 @@ object PhantomProcessLimit {
|
||||
if (usesDeviceConfig(sdk)) {
|
||||
val off = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(PREF_ANDROID_12_OFF, false)
|
||||
val global = try {
|
||||
Settings.Global.getString(context.contentResolver, SETTING)
|
||||
GlobalSettings.read(context, SETTING)
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
return android12Status(off, global, systemProperty(OVERRIDE_PROPERTY))
|
||||
}
|
||||
val global = try {
|
||||
Settings.Global.getString(context.contentResolver, SETTING)
|
||||
GlobalSettings.read(context, SETTING)
|
||||
} catch (_: Exception) {
|
||||
return PhantomProcessStatus.UNREADABLE
|
||||
}
|
||||
|
||||
@@ -52,8 +52,6 @@ object SessionLogCapture {
|
||||
if (t.parentFile?.absolutePath == dir.absolutePath) stop()
|
||||
}
|
||||
|
||||
/** flush() only reaches the page cache, and a hard reset on f2fs lost the last minutes of every
|
||||
* log. Every 2 s the session folder's files (ours and the native parts') are synced to storage. */
|
||||
private fun startSyncing(dir: File): Thread = Thread({
|
||||
while (true) {
|
||||
try { Thread.sleep(2000) } catch (e: InterruptedException) { break }
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
|
||||
class ShortcutsListingReceiver : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
if (intent.action == Intent.ACTION_MY_PACKAGE_REPLACED) SteamIntegration.syncShortcutsListing(context)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import android.accessibilityservice.AccessibilityServiceInfo
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import android.provider.Settings
|
||||
import android.view.accessibility.AccessibilityManager
|
||||
import com.droiddeck.launcher.HomeApp
|
||||
import com.droiddeck.launcher.input.HomeButtonService
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
|
||||
object SteamIntegration {
|
||||
const val ACTION_SETUP = "com.droiddeck.launcher.STEAM_INTEGRATION"
|
||||
const val EXTRA_FEATURE = "integration_feature"
|
||||
enum class Feature { WIFI, BRIGHTNESS, HOME, SHORTCUTS }
|
||||
|
||||
data class State(
|
||||
val wifi: Boolean = false,
|
||||
val locationPermission: Boolean = false,
|
||||
val locationOn: Boolean = false,
|
||||
val locationBlocked: Boolean = false,
|
||||
val brightness: Boolean = false,
|
||||
val home: Boolean = false,
|
||||
val shortcuts: Boolean = false,
|
||||
val shortcutsRestricted: Boolean = false,
|
||||
val shortcutsTried: Boolean = false,
|
||||
val suggested: Boolean = true,
|
||||
)
|
||||
|
||||
fun read(context: Context) = State(
|
||||
wifi = SessionPrefs.wifiDiscoveryEnabled(context),
|
||||
locationPermission = WifiDiscovery.permissionGranted(context),
|
||||
locationOn = WifiDiscovery.locationEnabled(context),
|
||||
brightness = Settings.System.canWrite(context),
|
||||
home = HomeApp.isDefault(context),
|
||||
shortcuts = context.getSystemService(AccessibilityManager::class.java)
|
||||
.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_ALL_MASK).any {
|
||||
val service = it.resolveInfo.serviceInfo
|
||||
ComponentName(service.packageName, service.name) == ComponentName(context, HomeButtonService::class.java)
|
||||
},
|
||||
shortcutsRestricted = restrictedSettings(context),
|
||||
suggested = !SessionPrefs.sessionPrefs(context).getBoolean("steam_integration_seen", false),
|
||||
)
|
||||
|
||||
private fun restrictedSettings(context: Context): Boolean {
|
||||
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.TIRAMISU) return false
|
||||
val mode = runCatching {
|
||||
context.getSystemService(android.app.AppOpsManager::class.java)
|
||||
.unsafeCheckOpNoThrow("android:access_restricted_settings", android.os.Process.myUid(), context.packageName)
|
||||
}.getOrDefault(android.app.AppOpsManager.MODE_ALLOWED)
|
||||
return mode == android.app.AppOpsManager.MODE_ERRORED || mode == android.app.AppOpsManager.MODE_IGNORED
|
||||
}
|
||||
|
||||
private fun shortcutsComponent(context: Context) = ComponentName(context, HomeButtonService::class.java)
|
||||
|
||||
fun shortcutsChosen(context: Context): Boolean = shortcutsSelection(context) == true
|
||||
|
||||
private fun shortcutsSelection(context: Context): Boolean? {
|
||||
val target = shortcutsComponent(context)
|
||||
val enabled = runCatching {
|
||||
Settings.Secure.getString(context.contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES)
|
||||
}.getOrElse { return null }.orEmpty()
|
||||
return enabled.split(':').any { ComponentName.unflattenFromString(it.trim()) == target }
|
||||
}
|
||||
|
||||
fun setShortcutsListed(context: Context, listed: Boolean) {
|
||||
val packages = context.packageManager
|
||||
val component = shortcutsComponent(context)
|
||||
val state = if (listed) PackageManager.COMPONENT_ENABLED_STATE_ENABLED else PackageManager.COMPONENT_ENABLED_STATE_DISABLED
|
||||
runCatching {
|
||||
if (packages.getComponentEnabledSetting(component) != state) {
|
||||
packages.setComponentEnabledSetting(component, state, PackageManager.DONT_KILL_APP)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun syncShortcutsListing(context: Context) {
|
||||
shortcutsSelection(context)?.let { setShortcutsListed(context, it) }
|
||||
}
|
||||
|
||||
fun dismissSuggestion(context: Context) {
|
||||
SessionPrefs.sessionPrefs(context).edit().putBoolean("steam_integration_seen", true).apply()
|
||||
}
|
||||
|
||||
fun brightnessSettings(context: Context) = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS,
|
||||
Uri.parse("package:${context.packageName}"))
|
||||
|
||||
fun shortcutSettings(context: Context): Intent {
|
||||
val service = ComponentName(context, HomeButtonService::class.java).flattenToString()
|
||||
return Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
|
||||
.putExtra(":settings:fragment_args_key", service)
|
||||
.putExtra(":settings:show_fragment_args", android.os.Bundle().apply { putString(":settings:fragment_args_key", service) })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import android.os.Build
|
||||
import android.view.View
|
||||
import androidx.core.view.ViewCompat
|
||||
import androidx.core.view.WindowInsetsCompat
|
||||
|
||||
object SystemInsets {
|
||||
fun fit(view: View) {
|
||||
if (Build.VERSION.SDK_INT < 35) return
|
||||
val left = view.paddingLeft
|
||||
val top = view.paddingTop
|
||||
val right = view.paddingRight
|
||||
val bottom = view.paddingBottom
|
||||
ViewCompat.setOnApplyWindowInsetsListener(view) { target, insets ->
|
||||
val safe = insets.getInsets(WindowInsetsCompat.Type.systemBars() or
|
||||
WindowInsetsCompat.Type.displayCutout() or WindowInsetsCompat.Type.ime())
|
||||
target.setPadding(left + safe.left, top + safe.top, right + safe.right, bottom + safe.bottom)
|
||||
insets
|
||||
}
|
||||
ViewCompat.requestApplyInsets(view)
|
||||
}
|
||||
}
|
||||
@@ -182,25 +182,47 @@ object WirelessAdbFix {
|
||||
}
|
||||
|
||||
fun setUsingSavedPairing(context: Context, enabled: Boolean) {
|
||||
withSavedPairing(context) { appContext, host, port -> setChildProcessLimit(appContext, host, port, enabled) }
|
||||
}
|
||||
|
||||
fun hasSavedPairing(context: Context): Boolean = savedConnection(context.applicationContext) != null
|
||||
|
||||
fun clearCachedApps(context: Context) {
|
||||
shell(context, "am kill-all")
|
||||
}
|
||||
|
||||
fun shell(context: Context, command: String): String {
|
||||
var output = ""
|
||||
withSavedPairing(context) { appContext, host, port ->
|
||||
loadOrCreateIdentity(appContext)
|
||||
Kadb.create(host, port).use { adb ->
|
||||
val result = adb.shell(command)
|
||||
check(result.exitCode == 0) { result.allOutput.ifBlank { appContext.getString(R.string.adbfix_command_failed, result.exitCode) } }
|
||||
output = result.output
|
||||
}
|
||||
saveConnection(appContext, host, port)
|
||||
}
|
||||
return output
|
||||
}
|
||||
|
||||
private fun withSavedPairing(context: Context, action: (Context, String, Int) -> Unit) {
|
||||
val appContext = context.applicationContext
|
||||
val saved = savedConnection(appContext)
|
||||
?: error(appContext.getString(R.string.adbfix_no_pairing))
|
||||
val cachedPort = saved.port
|
||||
if (cachedPort != null) {
|
||||
val cachedResult = runCatching {
|
||||
setChildProcessLimit(appContext, saved.host, cachedPort, enabled)
|
||||
}
|
||||
val cachedResult = runCatching { action(appContext, saved.host, cachedPort) }
|
||||
if (cachedResult.isSuccess) return
|
||||
val discoveredPort = findConnectPort(appContext, saved.host)
|
||||
if (discoveredPort != null && discoveredPort != cachedPort) {
|
||||
setChildProcessLimit(appContext, saved.host, discoveredPort, enabled)
|
||||
action(appContext, saved.host, discoveredPort)
|
||||
} else {
|
||||
cachedResult.getOrThrow()
|
||||
}
|
||||
} else {
|
||||
val discoveredPort = findConnectPort(appContext, saved.host)
|
||||
?: error(appContext.getString(R.string.adbfix_enter_address))
|
||||
setChildProcessLimit(appContext, saved.host, discoveredPort, enabled)
|
||||
action(appContext, saved.host, discoveredPort)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -60,7 +60,10 @@ class WirelessAdbPairingService : Service() {
|
||||
pairingPort = null
|
||||
working = false
|
||||
publish(Stage.Waiting)
|
||||
startForeground(NOTIFICATION_ID, notification(Stage.Waiting))
|
||||
if (!ForegroundServices.start(this, NOTIFICATION_ID, notification(Stage.Waiting))) {
|
||||
finish(Stage.Failed(getString(R.string.adbpair_title_failed)))
|
||||
return
|
||||
}
|
||||
startDiscovery()
|
||||
main.removeCallbacks(timeout)
|
||||
main.postDelayed(timeout, TIMEOUT_MS)
|
||||
@@ -184,12 +187,15 @@ class WirelessAdbPairingService : Service() {
|
||||
setSound(null, null)
|
||||
enableVibration(false)
|
||||
})
|
||||
manager?.createNotificationChannel(NotificationChannel(PROGRESS_CHANNEL_ID, getString(R.string.adbpair_progress_channel_name),
|
||||
NotificationManager.IMPORTANCE_LOW).apply { setShowBadge(false) })
|
||||
val open = PendingIntent.getActivity(this, 0,
|
||||
Intent(this, FrontEndActivity::class.java).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT),
|
||||
PendingIntent.FLAG_IMMUTABLE)
|
||||
val cancel = PendingIntent.getService(this, 1,
|
||||
Intent(this, WirelessAdbPairingService::class.java).setAction(ACTION_CANCEL), PendingIntent.FLAG_IMMUTABLE)
|
||||
val builder = Notification.Builder(this, CHANNEL_ID)
|
||||
val quiet = stage == Stage.Waiting || stage == Stage.Idle || stage is Stage.Working
|
||||
val builder = Notification.Builder(this, if (quiet) PROGRESS_CHANNEL_ID else CHANNEL_ID)
|
||||
.setSmallIcon(R.drawable.ic_stat_session)
|
||||
.setContentIntent(open)
|
||||
.setShowWhen(false)
|
||||
@@ -239,6 +245,7 @@ class WirelessAdbPairingService : Service() {
|
||||
|
||||
companion object {
|
||||
private const val CHANNEL_ID = "wireless-adb-pairing"
|
||||
private const val PROGRESS_CHANNEL_ID = "wireless-adb-pairing-progress"
|
||||
private const val NOTIFICATION_ID = 3
|
||||
private const val PAIRING_TYPE = "_adb-tls-pairing._tcp"
|
||||
private const val ACTION_CODE = "com.droiddeck.launcher.action.WIRELESS_ADB_CODE"
|
||||
@@ -252,6 +259,10 @@ class WirelessAdbPairingService : Service() {
|
||||
private fun publish(stage: Stage) { current.value = stage }
|
||||
|
||||
fun start(context: Context) {
|
||||
if (!AppPermissions.localNetwork(context)) {
|
||||
publish(Stage.Failed(context.getString(R.string.setup_local_network)))
|
||||
return
|
||||
}
|
||||
context.getSystemService(NotificationManager::class.java)?.cancel(NOTIFICATION_ID)
|
||||
publish(Stage.Waiting)
|
||||
val intent = Intent(context, WirelessAdbPairingService::class.java)
|
||||
|
||||
+16
-10
@@ -1,4 +1,4 @@
|
||||
package com.droiddeck.launcher.core
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.AlertDialog
|
||||
@@ -25,22 +25,28 @@ object AllFilesAccess {
|
||||
}
|
||||
|
||||
fun ask(activity: Activity): Boolean {
|
||||
if (granted() || activity.isFinishing) return false
|
||||
if (granted() || activity.isFinishing || activity.isDestroyed) return false
|
||||
AlertDialog.Builder(activity)
|
||||
.setTitle(R.string.all_files_title)
|
||||
.setMessage(R.string.all_files_message)
|
||||
.setPositiveButton(R.string.all_files_allow) { _, _ -> openSettings(activity) }
|
||||
.setNegativeButton(R.string.all_files_later, null)
|
||||
.setTitle(R.string.setup_all_files)
|
||||
.setMessage(R.string.fm_drive_access_text)
|
||||
.setPositiveButton(R.string.upd_open_settings) { _, _ -> openSettings(activity) }
|
||||
.setNegativeButton(R.string.common_cancel, null)
|
||||
.show()
|
||||
return true
|
||||
}
|
||||
|
||||
fun openSettings(activity: Activity) {
|
||||
val forApp = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION, Uri.parse("package:" + activity.packageName))
|
||||
fun missing(sdk: Int = Build.VERSION.SDK_INT, granted: () -> Boolean = { AllFilesAccess.granted() }): Boolean =
|
||||
sdk >= Build.VERSION_CODES.R && !granted()
|
||||
|
||||
fun openSettings(activity: Activity) = open(activity)
|
||||
|
||||
fun open(context: Context) {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) return
|
||||
val forApp = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION, Uri.parse("package:" + context.packageName)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
try {
|
||||
activity.startActivity(forApp)
|
||||
context.startActivity(forApp)
|
||||
} catch (e: ActivityNotFoundException) {
|
||||
runCatching { activity.startActivity(Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION)) }
|
||||
runCatching { context.startActivity(Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import com.droiddeck.launcher.ui.focusGlide
|
||||
import android.content.res.Configuration
|
||||
import androidx.compose.animation.core.animateDpAsState
|
||||
import androidx.compose.foundation.background
|
||||
@@ -181,14 +183,14 @@ fun CollapsibleRail(
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
if (!state.portraitLocked) {
|
||||
IconButton(onClick = state.onToggle, modifier = Modifier.size(28.dp)) {
|
||||
IconButton(onClick = state.onToggle, modifier = Modifier.size(28.dp).focusGlide(CircleShape)) {
|
||||
Text("‹‹", color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 15.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (collapsed && !state.portraitLocked) {
|
||||
IconButton(onClick = state.onToggle, modifier = Modifier.fillMaxWidth().height(24.dp)) {
|
||||
IconButton(onClick = state.onToggle, modifier = Modifier.fillMaxWidth().height(24.dp).focusGlide(CircleShape)) {
|
||||
Text("››", color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 15.sp)
|
||||
}
|
||||
}
|
||||
@@ -197,14 +199,14 @@ fun CollapsibleRail(
|
||||
if (collapsed) {
|
||||
Row(horizontalArrangement = Arrangement.Center, modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp)) {
|
||||
links.forEach { link ->
|
||||
IconButton(onClick = link.onClick, modifier = Modifier.size(32.dp)) {
|
||||
IconButton(onClick = link.onClick, modifier = Modifier.size(32.dp).focusGlide(CircleShape)) {
|
||||
Icon(link.icon, link.label, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(18.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
links.forEach { link ->
|
||||
TextButton(onClick = link.onClick, modifier = Modifier.padding(start = 4.dp)) {
|
||||
TextButton(onClick = link.onClick, modifier = Modifier.padding(start = 4.dp).focusGlide(CircleShape)) {
|
||||
Icon(link.icon, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(15.dp))
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(link.label, fontSize = 12.sp)
|
||||
@@ -250,11 +252,11 @@ fun CollapsibleRail(
|
||||
if (active) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline.copy(alpha = 0.5f),
|
||||
shape,
|
||||
)
|
||||
.clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = item.onClick)
|
||||
.focusGlide(shape).clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = item.onClick)
|
||||
.padding(horizontal = if (collapsed) 2.dp else 11.dp, vertical = if (collapsed) 6.dp else 9.dp)
|
||||
} else {
|
||||
base
|
||||
.clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = item.onClick)
|
||||
.focusGlide(shape).clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = item.onClick)
|
||||
.background(if (active) MaterialTheme.colorScheme.primary.copy(alpha = 0.14f) else Color.Transparent)
|
||||
.padding(horizontal = if (collapsed) 2.dp else 13.dp, vertical = if (collapsed) 7.dp else 11.dp)
|
||||
}
|
||||
@@ -309,86 +311,3 @@ fun CollapsibleRail(
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun RailTopTabs(
|
||||
items: List<RailItem>,
|
||||
modifier: Modifier = Modifier,
|
||||
links: List<RailLink> = emptyList(),
|
||||
) {
|
||||
Column(modifier = modifier.fillMaxWidth()) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 2.dp, vertical = 2.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
items.forEach { item ->
|
||||
TopTabCell(
|
||||
icon = item.icon,
|
||||
label = item.label,
|
||||
selected = item.selected,
|
||||
onClick = item.onClick,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
if (links.isNotEmpty()) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.padding(horizontal = 2.dp)
|
||||
.width(1.dp)
|
||||
.height(30.dp)
|
||||
.background(MaterialTheme.colorScheme.outline.copy(alpha = 0.4f)),
|
||||
)
|
||||
links.forEach { link ->
|
||||
TopTabCell(link.icon, link.label, selected = false, onClick = link.onClick, isTab = false, modifier = Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
}
|
||||
HorizontalDivider()
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TopTabCell(
|
||||
icon: ImageVector,
|
||||
label: String,
|
||||
selected: Boolean,
|
||||
onClick: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
isTab: Boolean = true,
|
||||
) {
|
||||
val tint = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
modifier = modifier
|
||||
.clip(RoundedCornerShape(9.dp))
|
||||
.background(if (selected) MaterialTheme.colorScheme.primary.copy(alpha = 0.14f) else Color.Transparent)
|
||||
.then(
|
||||
if (isTab) {
|
||||
Modifier.selectable(selected = selected, role = androidx.compose.ui.semantics.Role.Tab, onClick = onClick)
|
||||
} else {
|
||||
Modifier.clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = onClick)
|
||||
},
|
||||
)
|
||||
.padding(vertical = 6.dp, horizontal = 1.dp),
|
||||
) {
|
||||
Icon(icon, contentDescription = label, tint = tint, modifier = Modifier.size(20.dp))
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
label,
|
||||
color = tint,
|
||||
fontSize = 8.5.sp,
|
||||
fontWeight = FontWeight.Bold,
|
||||
letterSpacing = 0.2.sp,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.height(2.dp)
|
||||
.width(if (selected) 16.dp else 0.dp)
|
||||
.clip(RoundedCornerShape(3.dp))
|
||||
.background(if (selected) MaterialTheme.colorScheme.primary else Color.Transparent),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -22,17 +22,18 @@ class FileManagerActivity : ComponentActivity() {
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
requestedOrientation = com.droiddeck.launcher.session.SessionPrefs.orientation(this)
|
||||
requestedOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
com.droiddeck.launcher.core.AllFilesAccess.ask(this)
|
||||
} else if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
|
||||
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)
|
||||
com.droiddeck.launcher.files.AllFilesAccess.ask(this)
|
||||
} else if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
|
||||
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
|
||||
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE), 1)
|
||||
}
|
||||
val initialDir = intent.getStringExtra(EXTRA_START_DIR)?.let(::File)
|
||||
setContent {
|
||||
DroidDeckTheme(appScale = com.droiddeck.launcher.core.AppUiPrefs.scale(this)) {
|
||||
Surface(modifier = Modifier.fillMaxSize().systemBarsPadding(), color = MaterialTheme.colorScheme.background) {
|
||||
FileManagerScreen(initialDir = initialDir)
|
||||
FileManagerScreen(initialDir = initialDir, onExit = { finish() })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import com.droiddeck.launcher.ui.focusGlide
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
@@ -39,7 +41,7 @@ import androidx.compose.material.icons.filled.Storage
|
||||
import androidx.compose.material.icons.filled.Image
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import com.droiddeck.launcher.ui.GlideDropdownMenu as DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
@@ -105,12 +107,14 @@ private fun FileContextMenuItems(
|
||||
text = { Text(stringResource(R.string.fm_select)) },
|
||||
leadingIcon = { Icon(Icons.Filled.Checklist, null, tint = MaterialTheme.colorScheme.primary) },
|
||||
onClick = { onDismissMenu(); onSelect() },
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
MenuItemDivider()
|
||||
DropdownMenuItem(
|
||||
text = { Text(stringResource(R.string.fm_properties)) },
|
||||
leadingIcon = { Icon(Icons.Filled.Info, null, tint = MaterialTheme.colorScheme.primary) },
|
||||
onClick = { onDismissMenu(); onProperties() },
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
MenuItemDivider()
|
||||
if (isDir) {
|
||||
@@ -124,6 +128,7 @@ private fun FileContextMenuItems(
|
||||
)
|
||||
},
|
||||
onClick = { onToggleFavorite() },
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
MenuItemDivider()
|
||||
}
|
||||
@@ -131,24 +136,28 @@ private fun FileContextMenuItems(
|
||||
text = { Text(stringResource(R.string.fm_rename)) },
|
||||
leadingIcon = { Icon(Icons.Filled.Edit, null, tint = MaterialTheme.colorScheme.primary) },
|
||||
onClick = { onDismissMenu(); onRename() },
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
MenuItemDivider()
|
||||
DropdownMenuItem(
|
||||
text = { Text(stringResource(R.string.fm_copy)) },
|
||||
leadingIcon = { Icon(Icons.Filled.FileCopy, null, tint = MaterialTheme.colorScheme.primary) },
|
||||
onClick = { onDismissMenu(); onCopy() },
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
MenuItemDivider()
|
||||
DropdownMenuItem(
|
||||
text = { Text(stringResource(R.string.fm_cut)) },
|
||||
leadingIcon = { Icon(Icons.Filled.ContentCut, null, tint = MaterialTheme.colorScheme.primary) },
|
||||
onClick = { onDismissMenu(); onCut() },
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
MenuItemDivider()
|
||||
DropdownMenuItem(
|
||||
text = { Text(stringResource(R.string.common_delete)) },
|
||||
leadingIcon = { Icon(Icons.Filled.Delete, null, tint = MaterialTheme.colorScheme.primary) },
|
||||
onClick = { onDismissMenu(); onDelete() },
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -193,7 +202,7 @@ internal fun FileItemRow(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 3.dp)
|
||||
.combinedClickable(role = androidx.compose.ui.semantics.Role.Button,
|
||||
.focusGlide(RoundedCornerShape(10.dp)).combinedClickable(role = androidx.compose.ui.semantics.Role.Button,
|
||||
onClick = { if (selectionMode) onToggleSelect() else onTap() },
|
||||
onLongClick = onLongPress,
|
||||
),
|
||||
@@ -212,7 +221,7 @@ internal fun FileItemRow(
|
||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = if (compact) 3.dp else 8.dp),
|
||||
) {
|
||||
if (selectionMode) {
|
||||
androidx.compose.material3.Checkbox(checked = selected, onCheckedChange = { onToggleSelect() })
|
||||
androidx.compose.material3.Checkbox(checked = selected, onCheckedChange = { onToggleSelect() }, modifier = Modifier.focusGlide())
|
||||
Spacer(Modifier.width(4.dp))
|
||||
}
|
||||
when {
|
||||
@@ -270,7 +279,7 @@ internal fun FileItemRow(
|
||||
)
|
||||
}
|
||||
if (showActions) Box {
|
||||
IconButton(onClick = onMenu) {
|
||||
IconButton(onClick = onMenu, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Icon(Icons.Filled.MoreVert, stringResource(R.string.fm_actions), tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(20.dp))
|
||||
}
|
||||
DropdownMenu(
|
||||
@@ -302,7 +311,7 @@ internal fun ParentFolderRow(compact: Boolean = false, onTap: () -> Unit) {
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 3.dp)
|
||||
.clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = onTap),
|
||||
.focusGlide(RoundedCornerShape(10.dp)).clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = onTap),
|
||||
shape = RoundedCornerShape(10.dp),
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer),
|
||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline),
|
||||
@@ -370,6 +379,7 @@ internal fun FavoritesList(
|
||||
TextButton(
|
||||
onClick = onPinCurrent,
|
||||
enabled = !currentAlreadyPinned,
|
||||
modifier = Modifier.focusGlide(CircleShape),
|
||||
) {
|
||||
Icon(Icons.Filled.PushPin, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(16.dp))
|
||||
Spacer(Modifier.width(6.dp))
|
||||
@@ -422,7 +432,7 @@ private fun FavoriteCard(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 3.dp)
|
||||
.clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = onJump),
|
||||
.focusGlide(RoundedCornerShape(10.dp)).clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = onJump),
|
||||
shape = RoundedCornerShape(10.dp),
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer),
|
||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline),
|
||||
@@ -480,7 +490,7 @@ private fun FavoriteCard(
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
IconButton(onClick = onUnpin) {
|
||||
IconButton(onClick = onUnpin, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Icon(
|
||||
Icons.Filled.Star,
|
||||
contentDescription = stringResource(R.string.fm_unpin_favorite),
|
||||
@@ -526,7 +536,7 @@ internal fun FileGridTile(
|
||||
Card(
|
||||
modifier = Modifier
|
||||
.padding(4.dp)
|
||||
.combinedClickable(role = androidx.compose.ui.semantics.Role.Button,
|
||||
.focusGlide(RoundedCornerShape(10.dp)).combinedClickable(role = androidx.compose.ui.semantics.Role.Button,
|
||||
onClick = { if (selectionMode) onToggleSelect() else onTap() },
|
||||
onLongClick = onLongPress,
|
||||
),
|
||||
@@ -570,7 +580,7 @@ internal fun FileGridTile(
|
||||
androidx.compose.material3.Checkbox(
|
||||
checked = selected,
|
||||
onCheckedChange = { onToggleSelect() },
|
||||
modifier = Modifier.align(Alignment.TopStart),
|
||||
modifier = Modifier.align(Alignment.TopStart).focusGlide(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import com.droiddeck.launcher.ui.focusGlide
|
||||
import android.widget.Toast
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import android.content.res.Configuration
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
@@ -19,6 +23,7 @@ import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.lazy.grid.GridCells
|
||||
@@ -28,6 +33,8 @@ import androidx.compose.foundation.lazy.grid.items
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ExitToApp
|
||||
import androidx.compose.material.icons.automirrored.filled.KeyboardReturn
|
||||
import androidx.compose.material.icons.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.ContentPaste
|
||||
import androidx.compose.material.icons.filled.CreateNewFolder
|
||||
@@ -48,7 +55,7 @@ import androidx.compose.material.icons.filled.Description
|
||||
import androidx.compose.material.icons.filled.Image
|
||||
import androidx.compose.material.icons.filled.SportsEsports
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import com.droiddeck.launcher.ui.GlideDropdownMenu as DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
@@ -68,6 +75,7 @@ import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableFloatStateOf
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateListOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
@@ -90,12 +98,20 @@ import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.ensureActive
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
import java.util.Date
|
||||
|
||||
private enum class FileManagerNavigation { EXIT, RETURN_TO_START, BACK, UP }
|
||||
|
||||
private const val HISTORY_LIMIT = 50
|
||||
|
||||
internal fun canNavigateUp(currentDir: File, currentRoot: File): Boolean =
|
||||
currentDir != currentRoot && currentDir.parentFile?.exists() == true
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun FileManagerScreen(
|
||||
@@ -105,6 +121,7 @@ fun FileManagerScreen(
|
||||
initialDir: File? = null,
|
||||
pickerTitle: String? = null,
|
||||
onPick: ((File) -> Unit)? = null,
|
||||
onExit: (() -> Unit)? = null,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
@@ -118,12 +135,14 @@ fun FileManagerScreen(
|
||||
|
||||
val pickPrefs = remember { context.getSharedPreferences("file_manager", android.content.Context.MODE_PRIVATE) }
|
||||
val browsePrefs = pickPrefs
|
||||
val rootDir = remember {
|
||||
val rootDir = remember(initialDir) {
|
||||
initialDir?.takeIf { it.isDirectory } ?: File("/storage/emulated/0")
|
||||
}
|
||||
|
||||
val launchDir = remember(initialDir, pickMode) {
|
||||
initialDir?.takeIf { !pickMode }
|
||||
}
|
||||
var currentDir by remember { mutableStateOf(rootDir) }
|
||||
var currentRoot by remember {
|
||||
val initialRoot = remember(rootDir) {
|
||||
val abs = rootDir.absolutePath
|
||||
val internal = "/storage/emulated/0"
|
||||
val vol = when {
|
||||
@@ -139,8 +158,9 @@ fun FileManagerScreen(
|
||||
?: rootDir
|
||||
}
|
||||
}
|
||||
mutableStateOf(vol)
|
||||
vol
|
||||
}
|
||||
var currentRoot by remember { mutableStateOf(initialRoot) }
|
||||
var entries by remember { mutableStateOf(listOf<File>()) }
|
||||
var selectedEntry by remember { mutableStateOf<File?>(null) }
|
||||
var showMenuFor by remember { mutableStateOf<File?>(null) }
|
||||
@@ -151,8 +171,10 @@ fun FileManagerScreen(
|
||||
var pendingConflict by remember { mutableStateOf<File?>(null) }
|
||||
var conflictChoice by remember { mutableStateOf<ConflictChoice?>(null) }
|
||||
var conflictApplyToAll by remember { mutableStateOf(false) }
|
||||
var operationJob by remember { mutableStateOf<kotlinx.coroutines.Job?>(null) }
|
||||
var cancelledJob by remember { mutableStateOf<kotlinx.coroutines.Job?>(null) }
|
||||
var operationJob by remember { mutableStateOf<Job?>(null) }
|
||||
var cancelledJob by remember { mutableStateOf<Job?>(null) }
|
||||
var pendingNavigation by remember { mutableStateOf<FileManagerNavigation?>(null) }
|
||||
var cancellingNavigation by remember { mutableStateOf(false) }
|
||||
var pendingBulkDelete by remember { mutableStateOf<List<File>>(emptyList()) }
|
||||
var searchQuery by remember { mutableStateOf("") }
|
||||
val visibleEntries = if (searchQuery.isBlank()) entries
|
||||
@@ -178,10 +200,18 @@ fun FileManagerScreen(
|
||||
var showFavorites by remember { mutableStateOf(false) }
|
||||
var favTick by remember { mutableIntStateOf(0) }
|
||||
|
||||
var listingJob by remember { mutableStateOf<kotlinx.coroutines.Job?>(null) }
|
||||
var listingJob by remember { mutableStateOf<Job?>(null) }
|
||||
val history = remember { mutableStateListOf<Pair<File, File>>() }
|
||||
var shownRoot by remember { mutableStateOf(initialRoot) }
|
||||
|
||||
fun loadDirectory(dir: File, resetScroll: Boolean = true) {
|
||||
fun loadDirectory(dir: File, resetScroll: Boolean = true, record: Boolean = true) {
|
||||
if (cancellingNavigation) return
|
||||
if (record && dir != currentDir) {
|
||||
history.add(currentDir to shownRoot)
|
||||
if (history.size > HISTORY_LIMIT) history.removeAt(0)
|
||||
}
|
||||
currentDir = dir
|
||||
shownRoot = currentRoot
|
||||
if (pickMode) pickPrefs.edit().putString("lastFilePickerDir", dir.absolutePath).apply()
|
||||
listingJob?.cancel()
|
||||
listingJob = scope.launch {
|
||||
@@ -205,25 +235,102 @@ fun FileManagerScreen(
|
||||
}
|
||||
|
||||
fun openDrive(dir: File) {
|
||||
if (cancellingNavigation) return
|
||||
currentRoot = dir
|
||||
loadDirectory(dir)
|
||||
}
|
||||
|
||||
fun returnToStart() {
|
||||
if (cancellingNavigation) return
|
||||
val dir = launchDir ?: return
|
||||
if (!dir.isDirectory) {
|
||||
Toast.makeText(context, R.string.fm_start_unavailable, Toast.LENGTH_SHORT).show()
|
||||
return
|
||||
}
|
||||
showFavorites = false
|
||||
showSearch = false
|
||||
searchQuery = ""
|
||||
currentRoot = initialRoot
|
||||
loadDirectory(dir)
|
||||
}
|
||||
|
||||
LaunchedEffect(Unit) { loadDirectory(rootDir) }
|
||||
|
||||
BackHandler(enabled = showFavorites || currentDir != currentRoot) {
|
||||
if (showFavorites) {
|
||||
showFavorites = false
|
||||
return@BackHandler
|
||||
val canGoUp = currentDir != currentRoot && currentDir.parentFile?.exists() == true
|
||||
fun isOperationActive() = isOperationRunning || operationJob?.isCompleted == false || cancelledJob?.isCompleted == false
|
||||
val operationActive = isOperationActive()
|
||||
|
||||
fun navigate(action: FileManagerNavigation) {
|
||||
if (cancellingNavigation) return
|
||||
when (action) {
|
||||
FileManagerNavigation.EXIT -> onExit?.invoke()
|
||||
FileManagerNavigation.RETURN_TO_START -> returnToStart()
|
||||
FileManagerNavigation.BACK -> {
|
||||
if (showFavorites) showFavorites = false
|
||||
else {
|
||||
while (history.isNotEmpty() && !history.last().first.isDirectory) history.removeAt(history.lastIndex)
|
||||
val previous = history.removeLastOrNull()
|
||||
if (previous != null) {
|
||||
currentRoot = previous.second
|
||||
loadDirectory(previous.first, record = false)
|
||||
} else if (canNavigateUp(currentDir, currentRoot)) currentDir.parentFile?.let { loadDirectory(it, record = false) }
|
||||
else onExit?.invoke()
|
||||
}
|
||||
}
|
||||
FileManagerNavigation.UP -> {
|
||||
if (showFavorites) showFavorites = false
|
||||
else if (canNavigateUp(currentDir, currentRoot)) currentDir.parentFile?.let { loadDirectory(it) }
|
||||
else onExit?.invoke()
|
||||
}
|
||||
}
|
||||
val parent = currentDir.parentFile
|
||||
if (parent != null && parent.exists()) loadDirectory(parent)
|
||||
}
|
||||
|
||||
val canGoUp = currentDir != currentRoot && currentDir.parentFile?.exists() == true
|
||||
fun goUp() {
|
||||
val parent = currentDir.parentFile
|
||||
if (currentDir != currentRoot && parent != null && parent.exists()) loadDirectory(parent)
|
||||
fun requestNavigation(action: FileManagerNavigation) {
|
||||
if (cancellingNavigation) return
|
||||
if (isOperationActive()) pendingNavigation = action else navigate(action)
|
||||
}
|
||||
|
||||
BackHandler(enabled = operationActive || cancellingNavigation || showFavorites || currentDir != currentRoot || history.isNotEmpty()) {
|
||||
requestNavigation(FileManagerNavigation.BACK)
|
||||
}
|
||||
|
||||
if (pendingNavigation != null) {
|
||||
OutlinedAlertDialog(
|
||||
onDismissRequest = { pendingNavigation = null },
|
||||
title = { Text(stringResource(R.string.fm_cancel_operation_title)) },
|
||||
text = { Text(stringResource(R.string.fm_cancel_operation_confirmation)) },
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
val action = pendingNavigation ?: return@TextButton
|
||||
pendingNavigation = null
|
||||
val job = operationJob?.takeUnless(Job::isCompleted)
|
||||
?: cancelledJob?.takeUnless(Job::isCompleted)
|
||||
if (job == null) {
|
||||
navigate(action)
|
||||
} else {
|
||||
cancellingNavigation = true
|
||||
cancelledJob = job
|
||||
job.cancel()
|
||||
scope.launch {
|
||||
job.join()
|
||||
if (operationJob === job) operationJob = null
|
||||
if (cancelledJob === job) cancelledJob = null
|
||||
pendingConflict = null
|
||||
isOperationRunning = false
|
||||
operationDeterminate = false
|
||||
cancellingNavigation = false
|
||||
if (action != FileManagerNavigation.EXIT) loadDirectory(currentDir, resetScroll = false)
|
||||
navigate(action)
|
||||
}
|
||||
}
|
||||
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.fm_accept)) }
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { pendingNavigation = null }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Text(stringResource(R.string.fm_decline))
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fun uniqueDestination(dir: File, name: String): File {
|
||||
@@ -241,11 +348,14 @@ fun FileManagerScreen(
|
||||
}
|
||||
|
||||
fun performDelete(file: File) {
|
||||
scope.launch {
|
||||
if (isOperationActive()) return
|
||||
operationJob = scope.launch {
|
||||
isOperationRunning = true
|
||||
operationLabel = context.getString(R.string.fm_op_deleting)
|
||||
val ok = withContext(Dispatchers.IO) { FileOps.delete(file) }
|
||||
val job = coroutineContext[Job]
|
||||
val ok = withContext(Dispatchers.IO) { FileOps.delete(file) { job?.isActive == false } }
|
||||
isOperationRunning = false
|
||||
if (operationJob === job) operationJob = null
|
||||
loadDirectory(currentDir, resetScroll = false)
|
||||
if (!ok) Toast.makeText(context, R.string.fm_delete_failed, Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
@@ -260,7 +370,7 @@ fun FileManagerScreen(
|
||||
|
||||
fun performPaste() {
|
||||
val sources = clipboardFiles
|
||||
if (sources.isEmpty() || isOperationRunning || operationJob?.isActive == true || cancelledJob?.isCompleted == false) return
|
||||
if (sources.isEmpty() || isOperationActive()) return
|
||||
val dstDir = currentDir
|
||||
val cut = isCutOperation
|
||||
|
||||
@@ -269,7 +379,7 @@ fun FileManagerScreen(
|
||||
operationDeterminate = true
|
||||
operationLabel = context.getString(if (cut) R.string.fm_op_moving else R.string.fm_op_copying)
|
||||
isOperationRunning = true
|
||||
val job = coroutineContext[kotlinx.coroutines.Job]
|
||||
val job = coroutineContext[Job]
|
||||
|
||||
var applyToAll: ConflictChoice? = null
|
||||
var failed = 0
|
||||
@@ -322,7 +432,7 @@ fun FileManagerScreen(
|
||||
|
||||
isOperationRunning = false
|
||||
operationDeterminate = false
|
||||
operationJob = null
|
||||
if (operationJob === job) operationJob = null
|
||||
clipboardFiles = emptyList()
|
||||
isCutOperation = false
|
||||
selectionMode = false
|
||||
@@ -340,32 +450,38 @@ fun FileManagerScreen(
|
||||
}
|
||||
|
||||
fun performRename(file: File, newName: String) {
|
||||
if (isOperationActive()) return
|
||||
val target = File(file.parentFile, newName)
|
||||
if (target.exists()) {
|
||||
Toast.makeText(context, context.getString(R.string.fm_already_exists, newName), Toast.LENGTH_SHORT).show()
|
||||
return
|
||||
}
|
||||
scope.launch {
|
||||
operationJob = scope.launch {
|
||||
val job = coroutineContext[Job]
|
||||
isOperationRunning = true
|
||||
operationLabel = context.getString(R.string.fm_op_renaming)
|
||||
val ok = withContext(Dispatchers.IO) { file.renameTo(target) }
|
||||
isOperationRunning = false
|
||||
if (operationJob === job) operationJob = null
|
||||
loadDirectory(currentDir, resetScroll = false)
|
||||
if (!ok) Toast.makeText(context, R.string.fm_rename_failed, Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
|
||||
fun createFolder(parent: File, name: String) {
|
||||
if (isOperationActive()) return
|
||||
val target = File(parent, name)
|
||||
if (target.exists()) {
|
||||
Toast.makeText(context, context.getString(R.string.fm_already_exists, name), Toast.LENGTH_SHORT).show()
|
||||
return
|
||||
}
|
||||
scope.launch {
|
||||
operationJob = scope.launch {
|
||||
val job = coroutineContext[Job]
|
||||
isOperationRunning = true
|
||||
operationLabel = context.getString(R.string.fm_op_creating_folder)
|
||||
val ok = withContext(Dispatchers.IO) { target.mkdirs() }
|
||||
isOperationRunning = false
|
||||
if (operationJob === job) operationJob = null
|
||||
loadDirectory(currentDir, resetScroll = false)
|
||||
if (!ok) Toast.makeText(context, R.string.fm_create_folder_failed, Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
@@ -382,6 +498,25 @@ fun FileManagerScreen(
|
||||
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
|
||||
}
|
||||
val drives = remember(storageTick) { StorageRoots.list(context) }
|
||||
var accessDrive by remember { mutableStateOf<String?>(null) }
|
||||
fun unreadable(drive: StorageRoot) {
|
||||
if (AllFilesAccess.missing()) accessDrive = drive.label
|
||||
else Toast.makeText(context, context.getString(R.string.fm_drive_not_readable, drive.label), Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
accessDrive?.let { label ->
|
||||
OutlinedAlertDialog(
|
||||
onDismissRequest = { accessDrive = null },
|
||||
title = { Text(stringResource(R.string.fm_drive_access_title, label)) },
|
||||
text = { Text(stringResource(R.string.fm_drive_access_text)) },
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
accessDrive = null
|
||||
AllFilesAccess.open(context)
|
||||
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.upd_open_settings)) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { accessDrive = null }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
val linuxRoot = remember(storageTick) {
|
||||
com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context).takeIf { File(it, "usr").isDirectory }
|
||||
}
|
||||
@@ -398,15 +533,16 @@ fun FileManagerScreen(
|
||||
onValueChange = { folderName = it },
|
||||
label = { Text(stringResource(R.string.fm_folder_name)) },
|
||||
singleLine = true,
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
showNewFolderDialog = false
|
||||
if (folderName.isNotBlank()) createFolder(currentDir, folderName)
|
||||
}) { Text(stringResource(R.string.fm_create)) }
|
||||
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.fm_create)) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { showNewFolderDialog = false }) { Text(stringResource(R.string.common_cancel)) } },
|
||||
dismissButton = { TextButton(onClick = { showNewFolderDialog = false }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -421,6 +557,7 @@ fun FileManagerScreen(
|
||||
onValueChange = { newName = it },
|
||||
label = { Text(stringResource(R.string.fm_new_name)) },
|
||||
singleLine = true,
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
@@ -428,9 +565,9 @@ fun FileManagerScreen(
|
||||
val file = renameTarget
|
||||
renameTarget = null
|
||||
if (file != null && newName.isNotBlank()) performRename(file, newName)
|
||||
}) { Text(stringResource(R.string.fm_rename)) }
|
||||
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.fm_rename)) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { renameTarget = null }) { Text(stringResource(R.string.common_cancel)) } },
|
||||
dismissButton = { TextButton(onClick = { renameTarget = null }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -452,9 +589,9 @@ fun FileManagerScreen(
|
||||
TextButton(onClick = {
|
||||
selectedEntry = null
|
||||
performDelete(file)
|
||||
}) { Text(stringResource(R.string.common_delete)) }
|
||||
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_delete)) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { selectedEntry = null }) { Text(stringResource(R.string.common_cancel)) } },
|
||||
dismissButton = { TextButton(onClick = { selectedEntry = null }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -481,26 +618,28 @@ fun FileManagerScreen(
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
if (isOperationActive()) return@TextButton
|
||||
pendingBulkDelete = emptyList()
|
||||
selectionMode = false
|
||||
selectedPaths = emptySet()
|
||||
operationJob = scope.launch {
|
||||
isOperationRunning = true
|
||||
val job = coroutineContext[Job]
|
||||
var failed = 0
|
||||
victims.forEachIndexed { i, f ->
|
||||
operationLabel = context.getString(R.string.fm_op_deleting_batch, i + 1, victims.size, f.name)
|
||||
if (!withContext(Dispatchers.IO) { FileOps.delete(f) }) failed++
|
||||
if (!withContext(Dispatchers.IO) { FileOps.delete(f) { job?.isActive == false } }) failed++
|
||||
}
|
||||
isOperationRunning = false
|
||||
operationJob = null
|
||||
if (operationJob === job) operationJob = null
|
||||
loadDirectory(currentDir, resetScroll = false)
|
||||
if (failed > 0) {
|
||||
Toast.makeText(context, context.resources.getQuantityString(R.plurals.fm_delete_some_failed, failed, failed), Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
}) { Text(stringResource(R.string.common_delete), color = MaterialTheme.colorScheme.error) }
|
||||
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_delete), color = MaterialTheme.colorScheme.error) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { pendingBulkDelete = emptyList() }) { Text(stringResource(R.string.common_cancel)) } },
|
||||
dismissButton = { TextButton(onClick = { pendingBulkDelete = emptyList() }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -523,6 +662,7 @@ fun FileManagerScreen(
|
||||
androidx.compose.material3.Checkbox(
|
||||
checked = conflictApplyToAll,
|
||||
onCheckedChange = { conflictApplyToAll = it },
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
Text(stringResource(R.string.fm_conflict_apply_all), fontSize = 12.sp)
|
||||
}
|
||||
@@ -535,7 +675,7 @@ fun FileManagerScreen(
|
||||
ConflictChoice.SKIP to stringResource(R.string.fm_conflict_skip),
|
||||
).forEach { (choice, label) ->
|
||||
TextButton(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
modifier = Modifier.fillMaxWidth().focusGlide(CircleShape),
|
||||
onClick = { conflictChoice = choice; pendingConflict = null },
|
||||
) { Text(label, modifier = Modifier.fillMaxWidth()) }
|
||||
}
|
||||
@@ -543,13 +683,14 @@ fun FileManagerScreen(
|
||||
},
|
||||
confirmButton = {},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { conflictChoice = ConflictChoice.SKIP; pendingConflict = null }) {
|
||||
TextButton(onClick = { conflictChoice = ConflictChoice.SKIP; pendingConflict = null }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Text(stringResource(R.string.common_cancel))
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
val compactToolbar = LocalConfiguration.current.screenWidthDp < 600
|
||||
Column(modifier = Modifier.fillMaxSize()) {
|
||||
if (pickMode && !pickerTitle.isNullOrEmpty()) {
|
||||
Text(
|
||||
@@ -568,7 +709,7 @@ fun FileManagerScreen(
|
||||
onClick = { onPick?.invoke(currentDir) },
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp).focusGlide(CircleShape),
|
||||
) {
|
||||
Icon(Icons.Filled.Folder, null, modifier = Modifier.size(18.dp))
|
||||
Spacer(Modifier.width(8.dp))
|
||||
@@ -580,9 +721,10 @@ fun FileManagerScreen(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.background(MaterialTheme.colorScheme.surfaceContainer)
|
||||
.then(if (compactToolbar) Modifier.horizontalScroll(rememberScrollState()) else Modifier)
|
||||
.padding(horizontal = 8.dp, vertical = 6.dp),
|
||||
) {
|
||||
IconButton(onClick = { goUp() }, enabled = canGoUp) {
|
||||
IconButton(onClick = { requestNavigation(FileManagerNavigation.UP) }, enabled = canGoUp && !cancellingNavigation, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Icon(Icons.Filled.ArrowBack, stringResource(R.string.fm_back), tint = MaterialTheme.colorScheme.primary)
|
||||
}
|
||||
|
||||
@@ -624,13 +766,10 @@ fun FileManagerScreen(
|
||||
if (drive.readable) {
|
||||
openDrive(drive.dir)
|
||||
} else {
|
||||
Toast.makeText(
|
||||
context,
|
||||
context.getString(R.string.fm_drive_not_readable, drive.label),
|
||||
Toast.LENGTH_SHORT,
|
||||
).show()
|
||||
unreadable(drive)
|
||||
}
|
||||
},
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
}
|
||||
linuxRoot?.let { root ->
|
||||
@@ -641,6 +780,7 @@ fun FileManagerScreen(
|
||||
Icon(Icons.Filled.Terminal, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(18.dp))
|
||||
},
|
||||
onClick = { showDriveMenu = false; openDrive(root) },
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -656,10 +796,10 @@ fun FileManagerScreen(
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f),
|
||||
modifier = if (compactToolbar) Modifier.widthIn(max = 140.dp) else Modifier.weight(1f),
|
||||
)
|
||||
} else if (LocalConfiguration.current.orientation == Configuration.ORIENTATION_PORTRAIT) {
|
||||
Spacer(Modifier.weight(1f))
|
||||
if (!compactToolbar) Spacer(Modifier.weight(1f))
|
||||
} else {
|
||||
Text(
|
||||
text = currentDir.name.ifBlank { currentDir.absolutePath },
|
||||
@@ -668,17 +808,24 @@ fun FileManagerScreen(
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f),
|
||||
modifier = if (compactToolbar) Modifier.widthIn(max = 140.dp) else Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
|
||||
if (launchDir != null) {
|
||||
IconButton(onClick = { requestNavigation(FileManagerNavigation.RETURN_TO_START) }, enabled = !cancellingNavigation, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Icon(Icons.AutoMirrored.Filled.KeyboardReturn, stringResource(R.string.fm_return_to_start), tint = MaterialTheme.colorScheme.primary)
|
||||
}
|
||||
if (LocalConfiguration.current.screenWidthDp >= 700) Spacer(Modifier.width(56.dp))
|
||||
}
|
||||
|
||||
if (!showFavorites) {
|
||||
if (!pickMode) {
|
||||
OutlinedButton(
|
||||
onClick = { showNewFolderDialog = true },
|
||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary.copy(alpha = 0.6f)),
|
||||
contentPadding = PaddingValues(horizontal = 10.dp, vertical = 2.dp),
|
||||
modifier = Modifier.height(32.dp),
|
||||
modifier = Modifier.height(32.dp).focusGlide(CircleShape),
|
||||
) {
|
||||
Icon(Icons.Filled.CreateNewFolder, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(16.dp))
|
||||
Spacer(Modifier.width(5.dp))
|
||||
@@ -688,18 +835,18 @@ fun FileManagerScreen(
|
||||
IconButton(onClick = {
|
||||
gridView = !gridView
|
||||
browsePrefs.edit().putBoolean("fmGridView", gridView).apply()
|
||||
}) {
|
||||
}, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Icon(
|
||||
if (gridView) Icons.Filled.ViewList else Icons.Filled.GridView,
|
||||
if (gridView) stringResource(R.string.fm_list_view) else stringResource(R.string.fm_grid_view),
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
IconButton(onClick = { showSearch = !showSearch; if (!showSearch) searchQuery = "" }) {
|
||||
IconButton(onClick = { showSearch = !showSearch; if (!showSearch) searchQuery = "" }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Icon(Icons.Filled.Search, stringResource(R.string.fm_search), tint = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
Box {
|
||||
IconButton(onClick = { showSortMenu = true }) {
|
||||
IconButton(onClick = { showSortMenu = true }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Icon(Icons.Filled.Sort, stringResource(R.string.fm_sort), tint = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
DropdownMenu(expanded = showSortMenu, onDismissRequest = { showSortMenu = false }) {
|
||||
@@ -716,6 +863,7 @@ fun FileManagerScreen(
|
||||
showSortMenu = false
|
||||
loadDirectory(currentDir, resetScroll = false)
|
||||
},
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
}
|
||||
HorizontalDivider(color = MaterialTheme.colorScheme.outline)
|
||||
@@ -726,6 +874,7 @@ fun FileManagerScreen(
|
||||
browsePrefs.edit().putBoolean("fmCompactRows", compactRows).apply()
|
||||
showSortMenu = false
|
||||
},
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
DropdownMenuItem(
|
||||
text = { Text(if (showHidden) stringResource(R.string.fm_hide_hidden) else stringResource(R.string.fm_show_hidden)) },
|
||||
@@ -735,18 +884,24 @@ fun FileManagerScreen(
|
||||
showSortMenu = false
|
||||
loadDirectory(currentDir, resetScroll = false)
|
||||
},
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
IconButton(onClick = { showFavorites = !showFavorites }) {
|
||||
IconButton(onClick = { showFavorites = !showFavorites }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
if (showFavorites) {
|
||||
Icon(Icons.Filled.Star, stringResource(R.string.fm_hide_favorites), tint = MaterialTheme.colorScheme.primary)
|
||||
} else {
|
||||
Icon(Icons.Filled.StarBorder, stringResource(R.string.fm_show_favorites), tint = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
if (!pickMode && onExit != null) {
|
||||
IconButton(onClick = { requestNavigation(FileManagerNavigation.EXIT) }, enabled = !cancellingNavigation, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Icon(Icons.AutoMirrored.Filled.ExitToApp, stringResource(R.string.fm_exit), tint = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (showSearch && !showFavorites) {
|
||||
@@ -755,7 +910,7 @@ fun FileManagerScreen(
|
||||
onValueChange = { searchQuery = it },
|
||||
singleLine = true,
|
||||
placeholder = { Text(stringResource(R.string.fm_filter_folder), fontSize = 13.sp) },
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp).focusGlide(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -793,13 +948,14 @@ fun FileManagerScreen(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.background(MaterialTheme.colorScheme.primary.copy(alpha = 0.12f))
|
||||
.then(if (compactToolbar) Modifier.horizontalScroll(rememberScrollState()) else Modifier)
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp),
|
||||
) {
|
||||
Text(
|
||||
stringResource(R.string.fm_selected_count, selectedPaths.size),
|
||||
color = MaterialTheme.colorScheme.onBackground,
|
||||
fontSize = 13.sp,
|
||||
modifier = Modifier.weight(1f),
|
||||
modifier = if (compactToolbar) Modifier.padding(end = 12.dp) else Modifier.weight(1f),
|
||||
)
|
||||
val allVisibleSelected = visibleEntries.isNotEmpty() && visibleEntries.all { it.absolutePath in selectedPaths }
|
||||
val anyVisibleSelected = visibleEntries.any { it.absolutePath in selectedPaths }
|
||||
@@ -810,6 +966,7 @@ fun FileManagerScreen(
|
||||
selectedPaths = if (allVisibleSelected) selectedPaths - shown.toSet() else selectedPaths + shown
|
||||
},
|
||||
contentPadding = selBarPadding,
|
||||
modifier = Modifier.focusGlide(CircleShape),
|
||||
) { Text(if (allVisibleSelected) stringResource(R.string.fm_select_none) else stringResource(R.string.fm_select_all), fontSize = 12.sp) }
|
||||
Spacer(Modifier.width(4.dp))
|
||||
OutlinedButton(
|
||||
@@ -821,6 +978,7 @@ fun FileManagerScreen(
|
||||
selectedPaths = emptySet()
|
||||
},
|
||||
contentPadding = selBarPadding,
|
||||
modifier = Modifier.focusGlide(CircleShape),
|
||||
) { Text(stringResource(R.string.fm_copy), fontSize = 12.sp) }
|
||||
Spacer(Modifier.width(4.dp))
|
||||
OutlinedButton(
|
||||
@@ -832,6 +990,7 @@ fun FileManagerScreen(
|
||||
selectedPaths = emptySet()
|
||||
},
|
||||
contentPadding = selBarPadding,
|
||||
modifier = Modifier.focusGlide(CircleShape),
|
||||
) { Text(stringResource(R.string.fm_cut), fontSize = 12.sp) }
|
||||
Spacer(Modifier.width(4.dp))
|
||||
OutlinedButton(
|
||||
@@ -839,11 +998,13 @@ fun FileManagerScreen(
|
||||
onClick = { pendingBulkDelete = visibleEntries.filter { it.absolutePath in selectedPaths } },
|
||||
contentPadding = selBarPadding,
|
||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.error),
|
||||
modifier = Modifier.focusGlide(CircleShape),
|
||||
) { Text(stringResource(R.string.common_delete), color = MaterialTheme.colorScheme.error, fontSize = 12.sp) }
|
||||
Spacer(Modifier.width(4.dp))
|
||||
OutlinedButton(
|
||||
onClick = { selectionMode = false; selectedPaths = emptySet() },
|
||||
contentPadding = selBarPadding,
|
||||
modifier = Modifier.focusGlide(CircleShape),
|
||||
) { Text(stringResource(R.string.fm_done), fontSize = 12.sp) }
|
||||
}
|
||||
}
|
||||
@@ -865,7 +1026,7 @@ fun FileManagerScreen(
|
||||
if (isCutOperation) stringResource(R.string.fm_paste_move_here, what) else stringResource(R.string.fm_paste_here, what),
|
||||
color = MaterialTheme.colorScheme.onBackground, fontSize = 13.sp, modifier = Modifier.weight(1f),
|
||||
)
|
||||
TextButton(onClick = { clipboardFiles = emptyList(); isCutOperation = false }) {
|
||||
TextButton(onClick = { clipboardFiles = emptyList(); isCutOperation = false }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Text(stringResource(R.string.common_cancel), color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 12.sp)
|
||||
}
|
||||
}
|
||||
@@ -896,7 +1057,7 @@ fun FileManagerScreen(
|
||||
isOperationRunning = false
|
||||
operationDeterminate = false
|
||||
loadDirectory(currentDir, resetScroll = false)
|
||||
}) { Text(stringResource(R.string.common_cancel), fontSize = 12.sp) }
|
||||
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel), fontSize = 12.sp) }
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
@@ -926,7 +1087,7 @@ fun FileManagerScreen(
|
||||
add(locItem(stringResource(R.string.fm_drive_internal), Icons.Filled.Smartphone, File("/storage/emulated/0")))
|
||||
drives.filter { it.removable }.forEach { d ->
|
||||
add(RailItem(d.label, Icons.Filled.SdStorage, !showFavorites && currentRoot.absolutePath == d.dir.absolutePath) {
|
||||
showFavorites = false; if (d.readable) openDrive(d.dir)
|
||||
showFavorites = false; if (d.readable) openDrive(d.dir) else unreadable(d)
|
||||
})
|
||||
}
|
||||
linuxRoot?.let { add(locItem(stringResource(R.string.fm_drive_linux), Icons.Filled.Terminal, it)) }
|
||||
@@ -986,7 +1147,7 @@ fun FileManagerScreen(
|
||||
contentPadding = PaddingValues(8.dp),
|
||||
) {
|
||||
if (canGoUp) item(key = "..", span = { GridItemSpan(maxLineSpan) }) {
|
||||
ParentFolderRow(compact = compactRows, onTap = { goUp() })
|
||||
ParentFolderRow(compact = compactRows, onTap = { requestNavigation(FileManagerNavigation.UP) })
|
||||
}
|
||||
items(shownEntries, key = { it.absolutePath }) { file ->
|
||||
val isFav = remember(file.absolutePath, favTick) {
|
||||
@@ -1049,10 +1210,10 @@ fun FileManagerScreen(
|
||||
)
|
||||
}
|
||||
}
|
||||
} else
|
||||
} else {
|
||||
LazyColumn(state = listState, modifier = Modifier.fillMaxSize()) {
|
||||
if (canGoUp) item(key = "..") {
|
||||
ParentFolderRow(compact = compactRows, onTap = { goUp() })
|
||||
ParentFolderRow(compact = compactRows, onTap = { requestNavigation(FileManagerNavigation.UP) })
|
||||
}
|
||||
if (entries.isEmpty()) {
|
||||
item {
|
||||
@@ -1129,6 +1290,7 @@ fun FileManagerScreen(
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (pullState.verticalOffset > 0.5f || pullState.isRefreshing) {
|
||||
PullToRefreshContainer(
|
||||
state = pullState,
|
||||
|
||||
@@ -9,6 +9,7 @@ import java.io.FileOutputStream
|
||||
import java.io.IOException
|
||||
import java.nio.file.Files
|
||||
import java.util.Locale
|
||||
import java.util.concurrent.CancellationException
|
||||
|
||||
object FileOps {
|
||||
private const val TAG = "FileOps"
|
||||
@@ -24,24 +25,27 @@ object FileOps {
|
||||
|
||||
fun isSymlink(file: File): Boolean = try { Files.isSymbolicLink(file.toPath()) } catch (e: Exception) { false }
|
||||
|
||||
fun delete(target: File?): Boolean {
|
||||
fun delete(target: File?, isCancelled: () -> Boolean = { false }): Boolean {
|
||||
if (isCancelled()) throw CancellationException("Delete cancelled: $target")
|
||||
if (target == null) return false
|
||||
if (target.isDirectory && !isSymlink(target)) {
|
||||
if (!clear(target)) return false
|
||||
if (!clear(target, isCancelled)) return false
|
||||
}
|
||||
if (isCancelled()) throw CancellationException("Delete cancelled: $target")
|
||||
return target.delete()
|
||||
}
|
||||
|
||||
fun clear(dir: File): Boolean {
|
||||
fun clear(dir: File, isCancelled: () -> Boolean = { false }): Boolean {
|
||||
val children = dir.listFiles() ?: return true
|
||||
var ok = true
|
||||
for (child in children) if (!delete(child)) ok = false
|
||||
for (child in children) if (!delete(child, isCancelled)) ok = false
|
||||
return ok
|
||||
}
|
||||
|
||||
fun totalSize(f: File?): Long {
|
||||
fun totalSize(f: File?, isCancelled: () -> Boolean = { false }): Long {
|
||||
if (isCancelled()) throw CancellationException("Size scan cancelled: $f")
|
||||
if (f == null || !f.exists() || isSymlink(f)) return 0
|
||||
if (f.isDirectory) return f.listFiles()?.sumOf { totalSize(it) } ?: 0
|
||||
if (f.isDirectory) return f.listFiles()?.sumOf { totalSize(it, isCancelled) } ?: 0
|
||||
return f.length()
|
||||
}
|
||||
|
||||
@@ -53,12 +57,11 @@ object FileOps {
|
||||
return true
|
||||
}
|
||||
if (!copyWithProgress(src, dst, progress, isCancelled)) return false
|
||||
if (isCancelled()) return false
|
||||
return delete(src)
|
||||
}
|
||||
|
||||
fun copyWithProgress(src: File, dst: File, progress: ProgressCallback?, isCancelled: () -> Boolean = { false }): Boolean {
|
||||
val total = maxOf(totalSize(src), 1L)
|
||||
val total = maxOf(totalSize(src, isCancelled), 1L)
|
||||
return copyWithProgress(src, dst, longArrayOf(0), total, progress, isCancelled)
|
||||
}
|
||||
|
||||
@@ -71,15 +74,23 @@ object FileOps {
|
||||
return false
|
||||
}
|
||||
if (src.isDirectory) {
|
||||
if (!dst.exists() && !dst.mkdirs()) return false
|
||||
var allOk = true
|
||||
src.list()?.forEach { name ->
|
||||
if (!copyWithProgress(File(src, name), File(dst, name), done, total, progress, isCancelled)) {
|
||||
Log.e(TAG, "Failed to copy: ${File(src, name)}")
|
||||
allOk = false
|
||||
val created = if (dst.exists()) false else {
|
||||
if (!dst.mkdirs()) return false
|
||||
true
|
||||
}
|
||||
try {
|
||||
var allOk = true
|
||||
src.list()?.forEach { name ->
|
||||
if (!copyWithProgress(File(src, name), File(dst, name), done, total, progress, isCancelled)) {
|
||||
Log.e(TAG, "Failed to copy: ${File(src, name)}")
|
||||
allOk = false
|
||||
}
|
||||
}
|
||||
return allOk
|
||||
} catch (e: CancellationException) {
|
||||
if (created) delete(dst)
|
||||
throw e
|
||||
}
|
||||
return allOk
|
||||
}
|
||||
val parent = dst.parentFile
|
||||
if (!src.exists() || (parent != null && !parent.exists() && !parent.mkdirs())) return false
|
||||
@@ -118,6 +129,7 @@ object FileOps {
|
||||
val size = input.size()
|
||||
var position = 0L
|
||||
while (position < size) {
|
||||
if (isCancelled()) throw CancellationException("Copy cancelled: $src")
|
||||
val transferred = input.transferTo(position, minOf(chunk, size - position), channel)
|
||||
if (transferred <= 0) break
|
||||
position += transferred
|
||||
@@ -125,12 +137,19 @@ object FileOps {
|
||||
progress?.onProgress(done[0], total)
|
||||
}
|
||||
if (position < size) throw IOException("Incomplete copy: $position/$size bytes")
|
||||
if (size > 0 && isCancelled()) throw CancellationException("Copy cancelled: $src")
|
||||
}
|
||||
}
|
||||
staging?.let { directory ->
|
||||
val copied = File(directory, "file").toPath()
|
||||
if (permissions != null && Files.getPosixFilePermissions(copied) != permissions) {
|
||||
Files.setPosixFilePermissions(copied, permissions)
|
||||
if (permissions != null) {
|
||||
try {
|
||||
if (Files.getPosixFilePermissions(copied) != permissions) {
|
||||
Files.setPosixFilePermissions(copied, permissions)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Failed to restore destination permissions: $target", e)
|
||||
}
|
||||
}
|
||||
if (isCancelled()) throw java.util.concurrent.CancellationException("Copy cancelled: $src")
|
||||
Files.move(copied, target.toPath(), java.nio.file.StandardCopyOption.ATOMIC_MOVE)
|
||||
|
||||
@@ -26,11 +26,12 @@ class FilePickerActivity : ComponentActivity() {
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
requestedOrientation = com.droiddeck.launcher.session.SessionPrefs.orientation(this)
|
||||
requestedOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
com.droiddeck.launcher.core.AllFilesAccess.ask(this)
|
||||
} else if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
|
||||
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)
|
||||
com.droiddeck.launcher.files.AllFilesAccess.ask(this)
|
||||
} else if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
|
||||
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
|
||||
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE), 1)
|
||||
}
|
||||
|
||||
val extensions = intent.getStringArrayExtra(EXTRA_EXTENSIONS)?.toList() ?: emptyList()
|
||||
@@ -53,6 +54,7 @@ class FilePickerActivity : ComponentActivity() {
|
||||
setResult(Activity.RESULT_OK, Intent().putExtra(EXTRA_SELECTED_FILE, file.absolutePath))
|
||||
finish()
|
||||
},
|
||||
onExit = { finish() },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import com.droiddeck.launcher.ui.focusGlide
|
||||
import android.widget.Toast
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
@@ -128,7 +130,7 @@ internal fun FilePropertiesDialog(
|
||||
)
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.fm_done)) } },
|
||||
confirmButton = { TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.fm_done)) } },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -182,6 +184,7 @@ private fun AttributeToggleRow(
|
||||
checked = checked,
|
||||
enabled = enabled,
|
||||
onCheckedChange = onToggle,
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog
|
||||
import androidx.compose.material3.AlertDialogDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.Composable
|
||||
|
||||
@@ -29,6 +29,49 @@ object StorageRoots {
|
||||
val seeds = LinkedHashSet<File>()
|
||||
}
|
||||
|
||||
private val EXTERNAL_MOUNT_TYPES = setOf(
|
||||
"vfat", "exfat", "texfat", "ntfs", "ntfs3", "fuseblk", "fuse", "sdcardfs",
|
||||
)
|
||||
|
||||
internal data class MountPoint(val target: File, val type: String)
|
||||
|
||||
internal fun parseMountPoints(mounts: String): List<MountPoint> {
|
||||
val out = ArrayList<MountPoint>()
|
||||
for (line in mounts.lineSequence()) {
|
||||
val parts = line.split(' ')
|
||||
if (parts.size < 3) continue
|
||||
out.add(MountPoint(File(parts[1].replace("\\040", " ")), parts[2].lowercase()))
|
||||
}
|
||||
return out.distinct()
|
||||
}
|
||||
|
||||
internal fun isExternalMount(mount: MountPoint): Boolean {
|
||||
val path = mount.target.path
|
||||
val name = when {
|
||||
path.startsWith("/storage/") -> path.removePrefix("/storage/")
|
||||
path.startsWith("/mnt/media_rw/") -> path.removePrefix("/mnt/media_rw/")
|
||||
path.startsWith("/mnt/") -> path.removePrefix("/mnt/")
|
||||
else -> return false
|
||||
}
|
||||
if ('/' in name || name.isEmpty() || name == "emulated" || name == "self") return false
|
||||
if (mount.type in EXTERNAL_MOUNT_TYPES) {
|
||||
if (path.startsWith("/mnt/") && !path.startsWith("/mnt/media_rw/")) {
|
||||
val lower = name.lowercase()
|
||||
if (!lower.contains("usb") && !lower.contains("otg") &&
|
||||
!lower.contains("udisk") && !lower.contains("disk")
|
||||
) return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
return path.startsWith("/storage/") || path.startsWith("/mnt/media_rw/")
|
||||
}
|
||||
|
||||
internal fun parseExternalMounts(mounts: String): List<File> =
|
||||
parseMountPoints(mounts).filter(::isExternalMount).map { it.target }
|
||||
|
||||
fun externalMounts(): List<File> =
|
||||
runCatching { parseExternalMounts(File("/proc/mounts").readText()) }.getOrDefault(emptyList())
|
||||
|
||||
fun list(context: Context): List<StorageRoot> {
|
||||
val volumes = LinkedHashMap<String, Volume>()
|
||||
|
||||
@@ -44,21 +87,27 @@ object StorageRoots {
|
||||
val storageManager = context.getSystemService(StorageManager::class.java)
|
||||
|
||||
storageManager?.storageVolumes.orEmpty()
|
||||
.filter { isMounted(it.state) }
|
||||
.forEach { volume ->
|
||||
.filter { present(it.state) }
|
||||
.forEachIndexed { index, volume ->
|
||||
val uuid = volume.uuid?.takeIf { it.isNotBlank() }
|
||||
val entry = volumeOf(if (volume.isPrimary) PRIMARY_KEY else uuid ?: return@forEach)
|
||||
val dirName = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) volume.directory?.name?.takeIf { it.isNotBlank() } else null
|
||||
val descSlug = volume.getDescription(context)?.trim()
|
||||
?.takeIf { it.isNotBlank() && !it.equals("android", ignoreCase = true) }
|
||||
?.replace(Regex("[^A-Za-z0-9._-]+"), "-")
|
||||
val entry = volumeOf(if (volume.isPrimary) PRIMARY_KEY else uuid ?: dirName ?: descSlug ?: "volume-$index")
|
||||
entry.removable = !volume.isPrimary && volume.isRemovable
|
||||
if (entry.label == null) entry.label = labelFor(context, volume, uuid)
|
||||
if (entry.label == null) entry.label = labelFor(context, volume, uuid ?: dirName ?: descSlug)
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
volume.directory?.let { entry.candidates += it }
|
||||
}
|
||||
if (uuid != null) {
|
||||
entry.candidates += File("/storage/$uuid")
|
||||
entry.candidates += File("/mnt/media_rw/$uuid")
|
||||
val name = uuid ?: dirName
|
||||
if (name != null) {
|
||||
entry.candidates += File("/storage/$name")
|
||||
entry.candidates += File("/mnt/media_rw/$name")
|
||||
if (uuid != null) appDirs.filter { belongsTo(storageManager!!, it, volume) }
|
||||
.forEach { entry.seeds += it }
|
||||
}
|
||||
appDirs.filter { belongsTo(storageManager!!, it, volume) }.forEach { entry.seeds += it }
|
||||
}
|
||||
|
||||
File("/storage").listFiles().orEmpty().forEach { child ->
|
||||
@@ -68,6 +117,11 @@ object StorageRoots {
|
||||
File("/mnt/media_rw").listFiles().orEmpty().forEach { child ->
|
||||
if (child.isDirectory) volumeOf(child.name).candidates += child
|
||||
}
|
||||
for (mount in externalMounts()) {
|
||||
val entry = volumeOf(mount.name)
|
||||
if (entry.label == null) entry.label = mount.name
|
||||
entry.candidates += mount
|
||||
}
|
||||
|
||||
appDirs.forEach { dir ->
|
||||
val root = volumeRootOf(dir) ?: return@forEach
|
||||
@@ -141,15 +195,19 @@ object StorageRoots {
|
||||
|
||||
private fun labelFor(context: Context, volume: StorageVolume, uuid: String?): String {
|
||||
if (volume.isPrimary) return context.getString(R.string.fm_drive_internal)
|
||||
if (volume.isRemovable) return context.getString(R.string.fm_drive_sd)
|
||||
val description = volume.getDescription(context)?.trim()
|
||||
return description?.takeIf { it.isNotBlank() && !it.equals("android", ignoreCase = true) }
|
||||
?: uuid
|
||||
if (!description.isNullOrBlank() && !description.equals("android", ignoreCase = true)) return description
|
||||
if (volume.isRemovable) return context.getString(R.string.fm_drive_sd)
|
||||
return uuid
|
||||
?: context.getString(R.string.fm_drive_storage)
|
||||
}
|
||||
|
||||
private fun isEmulated(dir: File): Boolean = dir.absolutePath.startsWith(EMULATED_PREFIX)
|
||||
|
||||
private fun present(state: String?): Boolean =
|
||||
isMounted(state) || state == Environment.MEDIA_UNMOUNTED || state == Environment.MEDIA_CHECKING ||
|
||||
state == Environment.MEDIA_NOFS || state == Environment.MEDIA_UNMOUNTABLE
|
||||
|
||||
private fun isMounted(state: String?): Boolean =
|
||||
state == Environment.MEDIA_MOUNTED || state == Environment.MEDIA_MOUNTED_READ_ONLY
|
||||
|
||||
|
||||
@@ -4,7 +4,9 @@ import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.files.PeIconExtractor
|
||||
import com.droiddeck.launcher.runtime.BattleNet
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreArt
|
||||
import com.droiddeck.launcher.stores.StoreGameSidecar
|
||||
import org.json.JSONObject
|
||||
@@ -75,14 +77,18 @@ object AddedGameArt {
|
||||
)
|
||||
}
|
||||
|
||||
private fun storeArt(context: Context, game: AddedGames.Game): BattleNet.Art? =
|
||||
if (game.source != Store.BATTLENET.id) null else game.storeId?.let(BattleNet::title)?.let { BattleNet.art(context, it) }
|
||||
|
||||
fun resolve(context: Context, game: AddedGames.Game): Art {
|
||||
val own = local(game)
|
||||
val cache = cacheDir(context, game)
|
||||
val store = storeArt(context, game)
|
||||
fun cached(name: String) = File(cache, name).takeIf { it.isFile }
|
||||
return Art(
|
||||
portrait = chosen(cache, Slot.COVER) ?: own.portrait ?: cached("p.jpg") ?: exeArt(context, game, cover = true),
|
||||
header = chosen(cache, Slot.WIDE) ?: own.header ?: cached("header.jpg") ?: exeArt(context, game, cover = false),
|
||||
hero = chosen(cache, Slot.BACKGROUND) ?: own.hero ?: cached("hero.jpg"),
|
||||
portrait = chosen(cache, Slot.COVER) ?: own.portrait ?: store?.cover ?: cached("p.jpg") ?: exeArt(context, game, cover = true),
|
||||
header = chosen(cache, Slot.WIDE) ?: own.header ?: store?.header ?: cached("header.jpg") ?: exeArt(context, game, cover = false),
|
||||
hero = chosen(cache, Slot.BACKGROUND) ?: own.hero ?: store?.header ?: cached("hero.jpg"),
|
||||
logo = chosen(cache, Slot.LOGO) ?: own.logo ?: cached("logo.png"),
|
||||
icon = chosen(cache, Slot.ICON) ?: own.icon ?: cached("icon-sgdb.png") ?: exeIcon(context, game),
|
||||
)
|
||||
@@ -91,15 +97,16 @@ object AddedGameArt {
|
||||
fun describe(context: Context, game: AddedGames.Game): List<SlotState> {
|
||||
val own = local(game)
|
||||
val cache = cacheDir(context, game)
|
||||
val store = storeArt(context, game)
|
||||
fun cached(name: String): Pair<File, String>? = File(cache, name).takeIf { it.isFile }?.let { f ->
|
||||
f to (File(cache, "$name.src").takeIf { it.isFile }?.readText()?.trim()?.takeIf { it.isNotEmpty() } ?: STEAM)
|
||||
}
|
||||
return Slot.values().map { slot ->
|
||||
chosen(cache, slot)?.let { return@map SlotState(slot, it, chosenSource(context, game, slot).first.ifEmpty { FILE }, true) }
|
||||
val auto: Pair<File, String>? = when (slot) {
|
||||
Slot.COVER -> own.portrait?.let { it to FOLDER } ?: cached("p.jpg") ?: exeArt(context, game, cover = true)?.let { it to EXE }
|
||||
Slot.WIDE -> own.header?.let { it to FOLDER } ?: cached("header.jpg") ?: exeArt(context, game, cover = false)?.let { it to EXE }
|
||||
Slot.BACKGROUND -> own.hero?.let { it to FOLDER } ?: cached("hero.jpg")
|
||||
Slot.COVER -> own.portrait?.let { it to FOLDER } ?: store?.cover?.let { it to AUTO } ?: cached("p.jpg") ?: exeArt(context, game, cover = true)?.let { it to EXE }
|
||||
Slot.WIDE -> own.header?.let { it to FOLDER } ?: store?.header?.let { it to AUTO } ?: cached("header.jpg") ?: exeArt(context, game, cover = false)?.let { it to EXE }
|
||||
Slot.BACKGROUND -> own.hero?.let { it to FOLDER } ?: store?.header?.let { it to AUTO } ?: cached("hero.jpg")
|
||||
Slot.LOGO -> own.logo?.let { it to FOLDER } ?: cached("logo.png")
|
||||
Slot.ICON -> own.icon?.let { it to FOLDER } ?: File(cache, "icon-sgdb.png").takeIf { it.isFile }?.let { it to SGDB }
|
||||
?: exeIcon(context, game)?.let { it to EXE }
|
||||
@@ -253,12 +260,13 @@ object AddedGameArt {
|
||||
internal fun missing(context: Context, game: AddedGames.Game): Set<Slot> {
|
||||
val own = local(game)
|
||||
val cache = cacheDir(context, game)
|
||||
val store = storeArt(context, game)
|
||||
fun has(slot: Slot, mine: File?, cached: String) = chosen(cache, slot) != null || mine != null || File(cache, cached).isFile
|
||||
return Slot.values().filterNot { slot ->
|
||||
when (slot) {
|
||||
Slot.COVER -> has(slot, own.portrait, "p.jpg")
|
||||
Slot.WIDE -> has(slot, own.header, "header.jpg")
|
||||
Slot.BACKGROUND -> has(slot, own.hero, "hero.jpg")
|
||||
Slot.COVER -> has(slot, own.portrait ?: store?.cover, "p.jpg")
|
||||
Slot.WIDE -> has(slot, own.header ?: store?.header, "header.jpg")
|
||||
Slot.BACKGROUND -> has(slot, own.hero ?: store?.header, "hero.jpg")
|
||||
Slot.LOGO -> has(slot, own.logo, "logo.png")
|
||||
Slot.ICON -> has(slot, own.icon, "icon-sgdb.png")
|
||||
}
|
||||
@@ -279,14 +287,17 @@ object AddedGameArt {
|
||||
var sgdbDown = false
|
||||
var changed = false
|
||||
for (game in games) {
|
||||
if (forgetOtherAppsArt(context, game)) changed = true
|
||||
val cache = cacheDir(context, game)
|
||||
val start = missing(context, game)
|
||||
val again = refetch(cache) intersect start
|
||||
if (again.isEmpty()) File(cache, REFETCH).delete()
|
||||
val full = Slot.COVER in start
|
||||
val allowed = if (full) Slot.values().toSet() else EXTRAS
|
||||
val allowed = if (full) Slot.values().toSet() else EXTRAS + again
|
||||
var need = start intersect allowed
|
||||
if (need.isEmpty() || (need == setOf(Slot.ICON) && sgdbKey.isEmpty())) continue
|
||||
val cache = cacheDir(context, game)
|
||||
val tried = File(cache, EXTRAS_TRIED)
|
||||
if (!full && tried.isFile && tried.lastModified() >= keyChangedAt && System.currentTimeMillis() - tried.lastModified() < RETRY_AFTER_MS) continue
|
||||
if (!full && again.isEmpty() && tried.isFile && tried.lastModified() >= keyChangedAt && System.currentTimeMillis() - tried.lastModified() < RETRY_AFTER_MS) continue
|
||||
cache.mkdirs()
|
||||
if (Slot.LOGO in need && game.source != Library.ADDED && runCatching { sources.storeLogo(game) }.getOrDefault(false)) {
|
||||
changed = true
|
||||
@@ -316,12 +327,47 @@ object AddedGameArt {
|
||||
asked = false
|
||||
}
|
||||
}
|
||||
if ((missing(context, game) intersect EXTRAS).isEmpty()) tried.delete() else if (asked) tried.writeText("")
|
||||
val left = missing(context, game)
|
||||
if (again.isNotEmpty()) keepRefetch(cache, again intersect left)
|
||||
if ((left intersect EXTRAS).isEmpty()) tried.delete() else if (asked) tried.writeText("")
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
internal const val REFETCH = "refetch"
|
||||
|
||||
private fun refetch(cache: File): Set<Slot> =
|
||||
runCatching { File(cache, REFETCH).readText() }.getOrDefault("").split(',').mapNotNull { key -> Slot.values().firstOrNull { it.key == key } }.toSet()
|
||||
|
||||
private fun keepRefetch(cache: File, slots: Set<Slot>) {
|
||||
if (slots.isEmpty()) File(cache, REFETCH).delete() else File(cache, REFETCH).writeText(slots.joinToString(",") { it.key })
|
||||
}
|
||||
|
||||
internal fun forgetOtherAppsArt(context: Context, game: AddedGames.Game): Boolean {
|
||||
val cache = cacheDir(context, game)
|
||||
val recorded = SteamMatch.get(context, game.folder.path)?.takeIf { it.appId != null }
|
||||
val legacy = runCatching { File(cache, "steam-appid").readText().trim().toInt() }.getOrNull()?.takeIf { it > 0 }
|
||||
val before = recorded?.appId ?: legacy ?: return false
|
||||
val identity = runCatching { GameIdentifier.identify(game.exe) }.getOrNull()
|
||||
val now = identity?.appId
|
||||
val fromFiles = recorded?.certainty == SteamMatch.Certainty.FILES || before == GameIdentifier.SPACEWAR
|
||||
if (now == before || (now == null && !fromFiles)) return false
|
||||
SteamMatch.put(context, game.folder.path,
|
||||
if (identity != null && now != null) SteamMatch.Match(now, SteamMatch.Certainty.FILES, identity.source.name.lowercase(), System.currentTimeMillis())
|
||||
else SteamMatch.Match(null, SteamMatch.Certainty.NONE, "", 0))
|
||||
val dropped = Slot.values().filter { File(cache, SteamGridDb.cacheName(it)).delete() }.toSet()
|
||||
Slot.values().forEach { File(cache, SteamGridDb.cacheName(it) + ".src").delete() }
|
||||
listOf("sgdb-id", "steam-appid", EXTRAS_TRIED).forEach { File(cache, it).delete() }
|
||||
keepRefetch(cache, refetch(cache) + dropped)
|
||||
Log.i(TAG, "${game.name}: its files no longer name Steam app $before; its art is fetched again")
|
||||
return dropped.isNotEmpty()
|
||||
}
|
||||
|
||||
internal fun steamMatch(context: Context, game: AddedGames.Game, search: (String) -> Int?): SteamMatch.Match {
|
||||
if (game.source == Store.BATTLENET.id) {
|
||||
val id = game.storeId?.let(BattleNet::title)?.steam
|
||||
return SteamMatch.Match(id, if (id == null) SteamMatch.Certainty.NONE else SteamMatch.Certainty.FILES, Store.BATTLENET.id, System.currentTimeMillis())
|
||||
}
|
||||
val match = SteamMatch.resolve(context, game.folder.path, game.exe, game.name, legacy = File(cacheDir(context, game), "steam-appid"), search = search)
|
||||
match.appId?.let { Log.i(TAG, "${game.name}: Steam app $it (${match.certainty.name.lowercase()})") }
|
||||
return match
|
||||
@@ -361,14 +407,14 @@ object AddedGameArt {
|
||||
.filter { it.second > 0 && it.first.isNotEmpty() }
|
||||
.maxByOrNull { it.second }?.first
|
||||
|
||||
private fun search(name: String): String? {
|
||||
internal fun search(name: String): String? {
|
||||
val term = name.replace(EDITION, " ").trim().ifEmpty { name }
|
||||
val json = get(STORE_SEARCH + URLEncoder.encode(term, "UTF-8"))?.toString(Charsets.UTF_8) ?: return null
|
||||
val items = JSONObject(json).optJSONArray("items") ?: return null
|
||||
return pickStoreResult(name, (0 until items.length()).map { items.getJSONObject(it) }.map { it.optString("id") to it.optString("name") })
|
||||
}
|
||||
|
||||
private fun download(id: String, cache: File, slots: Set<Slot>): Boolean {
|
||||
internal fun download(id: String, cache: File, slots: Set<Slot> = Slot.entries.toSet()): Boolean {
|
||||
var got = false
|
||||
for ((slot, remote, localName) in listOf(
|
||||
Triple(Slot.COVER, "library_600x900.jpg", "p.jpg"), Triple(Slot.WIDE, "header.jpg", "header.jpg"),
|
||||
|
||||
@@ -6,6 +6,7 @@ import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import org.json.JSONObject
|
||||
import com.droiddeck.launcher.session.GameStorage
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.SteamLibraries
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreGameSidecar
|
||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
@@ -69,6 +70,10 @@ object AddedGames {
|
||||
if (path.startsWith("$roms/")) return "/root/ROMs/" + path.removePrefix("$roms/")
|
||||
}
|
||||
StoreInstallRoot.externalGuestPath(context, host)?.let { return it }
|
||||
for (lib in SteamLibraries.list(context)) {
|
||||
if (path == lib.path) return lib.guest
|
||||
if (path.startsWith("${lib.path}/")) return lib.guest + "/" + path.removePrefix("${lib.path}/")
|
||||
}
|
||||
GameStorage.effective(context)?.let { lib ->
|
||||
if (path.startsWith("${lib.path}/")) return "$LIBRARY/" + path.removePrefix("${lib.path}/")
|
||||
}
|
||||
@@ -79,6 +84,19 @@ object AddedGames {
|
||||
return null
|
||||
}
|
||||
|
||||
fun hostPath(context: Context, guest: String): File? {
|
||||
if (!guest.startsWith("/") || guest.split('/').any { it == ".." }) return null
|
||||
val mapped = roots(context).map { it.host to it.guest } + StoreInstallRoot.externalRoots(context) +
|
||||
listOfNotNull(GameStorage.effective(context)?.let { File(it.path) to LIBRARY }) +
|
||||
SteamLibraries.list(context).map { it.host to it.guest } +
|
||||
(android.os.Environment.getExternalStorageDirectory() to "/root/Storage")
|
||||
for ((host, root) in mapped.sortedByDescending { it.second.length }) {
|
||||
if (guest == root) return host
|
||||
if (guest.startsWith("$root/")) return File(host, guest.removePrefix("$root/"))
|
||||
}
|
||||
return File(LinuxRuntime.rootDir(context), guest.removePrefix("/"))
|
||||
}
|
||||
|
||||
fun candidates(folder: File): List<File> = rank(folder).exes
|
||||
|
||||
fun rank(folder: File): GameExePicker.Ranking {
|
||||
@@ -149,7 +167,25 @@ object AddedGames {
|
||||
"appxmanifest.xml" to Regex("<Application\\b[^>]*?\\bExecutable\\s*=\\s*\"([^\"]+)\"", RegexOption.IGNORE_CASE),
|
||||
)
|
||||
|
||||
/** The card's Steam libraries: the arm64 client's steamapps and the x86-64 client's own folder beside it. */
|
||||
private val GAME_PARTS = setOf(
|
||||
"bin", "bin32", "bin64", "binaries", "x64", "x86", "win64", "win32", "windows",
|
||||
"launcher", "game", "engine", "system", "data", "app",
|
||||
)
|
||||
|
||||
internal fun groupGames(folder: File): List<File>? {
|
||||
val files = folder.listFiles() ?: return null
|
||||
if (files.any { it.isFile && it.name.endsWith(".exe", ignoreCase = true) && !skipExe(it.name) }) return null
|
||||
if (declaredExes(folder).isNotEmpty()) return null
|
||||
val dirs = files.filter { it.isDirectory && !it.name.startsWith(".") && !isSteamLibraryFolder(it.name) }.sortedBy { it.name.lowercase() }
|
||||
if (dirs.any { it.name.lowercase() in GAME_PARTS || GameExePicker.auxiliaryDir(it) }) return null
|
||||
return dirs.filter { rank(it).exes.isNotEmpty() }.takeIf { it.size >= 2 }
|
||||
}
|
||||
|
||||
private fun expand(folder: File, entries: Set<String>): List<File> =
|
||||
if (folder.path in entries) listOf(folder) else groupGames(folder) ?: listOf(folder)
|
||||
|
||||
private fun entryFolders(context: Context): Set<String> = AddedExes.list(context).map { it.folder }.toSet()
|
||||
|
||||
internal fun isSteamLibraryFolder(name: String): Boolean =
|
||||
name.equals("steamapps", ignoreCase = true) || name == com.droiddeck.launcher.session.GameStorage.X64_CARD_DIR
|
||||
|
||||
@@ -161,6 +197,7 @@ object AddedGames {
|
||||
GameStorage.effective(context)?.let { File(it.path, "steamapps/common") },
|
||||
)
|
||||
val removed = SessionPrefs.removedAddedGames(context).toSet()
|
||||
val entries = entryFolders(context)
|
||||
for (dir in folders.distinctBy { it.absolutePath }) {
|
||||
if (!dir.isDirectory) { Log.w(TAG, "$dir is not a folder; skipped"); continue }
|
||||
val steamInstalls = steamInstallDirs(dir)
|
||||
@@ -168,7 +205,7 @@ object AddedGames {
|
||||
if (folder.name.lowercase() in steamInstalls || isSteamLibraryFolder(folder.name)) continue
|
||||
if (folder.path in removed) continue
|
||||
if (folder.name == "Games" && StoreInstallRoot.roots(context).any { it.absolutePath == folder.absolutePath }) continue
|
||||
scanGame(context, folder, out)
|
||||
for (game in expand(folder, entries)) if (game.path !in removed) scanGame(context, game, out)
|
||||
}
|
||||
}
|
||||
for (entry in AddedExes.list(context)) {
|
||||
@@ -177,6 +214,9 @@ object AddedGames {
|
||||
scanGame(context, folder, out, single = entry)
|
||||
}
|
||||
for (folder in StoreInstallRoot.gameFolders(context)) if (StoreInstallRoot.isFinished(folder)) scanGame(context, folder, out)
|
||||
for (game in com.droiddeck.launcher.runtime.BattleNet.games(context)) {
|
||||
if (game.folder.path !in removed) com.droiddeck.launcher.runtime.BattleNet.shortcut(context, game)?.let(out::add)
|
||||
}
|
||||
return out.distinctBy { it.folder.canonicalPath }
|
||||
}
|
||||
|
||||
@@ -217,8 +257,9 @@ object AddedGames {
|
||||
val entries = AddedExes.list(context)
|
||||
fun owns(f: File) = holds(f) && sameGame(f, currentExe(context, entries, f), exe)
|
||||
entries.map { File(it.folder) }.filter(::owns).maxByOrNull { canonical(it).length }?.let { return it }
|
||||
SessionPrefs.removedAddedGames(context).map { File(it) }.filter(::owns).maxByOrNull { canonical(it).length }?.let { return it }
|
||||
SessionPrefs.removedAddedGames(context).map { File(it) }.filter { owns(it) && groupGames(it) == null }.maxByOrNull { canonical(it).length }?.let { return it }
|
||||
StoreInstallRoot.gameFolders(context).firstOrNull(::holds)?.let { return it }
|
||||
val removed = SessionPrefs.removedAddedGames(context)
|
||||
val dirs = listOfNotNull(
|
||||
GameStorage.effective(context)?.let { File(it.path, "steamapps/common") },
|
||||
GameStorage.effective(context)?.let { File(it.path) },
|
||||
@@ -227,7 +268,10 @@ object AddedGames {
|
||||
val base = canonical(dir)
|
||||
if (!inside(path, base)) continue
|
||||
val first = path.removePrefix("$base/").substringBefore('/')
|
||||
File(dir, first).takeIf { it.isDirectory && !isSteamLibraryFolder(first) }?.let { return it }
|
||||
val top = File(dir, first).takeIf { it.isDirectory && !isSteamLibraryFolder(first) && it.path !in removed } ?: continue
|
||||
val group = groupGames(top) ?: return top
|
||||
if (top.path in entries.map { it.folder }) return null
|
||||
return group.firstOrNull(::holds)
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -274,16 +318,16 @@ object AddedGames {
|
||||
|
||||
class FolderResult(val added: List<Game>, val already: Int)
|
||||
|
||||
fun addFolder(context: Context, dir: File, onGame: (Game) -> Unit = {}, onChecking: (String?) -> Unit = {}): FolderResult {
|
||||
fun addFolder(context: Context, dir: File, onGame: (Game) -> Unit = {}, onChecking: (String?) -> Unit = {}, showHidden: Boolean = false): FolderResult {
|
||||
val app = context.applicationContext
|
||||
// Binds are mounted at session start, so a new one reaches the session from the next start.
|
||||
if (guestPath(app, dir) == null) bindFolder(app, dir)
|
||||
val removed = SessionPrefs.removedAddedGames(app).toSet()
|
||||
val listed = listedFolders(app, removed)
|
||||
val entries = entryFolders(app)
|
||||
var already = 0
|
||||
val fresh = ArrayList<String>()
|
||||
val added = ArrayList<Game>()
|
||||
for (sub in dir.listFiles { f -> f.isDirectory && !f.name.startsWith(".") }?.sortedBy { it.name.lowercase() }.orEmpty()) {
|
||||
for (sub in dir.listFiles { f -> f.isDirectory && (showHidden || !f.name.startsWith(".")) }?.sortedBy { it.name.lowercase() }.orEmpty().flatMap { expand(it, entries) }) {
|
||||
val path = canonical(sub)
|
||||
if (listed.any { it == path || inside(path, it) || inside(it, path) }) { already++; continue }
|
||||
onChecking(sub.name)
|
||||
@@ -317,6 +361,7 @@ object AddedGames {
|
||||
|
||||
private fun listedFolders(context: Context, removed: Set<String>): List<String> {
|
||||
val out = ArrayList<String>()
|
||||
val entries = entryFolders(context)
|
||||
GamesFolderMigration.run(context)
|
||||
val dirs = listOfNotNull(
|
||||
GameStorage.effective(context)?.let { File(it.path) },
|
||||
@@ -326,7 +371,7 @@ object AddedGames {
|
||||
for (folder in dir.listFiles { f -> f.isDirectory }.orEmpty()) {
|
||||
if (folder.path in removed || isSteamLibraryFolder(folder.name)) continue
|
||||
if (folder.name == "Games" && StoreInstallRoot.roots(context).any { it.absolutePath == folder.absolutePath }) continue
|
||||
out.add(canonical(folder))
|
||||
expand(folder, entries).filter { it.path !in removed }.forEach { out.add(canonical(it)) }
|
||||
}
|
||||
}
|
||||
AddedExes.list(context).filter { it.folder !in removed }.forEach { out.add(canonical(File(it.folder))) }
|
||||
@@ -387,11 +432,17 @@ object AddedGames {
|
||||
}
|
||||
}
|
||||
|
||||
private class LoginUser(val id: String, val mostRecent: Boolean, val autoLogin: Boolean, val timestamp: Long)
|
||||
|
||||
internal fun accountConfig(root: File): File? {
|
||||
val users = runCatching { File(root, "config/loginusers.vdf").readText() }.getOrDefault("")
|
||||
val recent = Regex(""""(\d{5,})"\s*\{([^}]*)\}""").findAll(users)
|
||||
.lastOrNull { Regex(""""MostRecent"\s*"1"""").containsMatchIn(it.groupValues[2]) }
|
||||
val account = recent?.groupValues?.get(1)?.toLongOrNull()?.let { (it - 76561197960265728L).toString() }
|
||||
val recent = Regex(""""(\d{5,})"\s*\{([^}]*)\}""").findAll(users).map {
|
||||
val body = it.groupValues[2]
|
||||
LoginUser(it.groupValues[1], Regex(""""MostRecent"\s*"1"""").containsMatchIn(body), Regex(""""AutoLogin"\s*"1"""").containsMatchIn(body),
|
||||
Regex(""""timestamp"\s*"(\d+)"""").find(body)?.groupValues?.get(1)?.toLongOrNull() ?: 0L)
|
||||
}.filter { it.mostRecent || it.autoLogin || it.timestamp > 0 }.toList().asReversed()
|
||||
.maxWithOrNull(compareBy<LoginUser>({ it.mostRecent }, { it.autoLogin }, { it.timestamp }))
|
||||
val account = recent?.id?.toLongOrNull()?.let { (it - 76561197960265728L).toString() }
|
||||
?: File(root, "userdata").list()?.filter { it.isNotEmpty() && it.all(Char::isDigit) && it != "0" }?.singleOrNull()
|
||||
return account?.let { File(root, "userdata/$it/config") }
|
||||
}
|
||||
|
||||
@@ -26,27 +26,29 @@ object AddedGamesPublisher {
|
||||
if (now) work.run() else worker.execute(work)
|
||||
}
|
||||
|
||||
fun refreshDuringSession(context: Context) {
|
||||
fun refreshDuringSession(context: Context, active: () -> Boolean) {
|
||||
val app = context.applicationContext
|
||||
worker.execute {
|
||||
try {
|
||||
if (!active()) return@execute
|
||||
val before = AddedGames.listingFile(app).takeIf { it.isFile }?.readText().orEmpty()
|
||||
val known = runCatching {
|
||||
val listing = JSONArray(before)
|
||||
List(listing.length()) { listing.getJSONObject(it).optString("exe") }.toSet()
|
||||
}.getOrDefault(emptySet())
|
||||
val games = AddedGames.scan(app)
|
||||
if (!active()) return@execute
|
||||
AddedGames.writeListing(app, games)
|
||||
val arch = com.droiddeck.launcher.session.SessionPrefs.activeSteamClientArch(app)
|
||||
LibraryCache.save(app, Library.launchableGames(app, added = games, arch = arch), arch == "x86_64")
|
||||
val fresh = games.filter { it.guestExe !in known }
|
||||
if (fresh.isEmpty()) return@execute
|
||||
Log.i(TAG, "session refresh: ${fresh.size} game(s) not in the listing the session started with")
|
||||
val attempts = java.util.concurrent.atomic.AtomicInteger()
|
||||
val retry = retries.scheduleWithFixedDelay({
|
||||
retries.scheduleWithFixedDelay({
|
||||
try {
|
||||
if (!active()) throw java.util.concurrent.CancellationException()
|
||||
if (com.droiddeck.launcher.stores.SteamLiveShortcuts.sync(app, fresh) { true } ||
|
||||
!com.droiddeck.launcher.session.SessionState.running || attempts.incrementAndGet() >= 36) {
|
||||
!com.droiddeck.launcher.session.SessionState.running) {
|
||||
throw java.util.concurrent.CancellationException()
|
||||
}
|
||||
} catch (e: java.util.concurrent.CancellationException) {
|
||||
@@ -55,7 +57,6 @@ object AddedGamesPublisher {
|
||||
Log.w(TAG, "session shortcut retry: ${e.message}")
|
||||
}
|
||||
}, 5, 5, TimeUnit.SECONDS)
|
||||
retries.schedule({ retry.cancel(false) }, 180, TimeUnit.SECONDS)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "session refresh: ${e.message}")
|
||||
}
|
||||
|
||||
@@ -89,7 +89,13 @@ object AutoComponents {
|
||||
|
||||
private fun enqueue(context: Context, job: Job) {
|
||||
if (!queuedKeys.add(job.key)) {
|
||||
if (job.asked && jobs.removeIf { it.key == job.key && !it.asked }) jobs.add(job)
|
||||
synchronized(jobs) {
|
||||
val old = jobs.firstOrNull { it.key == job.key }
|
||||
if (old != null && ((job.asked && !old.asked) || (job.inSession && !old.inSession)) && jobs.remove(old)) {
|
||||
jobs.add(Job(old.game ?: job.game, old.component, old.asked || job.asked,
|
||||
if (job.asked && !old.asked) job.seq else old.seq, old.pics ?: job.pics, old.inSession || job.inSession))
|
||||
}
|
||||
}
|
||||
if (runNow && !draining) drain(context)
|
||||
return
|
||||
}
|
||||
@@ -105,10 +111,7 @@ object AutoComponents {
|
||||
|
||||
@VisibleForTesting internal var gameRunning: () -> Boolean = { gameProcessRunning() }
|
||||
|
||||
private fun gameProcessRunning(): Boolean = File("/proc").listFiles()?.any { p ->
|
||||
p.name.all(Char::isDigit) && runCatching { String(File(p, "cmdline").readBytes()).replace('\u0000', ' ') }.getOrNull()
|
||||
?.let { it.contains("SteamLaunch AppId=") || it.contains("proton waitforexitandrun") } == true
|
||||
} == true
|
||||
private fun gameProcessRunning(): Boolean = com.droiddeck.launcher.session.SteamGameProcess.running()
|
||||
|
||||
fun queueInSession(context: Context, game: Library.SteamGame) {
|
||||
if (appKey(game) == null) return
|
||||
@@ -185,18 +188,19 @@ object AutoComponents {
|
||||
val catalog = (catalogOf(context, false) ?: catalogOf(context, true))?.associateBy { it.name } ?: return
|
||||
val wanted = autoPicks(findings, catalog)
|
||||
val user = WinComponents.selection(context, key).user
|
||||
val before = WinComponents.selection(context, key).auto
|
||||
val installed = installedOf(context)
|
||||
val kept = LinkedHashMap<String, WinComponents.AutoReason>()
|
||||
val missing = ArrayList<String>()
|
||||
for ((id, reason) in wanted) {
|
||||
if (user[id] == false) { kept[id] = reason; continue }
|
||||
if (id in installed) { kept[id] = reason; continue }
|
||||
if (id in before) kept[id] = reason
|
||||
synchronized(waiting) { waiting.getOrPut(id) { ArrayList() }.let { if (it.none { g -> appKey(g) == key }) it.add(game) } }
|
||||
queueDownload(context, id, asked, inSession)
|
||||
missing.add(id)
|
||||
}
|
||||
if (inSession) Pending.set(context, key, missing)
|
||||
val before = WinComponents.selection(context, key).auto
|
||||
if (inSession) Pending.set(context, key, (Pending.ids(context, key).filter { it !in installed && it !in wanted } + missing).distinct())
|
||||
if (before.keys != kept.keys) {
|
||||
WinComponents.setAuto(context, key, kept)
|
||||
Log.i(TAG, "${game.name}: on by itself ${kept.keys.joinToString().ifEmpty { "(none)" }}")
|
||||
@@ -235,6 +239,16 @@ object AutoComponents {
|
||||
write(context, games)
|
||||
}
|
||||
|
||||
@Synchronized fun ids(context: Context, key: String): List<String> =
|
||||
read(context).optJSONArray(key)?.let { a -> (0 until a.length()).map { a.optString(it) } }.orEmpty()
|
||||
|
||||
@Synchronized fun add(context: Context, key: String, ids: List<String>) {
|
||||
val games = read(context)
|
||||
val have = games.optJSONArray(key)?.let { a -> (0 until a.length()).map { a.optString(it) } }.orEmpty()
|
||||
games.put(key, JSONArray((have + ids).distinct()))
|
||||
write(context, games)
|
||||
}
|
||||
|
||||
@Synchronized fun drop(context: Context, id: String) {
|
||||
val games = read(context)
|
||||
for (k in games.keys().asSequence().toList()) {
|
||||
@@ -257,14 +271,18 @@ object AutoComponents {
|
||||
|
||||
|
||||
private const val FINDINGS = "wincomp-findings.json"
|
||||
private const val DETECTORS = "d3"
|
||||
|
||||
internal fun signature(context: Context, game: Library.SteamGame): String {
|
||||
val folder = game.gameFiles
|
||||
val parts = listOfNotNull(
|
||||
DETECTORS,
|
||||
folder?.lastModified(),
|
||||
folder?.let { SteamRedists.manifest(it, game.appId)?.lastModified() },
|
||||
folder?.let { StoreGameSidecar.file(it).lastModified() },
|
||||
folder?.let { File(it, "fuel.json").lastModified() },
|
||||
folder?.listFiles { f -> f.name.lowercase().let { it.startsWith("installscript") && it.endsWith(".vdf") } }
|
||||
?.maxOfOrNull { it.lastModified() },
|
||||
SteamAppInfo.appinfoFile(context).lastModified(),
|
||||
folder?.let { SteamMatch.get(context, it.path) }?.let { "${it.appId}/${it.certainty}" },
|
||||
steamAppOf(context, game)?.let { SteamAppInfo.state(context, it) },
|
||||
@@ -313,6 +331,32 @@ object AutoComponents {
|
||||
|
||||
fun beforeLaunch(context: Context, game: Library.SteamGame) = queueGame(context, game, asked = false)
|
||||
|
||||
fun restoreMissing(context: Context): List<String> {
|
||||
val selections = WinComponents.selections(context)
|
||||
if (selections.isEmpty()) return emptyList()
|
||||
val catalog = (catalogOf(context, false) ?: catalogOf(context, true))?.associateBy { it.name } ?: return emptyList()
|
||||
val installed = installedOf(context)
|
||||
val lostFor = selections.mapValues { (_, selection) ->
|
||||
withParts(selection.effective.filter { WinComponents.validId(it) }, catalog).filter { it !in installed && it in catalog }
|
||||
}.filterValues { it.isNotEmpty() }
|
||||
if (lostFor.isEmpty()) return emptyList()
|
||||
val lost = lostFor.values.flatten().distinct()
|
||||
Log.i(TAG, "wincomp: reinstalling ${lost.joinToString()}, picked for games but missing from the runtime")
|
||||
lostFor.forEach { (key, ids) -> Pending.add(context, key, ids) }
|
||||
lost.forEach { queueDownload(context, it, asked = true, inSession = true) }
|
||||
return lost
|
||||
}
|
||||
|
||||
private fun withParts(ids: List<String>, catalog: Map<String, WinComponents.Component>): List<String> {
|
||||
val out = LinkedHashSet<String>()
|
||||
fun visit(id: String, depth: Int) {
|
||||
if (depth > 8 || !out.add(id)) return
|
||||
catalog[id]?.dependencies?.forEach { visit(it, depth + 1) }
|
||||
}
|
||||
ids.forEach { visit(it, 0) }
|
||||
return out.toList()
|
||||
}
|
||||
|
||||
fun refreshLater(context: Context, game: Library.SteamGame) = queueGame(context, game, asked = true)
|
||||
|
||||
fun sweep(context: Context, games: List<Library.SteamGame>) {
|
||||
|
||||
@@ -54,21 +54,6 @@ object DependencyDetector {
|
||||
"d3dx9", "d3dx11", "xact", "xact_x64", "xna31", "xna40", "physx", "oalinst", "XLiveRedist",
|
||||
)
|
||||
|
||||
fun detectForExe(exeFile: File): List<Recommendation> {
|
||||
val start = exeFile.absoluteFile.parentFile ?: return emptyList()
|
||||
var d: File? = start
|
||||
var depth = 0
|
||||
while (d != null && depth < 4) {
|
||||
val hasRedistContainer = try {
|
||||
d.listFiles()?.any { it.isDirectory && REDIST_DIR_RE.matches(it.name.lowercase(Locale.US)) } == true
|
||||
} catch (_: Throwable) { false }
|
||||
if (hasRedistContainer) return detect(d)
|
||||
d = d.parentFile
|
||||
depth++
|
||||
}
|
||||
return detect(start)
|
||||
}
|
||||
|
||||
fun detect(gameDir: File): List<Recommendation> {
|
||||
if (!gameDir.isDirectory) return emptyList()
|
||||
val hits = LinkedHashMap<String, Recommendation>()
|
||||
|
||||
Loaded 100 of 1553 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user