Compare commits

...
1139 Commits
Author SHA1 Message Date
dijunkun 006526389a [docs] update README for DeskHub and refresh desktop screenshots 2026-10-14 21:06:06 +08:00
dijunkun e76d2bf903 [ui] unify settings dialogs and improve announcement controls 2026-10-14 20:18:51 +08:00
kunkundi 2cf0d79543 [ui] refine desktop layouts and unify control styling 2026-10-14 19:29:08 +08:00
dijunkun 3043b5f110 [fix] follow the selected device cursor in DeskHub 2026-10-14 10:20:31 +08:00
dijunkun 5721222724 [fix] disable already added devices in DeskHub recent picker 2026-10-14 10:20:20 +08:00
dijunkun 3ee0d42494 [feat] add DeskHub group control 2026-10-14 10:20:05 +08:00
dijunkun 417ef7d58c [fix] disconnect remote sessions when closing DeskHub 2026-10-14 04:17:44 +08:00
dijunkun 0a6356085d [feat] show video latency in DeskHub network status 2026-10-14 04:17:38 +08:00
dijunkun 61ff9b2787 [feat] add resizable DeskHub focus previews 2026-10-14 04:17:31 +08:00
dijunkun 4855b2d3b6 [fix] preserve DeskHub previews and control during fullscreen changes 2026-10-14 04:17:23 +08:00
dijunkun 2ac197c2de [ui] streamline DeskHub toolbar layout and buttons 2026-10-14 04:17:17 +08:00
dijunkun b90359b08d [fix] sync DeskHub previews with tile size and unify tooltips 2026-10-14 02:58:08 +08:00
dijunkun 5199b2df11 [feat] add standalone DeskHub window and resizable device table 2026-10-14 02:37:06 +08:00
dijunkun fd86dba212 [fix] preserve remote cursors when macOS hides the pointer, refs #116 2026-10-13 21:49:06 +08:00
dijunkun 2a9887ab8a [fix] fix UPnP leaks and disable UPnP on iOS, refs #115 2026-10-13 20:42:57 +08:00
dijunkun 435feb419c [ui] simplify DeskHub controls and unify device status styling 2026-10-13 18:12:57 +08:00
dijunkun 4e394ca650 [ui] place DeskHub thumbnails above the focused desktop and compact labels 2026-10-13 16:11:27 +08:00
dijunkun 4dfd8c3005 [feat] allocate DeskHub video bandwidth automatically 2026-10-13 15:39:50 +08:00
dijunkun de16eb3b92 [refactor] use MiniRTC APIs for DeskHub media pause controls 2026-10-13 15:39:34 +08:00
dijunkun 3bd0676672 [feat] add DeskHub stream controls and network status 2026-10-13 10:45:48 +08:00
dijunkun 73b4d0f645 [feat] add DeskHub device wall and shared group actions 2026-10-12 03:08:04 +08:00
dijunkun 54dbd04a8d [fix] isolate background connections and password retries 2026-10-12 03:08:00 +08:00
dijunkun c8907a00f9 [feat] negotiate per-device preview and audio subscriptions 2026-10-12 03:07:10 +08:00
dijunkun c9e0078bfb [fix] persist successful connections without saved passwords 2026-10-12 03:06:33 +08:00
dijunkun e156ff5277 [fix] handle Markdown separators in release notes 2026-10-12 03:06:18 +08:00
dijunkun b44a203b19 [fix] update MiniRTC with DTLS retransmission recovery 2026-10-12 03:06:03 +08:00
Junkun Di 852710f428 Merge pull request #111 from lamugu/fix/recent-tooltip-layer
最近连接悬浮框不再压住连接弹窗的确认按钮
2026-10-11 17:22:58 +08:00
Junkun Di 2d51936ca8 Merge pull request #110 from lamugu/fix/dtls-handshake-timeout
[fix] time out stalled DTLS handshakes so reconnects can recover
2026-10-11 17:03:37 +08:00
dijunkun 3baedac6df [chore] update MiniRTC after removing deadline tests 2026-10-11 16:59:41 +08:00
dijunkun a667fe3b31 [fix] preserve current MiniRTC fixes with bounded DTLS recovery 2026-10-11 16:57:26 +08:00
dijunkun 05f6d3d90a [fix] show truthful signaling recovery state and pin safe retries 2026-10-11 15:35:11 +08:00
lamagu 0e7d175631 [feat] add manual signaling reconnect action 2026-10-11 15:35:11 +08:00
lamagu 52ca253980 [fix] delay signaling offline indication during reconnects 2026-10-11 15:35:11 +08:00
lamagu 1925e5ffcc [fix] time out stalled DTLS handshakes so reconnects can recover
Without a deadline a half-negotiated session stayed CONNECTED forever;
every further reconnect reused that dead state until the app restarted.
2026-10-10 21:03:14 +08:00
dijunkun 3aa0470510 [fix] restore password prompts and handle join authentication failures 2026-10-10 17:00:58 +08:00
dijunkun fbbb8c9e2c [fix] align Android versions with release tags, refs #107 2026-10-10 15:10:03 +08:00
lamagu 3750687e66 最近连接悬浮框不再压住连接弹窗的确认按钮
悬浮框当初为了盖住 ScrollView 给了 z:50,正好和模态层(z 39~51)同层,
鼠标停在列表上时黑框会盖住"对等连接已建立"的确认按钮。降到 z:20(模态层
之下、标题菜单之上),并在连接弹窗打开时直接不显示。
2026-10-10 14:01:44 +08:00
dijunkun 420e7a8cbb [ui] add release notes button to about dialog 2026-10-10 03:07:56 +08:00
dijunkun 58ca67fa25 [fix] restore automatic update dialog on startup 2026-10-10 03:00:54 +08:00
dijunkun 1f82bb39da [release] align iOS versions with desktop release tags 2026-10-10 01:56:26 +08:00
dijunkun 587a1ef07b [ci] fix Linux release artifact paths in containers 2026-10-10 01:46:49 +08:00
dijunkun 171de8b026 [feat] update MiniRTC for fast signaling reconnects 2026-10-10 00:54:40 +08:00
dijunkun 1dccbe42a3 [feat] keep mobile sessions connected in background 2026-10-10 00:29:07 +08:00
dijunkun be639eaf97 [fix] restore video latency without Metal presentation timestamps 2026-10-09 17:19:15 +08:00
kunkundi 055d8424a6 [fix] route unelevated Windows input through service 2026-10-09 16:33:51 +08:00
dijunkun 5a7e816fb7 [fix] restore remote input for elevated Windows apps 2026-10-09 16:02:27 +08:00
dijunkun a06ed5806a [fix] support self-hosted server URLs with paths 2026-10-09 15:34:12 +08:00
dijunkun d3ecbe2cc9 [feat] add compact mobile virtual mouse controls 2026-10-09 14:26:36 +08:00
dijunkun 41aed0984f [feat] complete mobile session controls and file transfer 2026-10-09 12:57:23 +08:00
kunkundi 080b9760e3 [fix] prevent duplicate cursors on Windows lock screen 2026-10-09 10:19:20 +08:00
dijunkun 4d65d12add [fix] apply settings without reconnecting signaling 2026-10-09 10:01:34 +08:00
dijunkun dacdbc5c45 [fix] close remote stream tabs after host disconnects 2026-10-09 09:25:39 +08:00
dijunkun 6d9230ff91 [ui] square off right corners of host status bar 2026-10-09 05:45:58 +08:00
dijunkun 1d47256cbc [ui] replace host session window with compact edge controls 2026-10-09 05:44:10 +08:00
dijunkun 9d613a5a13 [fix] update MiniRTC to detect silent controller disconnects 2026-10-09 04:03:09 +08:00
dijunkun 06e23007ed [fix] restore Windows remote keyboard shortcuts and input recovery 2026-10-09 03:43:14 +08:00
kunkundi 3cfe7cbb80 [fix] improve Windows secure desktop capture and input transitions 2026-10-09 00:05:37 +08:00
dijunkun 5004c91a6c [fix] restore minimum Xmake version to 3.1.1 2026-10-08 16:26:25 +08:00
kunkundi b0d6e8a520 [fix] restore automatic privacy screen after Windows unlock 2026-10-08 16:12:38 +08:00
dijunkun abcdb214f2 [ci] remove tests from build and release workflows 2026-10-08 15:55:38 +08:00
dijunkun f335f274ab [fix] lower minimum Xmake version to 3.0.0 2026-10-08 15:48:34 +08:00
kunkundi 5af7cc35e9 [fix] repair Windows privacy screen startup and capture recovery 2026-10-08 15:31:27 +08:00
dijunkun 9550731681 [fix] make Xfce optional with separate Linux deb packages, refs #106 2026-10-08 14:43:58 +08:00
dijunkun ec6fe8ea98 [fix] compare resolved user SIDs in Windows autostart tests 2026-10-06 11:25:36 +08:00
dijunkun ddefd14409 [fix] repair desktop CI and upgrade outdated Xmake 2026-10-06 10:51:52 +08:00
dijunkun 76eddc9f02 [feat] support adaptive tablet layouts on Android and iPad 2026-10-05 14:10:00 +08:00
dijunkun 9489ede03c [ui] simplify mobile settings descriptions 2026-10-04 22:06:51 +08:00
dijunkun 2f1c16c781 [fix] improve mobile notification and settings icons 2026-10-04 15:06:19 +08:00
dijunkun 050394135a [build] unify minimum Xmake version across platforms 2026-10-04 14:55:49 +08:00
dijunkun 7f7b91851e [feat] add Windows pre-login remote control and fix autostart 2026-10-04 12:49:26 +08:00
dijunkun b8f704abb9 [feat] add mobile update badges and iOS simulator support 2026-10-04 01:38:08 +08:00
dijunkun 115533cd62 [fix] report mobile client info after identity login 2026-10-03 10:44:30 +08:00
dijunkun 6e36163eb9 [ci] ignore cached Xmake toolchains in release source checks 2026-10-02 05:01:10 +08:00
dijunkun 9a1371879b [fix] align Android viewport zoom and pan with iOS 2026-10-02 04:53:44 +08:00
dijunkun 42498ac33d [ci] cache Android build environment and toolchains 2026-10-02 04:42:59 +08:00
dijunkun ca89f2ddc3 [fix] align Android card shadows and corner radii with iOS 2026-10-02 04:19:56 +08:00
dijunkun 638f829418 [fix] align Android mouse cursor appearance with iOS 2026-10-02 04:04:12 +08:00
dijunkun 0f683168cf [fix] align Android privacy consent prompts with iOS 2026-10-02 04:01:22 +08:00
dijunkun 256e28c786 [ci] allow release retries for existing source tags 2026-10-02 03:56:52 +08:00
dijunkun 758bfaa7a0 [ci] sign Android release APKs with a fixed publishing key 2026-10-02 03:44:47 +08:00
dijunkun ad343f2f8b [docs] align mobile release manifest documentation 2026-10-02 03:35:34 +08:00
dijunkun da7dcbe8c4 [ci] remove platforms from release version manifest 2026-10-02 03:30:10 +08:00
dijunkun 13f4116825 [ci] sync desktop and mobile release downloads to version.json 2026-10-02 03:14:10 +08:00
dijunkun bb3949a28e [release] prepare Android v1.6.0 2026-10-02 02:42:34 +08:00
dijunkun 49e90adb60 [feat] support standalone iOS and Android releases 2026-10-02 02:38:45 +08:00
dijunkun 3b5cbf0735 [feat] add Android device presence and align status icons with iOS 2026-10-02 02:27:32 +08:00
dijunkun ff706857bd [feat] enable Android MediaCodec decoding and simplify tests 2026-10-02 02:11:33 +08:00
dijunkun e76cfecac8 [refactor] extract standalone iOS build workflow 2026-10-01 23:31:51 +08:00
dijunkun b2f6bd3204 [feat] add Android build and release workflow 2026-10-01 23:27:57 +08:00
dijunkun b05a84198a [fix] disable Rust symbol stripping for Slint on macOS 2026-10-01 23:21:17 +08:00
dijunkun b9448392a7 [fix] stabilize iOS floating controls and hide applying status 2026-10-01 23:19:34 +08:00
dijunkun f08194f686 [feat] add native Android controller 2026-10-01 23:17:47 +08:00
dijunkun 149d20cbd1 [fix] add missing colon to remote preview setting label 2026-09-30 03:06:29 +08:00
dijunkun b935df917f [fix] refine connection status badges and indicator glow 2026-09-30 03:00:16 +08:00
dijunkun fab7edeff1 [fix] unify recent connection card rounded corners 2026-09-30 02:26:36 +08:00
dijunkun 85ca13aa75 [fix] center exclamation mark in update badge 2026-09-30 02:17:13 +08:00
dijunkun ff7bda6988 [fix] restore remote window dragging on X11 2026-09-30 00:54:01 +08:00
dijunkun 380a2a225c [fix] update minirtc for macOS 14 libyuv compatibility 2026-09-30 00:25:24 +08:00
dijunkun a535ded76d [fix] align announcement dialog styling with desktop UI 2026-09-30 00:13:36 +08:00
dijunkun fc67a1543c [fix] keep macOS main window titlebar white and opaque 2026-09-29 23:57:36 +08:00
dijunkun 31acb6b2f0 [feat] add iOS announcement inbox 2026-09-29 23:43:32 +08:00
dijunkun 2d1241c0a0 [feat] update minirtc with session recovery 2026-09-29 22:36:20 +08:00
dijunkun 0031c411e5 [feat] add announcement dismissal and links 2026-09-29 17:16:39 +08:00
dijunkun bc8dbcbf68 [fix] avoid X11 macro conflict in announcement requests 2026-09-29 14:01:46 +08:00
dijunkun 2d49024bd6 [feat] add announcement inbox with local read tracking 2026-09-29 13:04:54 +08:00
kunkundi 597c1dd2c9 [feat] add Wayland session notice with X11 guidance 2026-09-29 00:46:08 +08:00
dijunkun a83b6badd0 [feat] add desktop preview settings and platform placeholders 2026-09-29 00:22:29 +08:00
dijunkun 6a71a3173a [fix] stabilize iOS settings navigation and validate server edits 2026-09-29 00:18:43 +08:00
dijunkun c345c69e81 [feat] add host platform metadata and iOS platform placeholders 2026-09-28 23:49:55 +08:00
dijunkun f8535a797b [feat] expand iOS network status and refine privacy prompts 2026-09-28 23:26:03 +08:00
dijunkun 163506f81e [feat] add live video settings to iOS controls 2026-09-28 17:12:04 +08:00
dijunkun a4baca222c [fix] require iOS privacy consent and simplify settings 2026-09-28 16:53:43 +08:00
dijunkun 3992ea56db [fix] decouple iOS license checks from minirtc revisions 2026-09-28 14:16:47 +08:00
dijunkun 51d392ef48 [feat] add remote host version checks and update prompts 2026-09-28 13:54:39 +08:00
dijunkun f347fc2387 [feat] update minirtc with negotiated audio and data SRTP 2026-09-28 11:14:31 +08:00
dijunkun 0b28d1bc99 [fix] improve iOS privacy and App Store distribution compliance 2026-09-28 10:23:41 +08:00
dijunkun e894f4a763 [fix] avoid deadlocks in macOS screen capture callbacks 2026-09-27 20:53:18 +08:00
dijunkun e65a30e969 [fix] use VideoToolbox exclusively for iOS H.264 2026-09-27 20:53:12 +08:00
dijunkun 52f6f23f93 [fix] validate signal port range before formatting 2026-09-27 03:48:30 +08:00
dijunkun 3d2235ad4e [fix] statically link the Windows CRT in Slint 2026-09-27 03:35:06 +08:00
dijunkun 0b2eb5b106 [fix] bundle missing Slint runtime in Windows packages 2026-09-27 02:52:56 +08:00
dijunkun 94760b2a3c [fix] keep desktop UI readable under dark system themes, refs #103 2026-09-27 02:34:14 +08:00
dijunkun bbbcfb9d6f [fix] correct video latency measurement and smooth connection RTT 2026-09-26 03:15:47 +08:00
dijunkun 9ef64cc00f [fix] reduce release log verbosity and enforce single instance 2026-09-26 02:58:55 +08:00
dijunkun b8389a8aa0 [feat] add connection latency to network statistics 2026-09-26 02:04:18 +08:00
dijunkun 7ac8163931 [feat] add video latency to network statistics 2026-09-26 00:39:05 +08:00
dijunkun 704938a157 [feat] update minirtc with adaptive media FEC 2026-09-25 23:39:23 +08:00
dijunkun 572a018a72 [docs] refresh README guides and desktop and web screenshots 2026-09-25 03:26:57 +08:00
dijunkun 41cab6fa0b [fix] render toolbar off-state slashes correctly in software mode 2026-09-25 03:26:49 +08:00
dijunkun f73a57baaa [fix] restore missing includes for Linux and Windows builds 2026-09-25 02:20:02 +08:00
dijunkun e62d473b64 [perf] reduce desktop build dependencies and binary size 2026-09-25 01:47:20 +08:00
dijunkun 3c5b3f8e38 [fix] add missing JSON include for Windows service runtime 2026-09-25 00:51:08 +08:00
kunkundi 191ba26772 [feat] add Linux headless mode and interactive console 2026-09-25 00:29:24 +08:00
dijunkun c661319890 [feat] add background and manual update checks 2026-09-24 17:36:41 +08:00
dijunkun e0cd4c0567 [feat] add live remote video settings to the toolbar 2026-09-24 15:44:02 +08:00
dijunkun 88da1081ef [release] prepare v1.5.2 release notes 2026-09-24 11:15:58 +08:00
dijunkun b9efb5944c [fix] recover headless capture and use WGC for usbmmidd displays 2026-09-23 14:40:58 +08:00
dijunkun 5f26a0e239 [feat] add force relay connection option to settings 2026-09-22 11:03:51 +08:00
dijunkun 938ce01513 [fix] align password reset input style and limit it to six characters 2026-09-22 10:47:42 +08:00
dijunkun 2235d5cb62 [fix] place the cursor at the end of the password on retry 2026-09-22 10:39:27 +08:00
dijunkun 7e3e050edf [feat] add random password refresh to the main window 2026-09-22 10:33:28 +08:00
dijunkun b610a0ec7e [fix] anchor display menu to the toolbar when network stats are expanded 2026-09-22 10:19:16 +08:00
dijunkun 120368e4f7 [fix] align remote mouse coordinates with the displayed video area 2026-09-22 10:06:41 +08:00
dijunkun b34755c5ee [chore] bundle the usbmmidd_v2 virtual display driver with Windows packages 2026-09-21 01:10:31 +08:00
dijunkun 6387f2e555 [feat] add headless compatibility capture and usbmmidd virtual display plugging 2026-09-21 01:10:30 +08:00
dijunkun fb556a763d [fix] keep Windows privacy screen across display changes and validate covers 2026-09-21 01:10:30 +08:00
dijunkun 276385b816 [fix] keep Windows display slots and input mapping stable across hotplug 2026-09-21 01:09:12 +08:00
dijunkun 1a59a6ac2e [refactor] build host information in the wire library 2026-09-21 00:56:16 +08:00
dijunkun 485e347337 [fix] render CPU NV12 native frames rejected by the native renderer 2026-09-21 00:51:50 +08:00
dijunkun 89b39803e8 [fix] reuse stale sessions and stored passwords when reconnecting 2026-09-21 00:51:50 +08:00
dijunkun 4797af9260 [fix] correct Windows remote control session routing and key mapping 2026-09-19 03:59:35 +08:00
dijunkun 000b2e44e3 [fix] restore Windows cursor capture and web input control 2026-09-18 23:26:06 +08:00
dijunkun 26217f9d18 [fix] reset mouse input display when restoring initial capture display 2026-09-18 22:40:51 +08:00
dijunkun c2ea90c740 [chore] remove unused ImGui code and old release notes 2026-09-18 19:54:47 +08:00
dijunkun 0eadcf2855 [fix] diagnose and serialize Linux image dependency installation 2026-09-17 12:42:44 +08:00
dijunkun e263aab10d [fix] keep Windows privacy screen active when running as administrator 2026-09-17 09:55:34 +08:00
dijunkun 9abdfbf684 [release] prepare v1.5.1 release notes 2026-09-17 02:56:49 +08:00
dijunkun 31a0b86cee [fix] refine network stats layout and alignment 2026-09-17 02:45:35 +08:00
dijunkun fb34f42744 [fix] show encryption status and simplify network stats labels 2026-09-17 02:01:55 +08:00
dijunkun 4302ab291c [fix] overlay control bar tooltips on expanded network stats 2026-09-17 01:39:09 +08:00
dijunkun 4bf92c9e2c [fix] use reliable transport for mouse input and cursor state 2026-09-17 01:31:54 +08:00
dijunkun 28de4cf938 [fix] improve Windows taskbar icon clarity at small sizes 2026-09-16 23:19:12 +08:00
dijunkun ce7a3c178e [fix] correct WGC and GDI cursor capture and positioning 2026-09-16 23:03:36 +08:00
dijunkun d9116200fe [fix] restore remote cursors on Windows without a physical mouse 2026-09-16 22:20:36 +08:00
dijunkun 1d9242515a [fix] restore remote cursor visibility during Windows privacy screen 2026-09-16 20:27:59 +08:00
dijunkun ad62e60b9a [fix] restore shared capture on Windows secure desktop 2026-09-16 15:31:27 +08:00
dijunkun c4aca303c8 [fix] restore cursor visibility on Windows lock screen 2026-09-16 14:48:39 +08:00
dijunkun 57bb91dba3 [fix] prevent duplicate cursors during Windows window dragging 2026-09-16 13:51:35 +08:00
dijunkun 57cab3979e [fix] initialize logging before startup operations and update MiniRTC 2026-09-16 12:54:07 +08:00
dijunkun d8ccdbaa38 [fix] add capture delivery diagnostics 2026-09-16 12:54:06 +08:00
dijunkun f3e67d7d6e [fix] recognize macOS window resize cursors 2026-09-15 16:44:19 +08:00
dijunkun d648585891 [fix] restore Linux X11 remote keyboard capture 2026-09-15 16:23:42 +08:00
dijunkun e40c7fca98 [fix] disable privacy screen for legacy and web clients 2026-09-15 13:04:53 +08:00
dijunkun f6324416ec [fix] update MiniRTC legacy DTLS-SRTP compatibility 2026-09-15 12:20:00 +08:00
dijunkun 0977bd4195 [fix] update MiniRTC SRTP replay handling and bandwidth accounting 2026-09-15 03:38:29 +08:00
dijunkun f4e094cb35 [fix] update MiniRTC packet validation and SRTP buffering 2026-09-15 03:16:18 +08:00
dijunkun 1fe706c5fc [fix] update MiniRTC SRTP initialization 2026-09-15 03:03:47 +08:00
dijunkun 5fd928ddba [fix] update MiniRTC DTLS-SRTP key layout and profiles 2026-09-15 02:53:25 +08:00
dijunkun 977899b240 [feat] enable iOS punching and preserve connection errors 2026-09-15 02:37:30 +08:00
dijunkun 7fc1344756 [feat] enable enhanced UDP punching on desktop 2026-09-15 02:37:30 +08:00
dijunkun 73e3bf709d [perf] exclude optional libaom from default builds 2026-09-13 06:43:29 +08:00
dijunkun 6d90c28513 [perf] strip packaged Slint runtime symbols 2026-09-13 06:39:26 +08:00
dijunkun c944db6519 [perf] scope desktop build variant and version defines 2026-09-13 06:39:23 +08:00
dijunkun fc921c9ca1 [perf] avoid redundant iOS native archive rebuilds 2026-09-13 06:36:05 +08:00
dijunkun ba2afc982b [fix] repair macOS Intel OpenH264 CI build 2026-09-13 06:04:23 +08:00
dijunkun c6635fbdc8 [feat] add Linux X11 privacy screen and automatic recovery 2026-09-13 03:49:17 +08:00
dijunkun 3c403f6162 [fix] update minirtc for SIMD and frame rate fixes 2026-09-13 02:40:44 +08:00
dijunkun b54d32ef41 [fix] disable and uncheck hardware codec setting in unsupported builds 2026-09-13 01:40:44 +08:00
dijunkun 28e9626e0d [fix] preserve Windows privacy startup and server window 2026-09-13 01:23:30 +08:00
kunkundi a6e325f190 [feat] add macOS privacy screen and keep remote sessions running 2026-09-13 00:38:40 +08:00
dijunkun 23bf2ff8b8 [feat] add compact tooltips for all control bar buttons 2026-09-12 22:39:44 +08:00
dijunkun 56ebfdf8e7 [feat] add dedicated privacy screen controls 2026-09-12 22:24:09 +08:00
kunkundi 99ae0fc811 [fix] avoid false Windows privacy screen obstruction failures 2026-09-11 17:43:04 +08:00
dijunkun 9af7417c46 [feat] add Windows screen capture method setting 2026-09-11 16:41:16 +08:00
dijunkun ceb0a1654a [feat] add Windows privacy screen and prefer DXGI capture 2026-09-11 16:11:50 +08:00
dijunkun 4f200095f4 [fix] improve OpenGL video clarity when downscaling 2026-09-09 17:28:48 +08:00
dijunkun bd0a7aa2f6 [fix] prevent system audio capture hangs across desktop platforms 2026-09-09 11:34:47 +08:00
dijunkun b87ab025be [feat] use server-issued ICE configuration across clients 2026-09-08 17:07:16 +08:00
dijunkun 5b60695a52 [fix] restore Linux Dock icons in packaged builds 2026-09-08 15:03:32 +08:00
dijunkun 0002bcea74 [fix] hide macOS Dock icon when closing to the tray 2026-09-08 00:22:08 +08:00
dijunkun 58225de7ea [release] prepare v1.5.0 release notes and iOS version 2026-09-07 23:24:53 +08:00
dijunkun 5f37d0e753 [docs] update MiniRTC submodule documentation 2026-09-07 23:13:49 +08:00
dijunkun b518ea82e2 [docs] refresh README screenshots and platform guides 2026-09-07 22:53:30 +08:00
dijunkun abc8f907f3 [fix] restore iOS video after returning to the foreground 2026-09-07 21:31:08 +08:00
dijunkun d498d3f0ef [feat] show video resolution in the iOS floating status bar 2026-09-07 21:17:54 +08:00
dijunkun 55806d9e82 [fix] allow iOS relative mouse control outside the video area 2026-09-07 21:14:53 +08:00
dijunkun 2d3f1bb475 [fix] prevent iOS relative cursor jumps after movement 2026-09-07 21:11:27 +08:00
dijunkun 5d97d5a393 [fix] keep iOS floating controls clear of the Dynamic Island 2026-09-07 21:04:14 +08:00
dijunkun 19218a57f9 [fix] prevent stale device online status on iOS 2026-09-07 20:57:30 +08:00
dijunkun af729144fe [fix] prevent stale device online status 2026-09-07 20:02:19 +08:00
dijunkun d381cbaa9b [fix] show system tray icon on application startup 2026-09-07 17:42:25 +08:00
dijunkun 5aedb09c55 [feat] enable CUDA/OpenGL video rendering on Linux 2026-09-07 17:31:48 +08:00
dijunkun fe1178e26f [fix] move connection cleanup off the UI thread 2026-09-07 10:54:18 +08:00
dijunkun e0cd761bdc [fix] restore Windows lock-screen control and improve capture performance, fixes #98 2026-09-07 05:29:42 +08:00
dijunkun 2000654792 [fix] prevent Windows startup crashes from OpenGL failures, fixes #97 2026-09-07 04:20:54 +08:00
dijunkun 19800ef350 [fix] update MiniRTC iOS UPnP dependencies 2026-09-07 02:57:40 +08:00
dijunkun d10b65cc19 [fix] update MiniRTC relay to P2P upgrades 2026-09-07 02:30:26 +08:00
dijunkun 3a0179968c [fix] update MiniRTC ICE connectivity 2026-09-07 02:04:34 +08:00
dijunkun 55f389b834 [fix] update MiniRTC recovery tuning 2026-09-04 18:45:57 +08:00
dijunkun 8a58166c59 [fix] update MiniRtc video recovery timing 2026-09-04 17:35:14 +08:00
dijunkun aa2ee8ce7f [fix] update MiniRtc video recovery handling 2026-09-04 17:07:39 +08:00
dijunkun b150d46501 [fix] align MiniRtc media interfaces and timestamps 2026-09-04 15:45:26 +08:00
dijunkun 010064d5b7 [feat] optimize Windows native video encoding 2026-09-04 02:23:16 +08:00
dijunkun db3b26efe7 [feat] optimize macOS native video encoding 2026-09-04 02:06:44 +08:00
dijunkun cd1b53ee65 [chore] standardize source file headers 2026-09-04 02:06:36 +08:00
dijunkun b031a3953e [feat] optimize macOS native video rendering 2026-09-04 01:28:13 +08:00
dijunkun 3f537ae63c [feat] optimize Windows native video rendering 2026-09-03 18:01:09 +08:00
dijunkun e716346b26 [fix] stabilize frame rate priority adaptation 2026-09-02 11:05:13 +08:00
dijunkun b7e1adbec6 [feat] add video adaptation preference setting 2026-09-02 01:05:30 +08:00
dijunkun 58f2daa9c1 [fix] prioritize remote desktop resolution quality 2026-09-01 20:21:03 +08:00
dijunkun 8752e51921 [fix] build CI test targets separately 2026-09-01 08:33:59 +08:00
dijunkun a8cb0e21ce [fix] load desktop options on first configuration 2026-09-01 01:43:09 +08:00
dijunkun 90184f5251 [refactor] reorganize platform and wire sources 2026-09-01 01:29:30 +08:00
dijunkun fb0ab4f14e [fix] isolate iOS native build environment 2026-08-31 10:49:38 +08:00
dijunkun 0e3f3cec00 [fix] pin iOS CI xmake version 2026-08-31 10:39:36 +08:00
dijunkun 72af49eb80 [fix] use isolated iOS host build tools 2026-08-31 10:31:49 +08:00
dijunkun 36f05834b5 [fix] stabilize clean iOS dependency builds 2026-08-31 10:19:35 +08:00
dijunkun 1a190fbaf5 [fix] integrate iOS build workflow 2026-08-31 10:03:07 +08:00
dijunkun 1fe236da76 [fix] pin iOS CI package repository 2026-08-31 09:49:59 +08:00
dijunkun 3b989fb70d [fix] set up Python for iOS CI 2026-08-31 02:20:46 +08:00
dijunkun 7595ab8bd8 [feat] add native iOS client support 2026-08-31 02:14:27 +08:00
dijunkun 126f455681 [fix] synchronize Linux Wayland cursor shapes 2026-08-27 09:41:36 +08:00
dijunkun d6d0a548b2 [fix] rename remote cursor shape to avoid X11 macro conflict 2026-08-26 00:01:25 +08:00
dijunkun 74ac849efe Merge branch 'slint-client' of https://github.com/kunkundi/crossdesk into slint-client 2026-08-25 23:25:27 +08:00
dijunkun e2cd18dba4 [fix] detect macOS remote cursor shapes 2026-08-25 23:24:20 +08:00
dijunkun d2b1329eca [fix] restore Linux cursor state build compatibility 2026-08-25 22:59:45 +08:00
dijunkun 0653a95250 [fix] update minirtc NVDEC reconfigure handling 2026-08-25 22:52:41 +08:00
dijunkun bd73ef55f1 [feat] synchronize remote cursor state 2026-08-25 22:25:18 +08:00
dijunkun b854512c24 [feat] integrate Linux tray with desktop environment 2026-08-25 18:17:53 +08:00
dijunkun 4528caf0f4 [feat] refine tray and main window behavior 2026-08-25 17:14:45 +08:00
dijunkun f6e89725aa [fix] update minirtc NVENC fallback 2026-08-25 16:39:13 +08:00
dijunkun 62f79a8e44 [fix] update minirtc video adaptation 2026-08-25 16:18:55 +08:00
dijunkun 096bc68d35 [fix] prevent remote mouse input from popup menus 2026-08-25 12:43:30 +08:00
dijunkun 8ea4668305 [refactor] modularize Slint video rendering backends 2026-08-25 11:45:38 +08:00
dijunkun 21eec76008 [feat] add OpenGL NV12 underlay rendering for Slint on Linux 2026-08-25 10:26:05 +08:00
dijunkun 3e63675787 [fix] update minirtc NVDEC resolution handling 2026-08-25 05:28:39 +08:00
dijunkun 439f137764 [fix] update minirtc signal join sequencing 2026-08-25 04:40:37 +08:00
dijunkun f537147f54 [fix] update minirtc ICE state handling 2026-08-25 04:28:34 +08:00
dijunkun 2186ebd7eb [fix] restore Linux GCC build compatibility 2026-08-25 04:05:11 +08:00
dijunkun c11d48fc1f [fix] correct controlled-side status window behavior 2026-08-25 03:54:51 +08:00
dijunkun 1690fc92a3 [fix] prevent green tint during NV12 scaling 2026-08-25 03:37:02 +08:00
dijunkun 0d9d385d10 [feat] add OpenGL NV12 underlay rendering for Slint on Windows 2026-08-25 02:16:14 +08:00
dijunkun 20f8137df2 [fix] update minirtc video bitrate serialization 2026-08-25 01:34:03 +08:00
dijunkun 29aae747c6 [feat] add native Metal video rendering for Slint on macOS 2026-08-25 00:41:18 +08:00
dijunkun 3f93dc05aa [fix] eliminate Slint UI frame rate cap on macOS and Linux 2026-08-24 16:35:09 +08:00
dijunkun 05885ecd48 [fix] eliminate 30 fps cap in remote desktop rendering pipeline 2026-08-24 16:22:32 +08:00
dijunkun ee92c4ce5f [fix] update minirtc NVDEC teardown, fixes #95 2026-08-24 14:46:58 +08:00
dijunkun d94443330c [feat] prioritize frame rate for remote desktop 2026-08-24 14:00:40 +08:00
dijunkun df72204619 [fix] update minirtc OpenH264 bitrate handling 2026-08-24 10:33:56 +08:00
dijunkun 3678271577 [feat] report client version and platform 2026-08-24 09:46:51 +08:00
dijunkun 6b5535ab3d [fix] keep display stream IDs stable after monitor changes 2026-08-24 00:32:43 +08:00
dijunkun 078bd1e520 [fix] recover interrupted password changes 2026-08-23 21:59:20 +08:00
dijunkun 718705c352 [fix] prevent NVCodec unload crashes, fixes #95 2026-08-23 21:16:41 +08:00
dijunkun 1ca5852280 [fix] update minirtc reliable transmission 2026-08-23 19:04:43 +08:00
dijunkun 1eda6cc183 [fix] update minirtc feedback handling 2026-08-21 16:19:49 +08:00
dijunkun 8d37f8f5fb [fix] update minirtc CBR encoder configuration 2026-08-21 15:51:20 +08:00
dijunkun 05b8aa629e [fix] update minirtc for Windows build 2026-08-21 14:36:21 +08:00
dijunkun 2cbceba953 [fix] use screen content defaults for desktop streaming 2026-08-21 14:29:44 +08:00
dijunkun 89d3c8b53f [fix] prevent expired probe cluster reuse 2026-08-20 18:30:04 +08:00
dijunkun 51a4190e97 [fix] propagate encoder bitrate update failures 2026-08-20 18:20:02 +08:00
dijunkun 3737cd0dd5 [fix] align encoder and network bitrate limits 2026-08-20 18:05:45 +08:00
dijunkun 00957d6740 [fix] serialize pacer tasks and harden probing 2026-08-20 17:42:50 +08:00
dijunkun 6ec86322b2 [fix] abort probing when ICE becomes unavailable 2026-08-20 17:12:45 +08:00
dijunkun ecc131b5ee [fix] gate media-less probing by transport capability 2026-08-20 16:56:49 +08:00
dijunkun 1aa50e9ffa [fix] schedule pacer with high precision tasks 2026-08-20 16:22:01 +08:00
dijunkun d49f5bc520 [fix] handle task queue wakeups correctly 2026-08-20 14:45:18 +08:00
dijunkun 8818b9b8be [fix] ensure video bitrate updates reach encoders 2026-08-19 16:33:47 +08:00
dijunkun 3be283238c [fix] prevent screen capture without connected peers 2026-08-19 15:51:37 +08:00
dijunkun 5d0453fff3 [fix] prevent ICE callback self-join during teardown 2026-08-18 17:10:03 +08:00
dijunkun 8a9775a571 [fix] adapt VideoToolbox encoder resolution 2026-08-18 16:42:42 +08:00
dijunkun 7f4f1882ae [fix] sync signal status after server switch 2026-08-17 00:07:01 +08:00
dijunkun 23e24e3d47 [fix] prevent websocket reconnect during shutdown 2026-08-16 23:07:02 +08:00
dijunkun 7e1b9cb00e [fix] use -ld_classic only on macOS Intel 2026-08-16 22:34:58 +08:00
dijunkun 0c70acbdbf [fix] eliminate macOS build warnings 2026-08-16 22:18:30 +08:00
dijunkun fcbbb0f51c [fix] check log path before logger initialization 2026-08-16 22:16:26 +08:00
dijunkun f4be0700bf [fix] remove deprecated -ld_classic linker flag 2026-08-16 22:05:22 +08:00
dijunkun a45670b04d [fix] prevent invalid file descriptors during ICE teardown 2026-08-16 21:54:02 +08:00
dijunkun ff329cae81 [fix] use libsrtp v2.7.0 release tag 2026-08-16 17:51:08 +08:00
dijunkun 092664784e [fix] synchronize authenticated password changes 2026-08-16 16:57:36 +08:00
dijunkun 1709eb0efb [feat] use server-issued TURN credentials 2026-08-16 16:41:26 +08:00
dijunkun d27bb5d7a4 [docs] add CrossDesk privacy policy 2026-08-08 03:26:02 +08:00
dijunkun 62c8f0a38d [docs] improve README structure and signing policy 2026-08-08 03:00:13 +08:00
dijunkun 21eee5ccdc [ci] add SignPath Windows test signing 2026-08-08 01:50:47 +08:00
dijunkun e6c26511cd [fix] capture Windows keyboard input with Raw Input, refs #94 2026-08-03 17:38:46 +08:00
dijunkun c0b880e1eb [fix] pass Windows resource compiler to Slint build 2026-08-01 02:08:05 +08:00
dijunkun c10f1499f2 [fix] encode web audio before RTP packetization, fixes #93 2026-07-31 23:58:56 +08:00
dijunkun d7a9c26ff9 [fix] scale local ID text to fit 2026-07-31 23:57:09 +08:00
dijunkun f809ad173c [fix] restore Linux keyboard injection 2026-07-31 23:57:09 +08:00
dijunkun 34155d0266 [fix] let SDL select available Linux audio driver 2026-07-31 23:57:09 +08:00
dijunkun 9d544788b0 [fix] use custom titlebar only with X11 2026-07-31 23:57:08 +08:00
dijunkun dd16e65b68 [fix] stabilize third-party dependency builds 2026-07-31 23:57:08 +08:00
dijunkun 91eac61a90 [docs] use GCC 10 toolchain for Linux builds 2026-07-31 23:57:08 +08:00
dijunkun 941cc79af5 [fix] use xmake-managed CMake for builds 2026-07-31 23:57:08 +08:00
dijunkun 0d6ecfc730 [ci] build Linux releases on Ubuntu 20.04 for compatibility 2026-07-31 23:57:08 +08:00
dijunkun d32974dc18 ci: add Linux capture build dependencies 2026-07-28 17:58:39 +08:00
dijunkun efd8b7c0ff fix: let ICE drive connection failure state 2026-07-28 17:43:25 +08:00
dijunkun 383452ed3b ci: enable Wayland for Linux release builds 2026-07-28 17:25:49 +08:00
dijunkun 2570e57958 ci: use macOS 26 SDK for release artifacts 2026-07-28 16:29:32 +08:00
dijunkun eed90dad34 revert: keep macOS main window titlebar opaque 2026-07-28 16:29:32 +08:00
dijunkun c53ce2a581 fix: prevent video callback crash during transport teardown 2026-07-28 15:26:13 +08:00
dijunkun 708c39bb99 fix: keep macOS main window titlebar opaque 2026-07-28 14:42:06 +08:00
dijunkun cee249a25b fix: align DTLS handling with SRTP negotiation 2026-07-28 14:11:17 +08:00
dijunkun 7c3b13409c fix: restore remote keyboard control in Slint client, refs #91 2026-07-28 14:11:16 +08:00
dijunkun e3d15f8f9a fix: include platform header for Linux build 2026-07-27 10:18:48 +08:00
dijunkun a6e8038286 fix: block remote mouse input over control bar 2026-07-27 00:30:48 +08:00
dijunkun 765452e3c9 fix: close server window after controller disconnects 2026-07-27 00:22:33 +08:00
dijunkun 7cd0d6a351 fix: support SDL keyboard auto-repeat 2026-07-26 18:11:41 +08:00
dijunkun c01b52eac5 fix: refine settings dialog scrolling layout 2026-07-26 17:52:23 +08:00
dijunkun 737cf9b558 fix: prioritize online recent connections 2026-07-26 16:49:03 +08:00
dijunkun 6f5faa7111 fix: refine Wayland window behavior and titlebars 2026-07-23 20:40:13 +08:00
dijunkun 3a72e4849e Merge branch 'slint-client' of https://github.com/kunkundi/crossdesk into slint-client 2026-07-23 16:29:21 +08:00
dijunkun 43e44af730 fix: copy Slint runtime beside Windows binaries 2026-07-23 16:27:19 +08:00
dijunkun 97e592861c fix: remove main window maximize button 2026-07-23 16:27:11 +08:00
dijunkun 31b8983328 fix: gray out unavailable hardware codec setting 2026-07-23 11:11:08 +08:00
dijunkun 522f519d38 fix: include X11 headers for Wayland keyboard 2026-07-22 21:56:41 +08:00
dijunkun 37c4fe2e8a build: install Rust toolchain for Slint 2026-07-22 17:23:35 +08:00
dijunkun 2c20599800 fix: improve update notes display 2026-07-22 03:08:22 +08:00
dijunkun f5c4e2ba4a ci: add Linux build image workflow 2026-07-22 00:06:18 +08:00
dijunkun 59f77c2820 refactor: rebuild desktop client with Slint 2026-07-21 16:42:13 +08:00
dijunkun eeb6a2a1ae [refactor] organize GUI code by responsibility 2026-07-19 21:43:19 +08:00
dijunkun 1f86c43458 [fix] replace clipboard handling with SDL and optimize threading 2026-07-18 23:31:33 +08:00
dijunkun c487d3a62c [fix] refine recent connections overflow layout, refs #85 2026-07-18 22:03:36 +08:00
dijunkun aee5be5ee6 [feat] refine recent connection card controls and tooltip 2026-07-18 20:59:29 +08:00
dijunkun 6ff2783105 [feat] add TURN relay mode configuration 2026-07-18 20:22:36 +08:00
dijunkun d6d30b6842 [fix] fix Windows UAC prompt input by routing Consent UI through secure input helper 2026-07-06 17:47:50 +08:00
dijunkun 5db309243b [fix] fix stuck connecting state when remote device is offline, refs #57 2026-07-05 00:52:21 +08:00
dijunkun 0681f6540d [fix] fix persistent scrollbar in recent connections area when empty, refs #85 2026-06-26 17:29:04 +08:00
dijunkun d843901550 [fix] fix intermittent crash on incoming connection by guarding shared connection status state across threads 2026-06-26 17:21:09 +08:00
dijunkun b41630ebb4 [fix] fix blank connection status popup by handling Gathering state 2026-06-26 16:23:15 +08:00
dijunkun a815eecc73 [fix] fix close-issue workflow env indentation, pagination, and activity time base 2026-06-26 16:14:09 +08:00
dijunkun 7e0984fe9c [chore] refine online status indicator with gradient glow and remove status text 2026-06-26 16:09:21 +08:00
dijunkun 9c28cd2ab2 [fix] fix crash when switching monitors due to race condition and missing bounds checks in screen capturer 2026-06-26 14:44:30 +08:00
dijunkun 3c4000bdbb [fix] add missing Xft development dependency for Linux tray build 2026-06-25 00:35:25 +08:00
dijunkun d8e9fa5bba [feat] support minimizing to the system tray on Linux when closing 2026-06-23 17:11:42 +08:00
dijunkun e026491b9f [feat] support minimizing to the system tray on macOS when closing, refs #87 2026-06-23 17:11:42 +08:00
dijunkun 009699b375 [chore] optimize online status indicator icon 2026-06-22 16:52:51 +08:00
dijunkun 3677588a3d [fix] align recent connection name footer 2026-06-18 10:53:31 +08:00
dijunkun 3d280053a7 [feat] add custom names for recent connection devices and improve panel display 2026-06-17 17:48:17 +08:00
dijunkun fbde3f6a47 [fix] prevent remote keyboard keys from getting stuck 2026-06-15 17:28:34 +08:00
dijunkun 1c1a33fdce [fix] use evdev keycodes for Wayland keyboard input 2026-06-12 11:25:00 +08:00
kunkundi fea238722d [fix] fix macOS remote double-click and triple-click handling, refs #86 2026-06-05 00:25:08 +08:00
kunkundi 178d958c08 [fix] show self-hosted TLS certificate errors in status bar 2026-06-01 00:31:45 +08:00
kunkundi f9633f366b [fix] update MiniRTC: support loading macOS self-hosted TLS roots, refs #79 2026-06-01 00:31:27 +08:00
dijunkun 7a81f3e767 Merge branch 'file-transfer' of https://github.com/kunkundi/crossdesk into file-transfer 2026-05-31 23:21:42 +08:00
dijunkun bbbbbf7927 [fix] update MiniRTC: support loading Windows self-signed root certificates from intermediate stores, refs #79 2026-05-31 23:04:13 +08:00
dijunkun 5735f84008 [ci] include version alias in version.json for compatibility 2026-05-29 11:28:09 +08:00
kunkundi fe0cf42e5d [fix] use Linux system CA paths for update checks 2026-05-29 10:51:22 +08:00
kunkundi 04100584ce [fix] restore latest_version update metadata 2026-05-29 02:11:46 +08:00
kunkundi 9d3a422916 [fix] log update check failures and use macOS trust store 2026-05-29 02:00:13 +08:00
kunkundi 65d8284fb8 [ci] standardize hotfix package version ordering across platforms 2026-05-29 00:52:07 +08:00
kunkundi eea107db66 [chore] adjust settings window button vertical spacing 2026-05-28 23:36:25 +08:00
kunkundi 67812957db [ci] fix GitHub Actions Linux build version parsing 2026-05-28 23:30:42 +08:00
dijunkun 69d77e59cc [fix] make portable Windows Service setup optional, refs #84 2026-05-28 18:59:27 +08:00
dijunkun efcebfd82c [feat] add explicit hotfix patch version support 2026-05-28 15:22:35 +08:00
dijunkun 32345f93bf [fix] validate macOS input display state before injecting events 2026-05-28 04:22:14 +08:00
dijunkun 193e4bd5bf [fix] guard macOS speaker capture callbacks against invalid buffers 2026-05-28 04:22:07 +08:00
dijunkun 53edf3d57e [fix] harden macOS screen capture lifecycle against late callbacks 2026-05-28 04:21:59 +08:00
dijunkun 895e297771 [fix] initialize render runtime state to avoid invalid SDL handles 2026-05-28 04:21:52 +08:00
dijunkun 8f3959e6c6 [fix] reset stale macOS permissions during install 2026-05-28 01:34:02 +08:00
dijunkun 5ff6b601c7 [fix] improve macOS permission request flow 2026-05-28 01:33:50 +08:00
kunkundi 4895ac9c23 [fix] bundle Windows Service binaries in Windows portable package 2026-05-27 19:37:06 +08:00
kunkundi f121aa47f7 [feat] add portable Windows Service install prompt with one-click setup 2026-05-27 19:32:58 +08:00
dijunkun 00a8d59284 [chore] update README 2026-05-27 17:22:51 +08:00
dijunkun a30489e05b [feat] update MiniRTC: report relay traversal when either ICE candidate is relayed 2026-05-27 16:37:08 +08:00
dijunkun dfbeb3ed20 [fix] request stream keyframes when capture resumes 2026-05-27 16:05:42 +08:00
dijunkun 2eed1c974e [fix] recover Windows capture backends after secure desktop exit 2026-05-27 16:05:00 +08:00
dijunkun 63a79a90ac [fix] refine Windows credential UI state detection 2026-05-27 16:04:38 +08:00
dijunkun a61e74d97b [feat] add video keyframe request APIs 2026-05-27 15:58:32 +08:00
kunkundi 54438a4aa1 [feat] refine control bar display index label sizing and alignment 2026-05-27 10:24:53 +08:00
dijunkun 7682ad63e4 [feat] add localized tooltips for control bar buttons 2026-05-27 00:37:34 +08:00
dijunkun 06c53fdc9c [fix] handle SAS secure desktop transitions and restore desktop capture promptly, refs #77 2026-05-26 04:38:07 +08:00
dijunkun 665f4e684c [feat] improve Windows secure desktop capture and input handling, refs #77 2026-05-26 03:26:37 +08:00
dijunkun 52b894fe0e [feat] improve secure desktop capture by streaming latest frames through shared memory 2026-05-26 01:28:12 +08:00
kunkundi 82c0cbbad4 [fix] fix C++17 WGC build with newer MSVC coroutine deprecation 2026-05-25 17:37:26 +08:00
dijunkun ce004af379 [feat] add a control bar shortcut menu for sending Ctrl+Alt+Del and remote lock commands 2026-05-25 15:57:31 +08:00
dijunkun 15bd9e9fdc [fix] enable repeated SPS/PPS on NVENC keyframes, fixes #78 2026-05-25 02:16:19 +08:00
dijunkun 37aabeaf72 [fix] reset display popup hover state after monitor switching to restore mouse control, fixes #83 2026-05-25 01:28:17 +08:00
dijunkun 473737ac9b [fix] fix Windows input forwarding and allow debug builds to run without admin, fixes #82 2026-05-25 00:40:38 +08:00
dijunkun 1e29ec708f [fix] fix macOS remote keyboard modifier injection, fixes #81 2026-05-21 00:23:50 +08:00
dijunkun 515d517a99 [feat] add portable build storage mode, refs #80 2026-05-21 00:13:27 +08:00
dijunkun a3aedcb624 [fix] fix incorrect new version notification display issue 2026-05-07 15:45:21 +08:00
dijunkun 98b7c6c966 [fix] preserve Linux keypad navigation semantics and Windows scan-code metadata for remote keyboard input 2026-05-07 14:50:00 +08:00
dijunkun b1d956af2c [fix] fix left/right modifier key injection while preserving scan code metadata 2026-05-06 17:52:31 +08:00
dijunkun b7a031bb7f [fix] make PipeWire and portal dependencies optional 2026-04-28 17:08:34 +08:00
dijunkun 15cce07b6e Merge branch 'desktop-unlock-win' into file-transfer 2026-04-28 15:53:18 +08:00
dijunkun 1d5d6f5121 [fix] fix Debian package dependencies for PipeWire and ALSA t64 transitions 2026-04-28 11:14:25 +08:00
dijunkun 5f541f5c8b [feat] make CrossDesk service start and stop with the app 2026-04-28 10:25:16 +08:00
dijunkun 71bce08549 [fix] select the correct X11 pixel format conversion to prevent green-tinted screen capture on ubuntu 2026-04-27 17:57:11 +08:00
dijunkun 37b9badb2a [ci] fix NSIS uninstall function naming for service cleanup 2026-04-22 00:16:58 +08:00
dijunkun 4089e80fe8 [feat] register and remove CrossDeskService in the Windows installer 2026-04-21 23:23:11 +08:00
dijunkun 2be6e727ce [fix] use SDL keyboard capture on Wayland only 2026-04-21 17:37:19 +08:00
dijunkun d3b886c3f6 [fix] fix blocking issue on controlled-side during shutdown 2026-04-21 16:52:59 +08:00
dijunkun 97e48bfe71 [fix] fix Wayland keyboard capture by using SDL key events 2026-04-21 14:47:10 +08:00
dijunkun a8769dee06 Merge branch 'file-transfer' of https://github.com/kunkundi/crossdesk into file-transfer 2026-04-21 09:28:22 +08:00
dijunkun ffa94986d5 [feat] add Windows secure desktop remote unlock support for locked sessions, refs #77 2026-04-21 04:10:08 +08:00
dijunkun e4dfb61509 [fix] fix wayland cursor mapping 2026-04-20 18:09:13 +08:00
dijunkun d42b6e3261 [feat] update MiniRTC 2026-04-20 18:02:56 +08:00
dijunkun 855b15025c [fix] fix file transfer window interactions issue 2026-04-14 14:25:16 +08:00
dijunkun 3701b2c0d9 [chore] add acknowledgements 2026-04-14 11:03:06 +08:00
dijunkun ecbec4d301 [ci] use rolling cache keys for xmake dependency caches 2026-04-14 02:16:17 +08:00
dijunkun 21425c7132 [fix] fix system tray icon display issue 2026-04-14 01:54:03 +08:00
dijunkun 3e95a7ba29 [fix] fix startup failure caused by wgc_plugin working directory change 2026-04-14 01:53:20 +08:00
dijunkun c1394db285 [fix] fix missing wgc_plugin.dll in Windows packaging process, refs #76 2026-04-13 23:51:39 +08:00
dijunkun eee6c588bd [fix] fix X11 odd-size captures by aligning dimensions to even values 2026-03-24 00:07:44 +08:00
dijunkun eca68f6c7a [fix] fix keyboard input injection on Linux Wayland sessions 2026-03-23 23:14:05 +08:00
dijunkun f4e28d8774 [fix] fix mac-to-windows symbol key input 2026-03-23 22:30:58 +08:00
dijunkun 21b179e01c [fix] release pressed modifier keys when stream window loses focus 2026-03-23 21:33:01 +08:00
dijunkun 83cacf6f51 [fix] split mouse and keyboard from data channel and use reliable transimission 2026-03-23 21:14:07 +08:00
dijunkun 13c37f01b1 [fix] fix cross-platform key capture and mapping issues 2026-03-23 20:42:48 +08:00
dijunkun 511831ced3 [fix] fix Wayland reconnect black screen by keeping capturer warm and also fix Wayland mouse control 2026-03-23 05:18:56 +08:00
dijunkun 518e1afa58 [feat] add Linux screen capture fallback support for DRM and Wayland 2026-03-22 21:33:50 +08:00
dijunkun 43d03ac081 [fix] fix font path lookup for wqy/dejavu by switching from OpenType to TrueType 2026-03-22 00:39:19 +08:00
dijunkun f7f62c5fe0 [fix] update MiniRTC: refactor IceAgent to improve stability 2026-03-20 15:58:59 +08:00
dijunkun 2bbddbca6b [fix] fix Linux audio fallback when audio devices are unavaliable 2026-03-20 15:14:45 +08:00
dijunkun f0f8f27f4c [fix] fix blocking join() in Linux clipboard monitor thread during shutdown 2026-03-20 15:02:34 +08:00
dijunkun 262af263f2 [fix] move keyboard capturer to a background thread and use poll-based X11 event handling to avoid main-thread blocking 2026-03-20 14:56:40 +08:00
dijunkun 38b7775b1b [fix] fix restart/shutdown races in process monitor 2026-03-20 14:50:42 +08:00
dijunkun 56c0bca62f [chore] adjust hyperlink spacing and alignment 2026-03-20 14:47:33 +08:00
dijunkun 4b1b09fd5b [fix] fix Linux fonts: use opentype instead of truetype 2026-03-20 13:01:13 +08:00
dijunkun 1d6425bbf4 [fix] update MiniRTC: fix compiler warnings by adding missing override specifiers 2026-03-20 04:36:58 +08:00
dijunkun 5ec6552d25 [fix] fix macOS intel CI build failure caused by python 3.13 PGO mismatch 2026-03-20 03:50:19 +08:00
dijunkun 79e4a0790a [fix] fix issue where wgc_plugin was not compiled 2026-03-20 02:59:31 +08:00
dijunkun 1d3cac54ab [feat] load wgc from wgc_plugin.dll at runtime and drop direct'windowsapp' linking, refs #74 2026-03-20 01:36:36 +08:00
dijunkun 2f26334775 [feat] unify UI font loading across platforms and prefer PingFang on macOS 2026-03-19 21:58:14 +08:00
dijunkun 9270d528e3 [feat] update miniRTC: fix compiler warnings caused by missing override specifiers 2026-03-19 21:57:52 +08:00
dijunkun 91db3a7e34 [feat] add Russian language support 2026-03-19 20:04:30 +08:00
dijunkun d017561e54 [fix] fix typo ImGuiChildFlags_Border to ImGuiChildFlags_Borders 2026-03-19 16:16:51 +08:00
dijunkun 8e8a85bae3 [feat] upgrade actions/checkout and actions/cache to v5 for Node 24 compatibility 2026-03-19 15:03:58 +08:00
dijunkun bea89e9111 [feat] crossdesk server image supports Linux ARM64, refs #72 2026-03-19 10:06:57 +08:00
dijunkun 499ce0190a [fix] process mouse events only from the stream window 2026-03-11 16:00:29 +08:00
dijunkun 91bde91238 [feat] probe presence before connect and show warning if offline 2026-03-10 17:46:44 +08:00
dijunkun 3e31ba102d [fix] prevent sending connection requests to offline devices 2026-03-10 10:53:58 +08:00
dijunkun 263c5eefd3 [fix] fix update button lag in release mode by using non-blocking URL opener. 2026-03-10 10:39:05 +08:00
dijunkun b230b851e4 [fix] fix cannot close connection from Server Window when the peer is a web client 2026-03-10 00:39:00 +08:00
dijunkun ff32477ffe [fix] update MiniRTC: fix crash on disconnect 2026-03-10 00:35:33 +08:00
dijunkun c6c60decdb [fix] fix incorrect online status of recently connections 2026-03-09 22:52:05 +08:00
dijunkun 7505adeca8 [feat] update MiniRTC 2026-03-09 22:50:42 +08:00
dijunkun 754f1fba88 [feat] show 'Receiving screen' text before the remote frame arrives 2026-03-09 22:37:50 +08:00
dijunkun 8be46b870a [feat] add cancel button during connecting 2026-03-09 21:35:21 +08:00
dijunkun 81cb1d6c0b [fix] disable clipboard sharing when not in control mode 2026-03-05 17:46:27 +08:00
dijunkun 319416f1b7 [feat] update MiniRTC: optimize video quality and smoothness 2026-03-05 17:30:05 +08:00
dijunkun d679c6251b [feat] update MiniRTC 2026-03-04 10:46:21 +08:00
dijunkun a14baafda7 [fix] fix keyboard event loss due to start_keyboard_capturer_ flag improper setting, fixes #65 2026-03-04 10:36:39 +08:00
dijunkun cfdc7d3106 [fix] update MiniRTC: fix bandwidth degradation caused by ALR-triggered resolution downgrade during static frames 2026-03-03 10:58:38 +08:00
dijunkun 33d51b8ce5 [fix] reset to initial monitor on connection close via ResetToInitialMonitor to fix black screen 2026-03-02 15:42:44 +08:00
dijunkun b13dac2093 [feat] refine display of recent connections presence tooltip 2026-03-02 10:48:16 +08:00
dijunkun a605c95e5a [fix] fix window rounding inconsistency under different DPI scales 2026-03-02 10:38:06 +08:00
dijunkun 9a5553a636 [chore] update fonts 2026-03-02 10:17:06 +08:00
dijunkun ef02403da6 [fix] fix incorrect sizing of the online status indicator on high-DPI displays 2026-03-01 16:47:09 +08:00
dijunkun adfab363c1 [feat] add online presence check before connecting and show offline warning dialog 2026-03-01 16:29:11 +08:00
dijunkun 123d4cf595 [fix] update MiniRTC: fix the macOS hardware decode fail when the server using openH264 encode 2026-03-01 15:40:50 +08:00
dijunkun 19feb8ff49 [feat] show device online/offline status in recent connection tooltip 2026-02-28 17:25:41 +08:00
dijunkun 9223bf9d2d [feat] add online status indicators for recent connections 2026-02-28 17:06:44 +08:00
dijunkun 11b5f87841 [feat] update MiniRTC: add signaling send/receive API support 2026-02-28 17:04:47 +08:00
dijunkun cea59fb453 [feat] update MiniRTC 2026-02-27 17:53:51 +08:00
ZongYangBigPolo 3a179bf480 [feat] add macOS installer icon and optimize packaging script (#70) 2026-02-27 17:37:54 +08:00
dijunkun b9c53024f1 [feat] set video quality to HIGH and enable hardware codec by default 2026-02-27 17:24:04 +08:00
dijunkun 62b37ad698 [fix] resolve failures in the WGC→DXGI→GDI fallback chain 2026-02-27 16:33:57 +08:00
dijunkun de56cd5d3b [feat] update MiniRTC 2026-02-27 16:30:08 +08:00
dijunkun 8d9d78185a [fix] fix issue where client display list was incorrectly merged into the server display list 2026-02-27 16:27:37 +08:00
dijunkun b10a6512fe [feat] add Windows DXGI/GDI screen capture with WGC→DXGI→GDI fallback support 2026-02-27 13:55:41 +08:00
dijunkun a94da8802f [feat] make MainWindow and ServerWindow use rounded corners 2026-02-26 18:06:07 +08:00
dijunkun 4e6f82d00c [feat] restrict the dragging range of the ControlWindow 2026-02-26 15:55:04 +08:00
dijunkun 5e2ad99ec0 [feat] update MiniRTC to resolve color distortion in the OpenH264 decoder 2026-02-25 17:48:30 +08:00
dijunkun 8ab50ea362 [feat] add video resolution and conection mode in NetTrafficStats window 2026-02-25 15:33:17 +08:00
dijunkun 25e9958a69 Merge branch 'file-transfer' of https://github.com/kunkundi/crossdesk into file-transfer 2026-02-24 17:56:21 +08:00
dijunkun 410ea8b96b [feat] update MiniRTC 2026-02-24 17:56:02 +08:00
dijunkun e656664cad [chore] adjust file transfer save path button pos 2026-02-24 14:36:03 +08:00
dijunkun 0e6cee0961 [fix] fix stream window rendering height 2026-02-24 14:31:34 +08:00
dijunkun 42506b8c1d [ci] combine Linux amd64 and arm64 builds into a single job using matrix 2026-02-13 02:31:58 +08:00
dijunkun e35365d162 [feat] disable and style minimize_to_tray checkbox for non-Windows platforms 2026-02-13 02:29:52 +08:00
dijunkun bf1c0f796d [fix] fix Linux system certificate loading failure 2026-02-13 01:56:49 +08:00
dijunkun 547532b28c [fix] fix server window scaling issues on high-DPI displays 2026-02-13 01:26:10 +08:00
dijunkun a91e23abf6 [fix] fix raw pointer issues when closing connections 2026-02-13 01:12:21 +08:00
dijunkun 2b324f636b [fix] fix macOS system certificate loading failure 2026-02-12 22:49:54 +08:00
dijunkun 103b8372e4 [chore] rename packaged executable to CrossDesk.exe in NSIS and portable artifacts 2026-02-12 16:45:41 +08:00
dijunkun f7f1724bf1 [feat] optimize hyperlink opening by replacing system start with CreateProcessW-based URL launch on Winodws 2026-02-12 16:22:57 +08:00
dijunkun 5d70e11f17 [feat] support Windows x64 portable build, refs #54 2026-02-12 16:03:06 +08:00
dijunkun fb7ae90d46 [feat] add configurable file transfer save path in settings window, refs #63 2026-02-12 14:30:14 +08:00
dijunkun 957792a7a0 [feat] remove client certificate dependency 2026-02-11 16:23:43 +08:00
dijunkun 2e8ce6a2f0 [fix] reset default cert fingerprint if mismatch 2026-02-05 18:59:28 +08:00
dijunkun 9927a56b78 [feat] update MiniRTC 2026-02-05 18:05:35 +08:00
dijunkun db3da52f83 [feat] clear cached fingerprint when verification fails 2026-02-05 17:15:59 +08:00
dijunkun 19a7c6978a [feat] update MiniRTC to resolve websocket reconnection and post task issues 2026-01-28 09:45:19 +08:00
dijunkun b5e9ba03a1 [fix] double-buffer video frames and handle stream cleanup on main thread 2026-01-28 09:44:54 +08:00
dijunkun cb5f8b91ad [feat] update update-notification icon 2026-01-27 21:11:26 +08:00
dijunkun f627f60f1a [feat] use tooltips to display server-side file transfer status information 2026-01-27 17:50:21 +08:00
dijunkun e9fce5b8b8 [feat] display remote controller hostname instead of remote id 2026-01-26 22:52:58 +08:00
dijunkun a7820a79db [fix] fix incorrect peer_ usage in SendReliableDataFrame 2026-01-26 21:47:10 +08:00
dijunkun b6a52dbcd4 [feat] add support for displaying multiple controller info and file transfer to controllers 2026-01-26 17:47:31 +08:00
dijunkun 7bbd10a50c [fix] fix rendering issues in stream and server windows when the main window is minimized 2026-01-22 17:56:00 +08:00
dijunkun ee08b231db [fix] fix height when server window is restored from collapsed state 2026-01-20 23:58:43 +08:00
dijunkun 619e54dc0e [feat] add controller info and file transfer in server window 2026-01-20 21:22:20 +08:00
dijunkun 9b69596af1 [fix] fix stream window size recalculation 2026-01-20 01:33:27 +08:00
dijunkun f6e169c013 [feat] add support for server window resizing and dragging 2026-01-20 01:22:14 +08:00
dijunkun fd242d50c1 [feat] show server window in the bottom-right corner of the screen 2026-01-19 17:42:22 +08:00
dijunkun d6d8ecd6c5 [feat] add server window 2026-01-19 00:47:34 +08:00
dijunkun 669fac7f50 [feat] support drag-and-drop file sending, refs #63 2026-01-14 18:13:22 +08:00
dijunkun 92d670916e [fix] fix incorrect data send function used for control data 2026-01-13 18:13:54 +08:00
dijunkun 0155413c12 [feat] use reliable transmission to send control info 2026-01-12 17:28:19 +08:00
dijunkun 8468be6532 [fix] update MiniRTC 2026-01-12 17:27:49 +08:00
dijunkun 78c82f778a [chore] remove SetOnFileComplete() in class FileReceiver 2025-12-29 12:48:14 +08:00
dijunkun ab89a3d41a [fix] fix clipboard copy from remote device to controller 2025-12-29 12:46:19 +08:00
dijunkun 5f320af6e6 [fix] fix macOS clipboard monitoring compilation error using changeCount polling 2025-12-29 01:01:08 +08:00
dijunkun 17b7ba6b72 [feat] support clipboard sharing, refs #35 2025-12-29 00:53:14 +08:00
dijunkun c70ebdfe15 [fix] correct file send rate calculation by using data channel feedback 2025-12-29 00:53:14 +08:00
dijunkun a3e564f160 [feat] support multi-file transfer, refs #45 2025-12-29 00:52:58 +08:00
dijunkun eea37424c9 [feat] use receiver ack to calculate file transfer progress 2025-12-25 18:13:18 +08:00
dijunkun b322181853 [feat] add file transfer window to show file sending info 2025-12-24 18:12:50 +08:00
dijunkun 3ad66f5e0b [fix] fix file transfer 2025-12-24 01:45:59 +08:00
dijunkun 4035e0dd13 [feat] upgrade MiniRTC and expose source ID in data callbacks 2025-12-23 00:53:47 +08:00
dijunkun 832b820096 [fix] update MiniRTC to latest version and add logging for sent file size 2025-12-22 18:33:53 +08:00
dijunkun d337971de0 [feat] update MiniRTC api calling 2025-12-19 18:22:34 +08:00
dijunkun a967dc72d7 [feat] use SendReliableDataFrame() instead of SendDataFrame() 2025-12-19 01:46:16 +08:00
dijunkun 5066fcda48 [feat] implement file transfer module 2025-12-18 18:30:51 +08:00
dijunkun e7bdf42694 [feat] add file transfer button to control bar 2025-12-18 01:54:03 +08:00
dijunkun 875fea88ee [chore] adjust main window title font size 2025-12-18 01:32:38 +08:00
dijunkun b2654ea9db [feat] use fingerprint-based verification for both default and self-hosted servers 2025-12-10 03:46:03 +08:00
dijunkun 8f8e415262 [chore] update README 2025-12-10 03:38:05 +08:00
dijunkun 5ff624f7b2 [feat] use fingerprint-based verification for TLS connection 2025-12-10 03:28:28 +08:00
dijunkun e09243f1ec [chore] update README 2025-12-10 00:23:04 +08:00
dijunkun f5941c7eda [chore] update README 2025-12-10 00:20:26 +08:00
dijunkun 3c2ebe602e [fix] do not save password info into logs 2025-12-10 00:20:10 +08:00
dijunkun 2f64172ead [feat] use new client id and password if server switched 2025-12-10 00:09:49 +08:00
Junkun Di a83206a346 [ci] update issue templates 2025-12-09 17:50:57 +08:00
dijunkun 46e769976f [chore] update README 2025-12-09 00:36:00 +08:00
dijunkun 58c24b798e [chore] update README: refresh self-hosted server setup guide 2025-12-09 00:19:25 +08:00
dijunkun 5cc31e5ba3 [fix] fix self-hosted server configuration being reset when disabling self-hosted mode 2025-12-08 18:27:18 +08:00
dijunkun 74fe9bebf5 [fix] fix server settings window height 2025-12-08 17:42:02 +08:00
dijunkun 1f6a2182be [fix] resolve tab bar dragging issue 2025-12-06 18:46:04 +08:00
dijunkun 1a883f0d6c [fix] fix menu BeginPopup & EndPopup pairing 2025-12-05 17:53:17 +08:00
dijunkun a560b4ca70 [feat] make thumbnail save asynchronous to prevent UI blocking 2025-12-05 17:07:55 +08:00
dijunkun 46f45ed216 [fix] fix tab close button not working in stream window 2025-12-05 15:18:35 +08:00
dijunkun 5c23f1c5e8 [fix] correct tab bar scaling and layout 2025-12-05 15:17:07 +08:00
dijunkun 70ae02549f [fix] correct title bar display 2025-12-05 04:28:33 +08:00
dijunkun 68de995c64 [fix] correct hardware codec setting item display 2025-12-05 00:57:33 +08:00
dijunkun ed5ddb96fd [refactor] update notification window rendering for high-DPI scaling support 2025-12-04 19:00:37 +08:00
dijunkun 436dfafc2a [refactor] update about window rendering for high-DPI scaling support 2025-12-04 17:51:03 +08:00
dijunkun 5221b193e5 [refactor] update settings window rendering for high-DPI scaling support 2025-12-04 17:23:14 +08:00
dijunkun fafced23c2 [refactor] update stream window rendering for high-DPI scaling support 2025-12-04 02:11:06 +08:00
dijunkun 1e48b645ca [refactor] update recent connections panel rendering for high-DPI scaling support 2025-12-04 00:14:09 +08:00
dijunkun 49ed0200e7 [refactor] update connection status window rendering for high-DPI scaling support 2025-12-03 21:54:10 +08:00
dijunkun 24873afe64 [refactor] update remote peer panel rendering for high-DPI scaling support 2025-12-03 21:17:11 +08:00
dijunkun d21e1bd422 [refactor] update remote peer panel rendering for high-DPI scaling support 2025-12-03 17:36:19 +08:00
dijunkun be044c248b [refactor] update local peer panel rendering for high-DPI scaling support 2025-12-03 17:12:35 +08:00
dijunkun 49cbbc3363 [refactor] update status bar rendering for high-DPI scaling support 2025-12-03 12:45:01 +08:00
dijunkun 1e20cb806b [refactor] update title bar rendering for high-DPI scaling support 2025-12-03 04:20:49 +08:00
dijunkun 2e52818f6f fix: correct array deletion and improve state management in WGC screen capturer 2025-12-01 23:06:46 +08:00
dijunkun b50f386713 [fix] fix system_chinese_font_ usage to avoid dangling font pointer after closing stream window 2025-12-01 23:03:45 +08:00
dijunkun 280e011ae4 [fix] update RecentConnectionsWindow layout 2025-12-01 17:16:28 +08:00
dijunkun 8d09bf53c3 [fix] fix UpdateNotificationWindow dpi scaling 2025-12-01 13:52:39 +08:00
dijunkun 131b4f1795 [fix] resolve compilation errors on Linux 2025-12-01 13:07:36 +08:00
dijunkun 7d3ecf789d [fix] fix control bar dpi scaling 2025-12-01 11:30:35 +08:00
dijunkun 37797bf873 [fix] fix DPI scaling issues 2025-12-01 04:54:30 +08:00
dijunkun 91d42b6561 [fix] macOS: fix audio capture, refs #29 2025-11-30 17:13:02 +08:00
dijunkun feb9f2f460 [revert] revert to the pre-lock version 2025-11-28 11:44:08 +08:00
Junkun Di 9c1753c78c [chroe] add issue templates 2025-11-28 11:34:22 +08:00
dijunkun 7370ff5b30 [chore] add HelloGitHub badge 2025-11-28 11:10:41 +08:00
dijunkun f6eda34dbd [fix] fix dead lock during connecting 2025-11-28 10:02:57 +08:00
dijunkun 5d9a0a3ea5 [fix] fix dead lock during peer init 2025-11-28 09:32:21 +08:00
dijunkun 3d8249bffa [fix] use lock and null pointer checks to prevent crashes 2025-11-28 00:41:29 +08:00
dijunkun 82f32cbe8f [fix] fix incorrect peer reference in AddVideoStream call 2025-11-27 23:53:27 +08:00
dijunkun 56da2f99f3 [chore] update Linux log path configuration 2025-11-27 23:20:14 +08:00
dijunkun e6c72fe558 [feat] remove screen capture and accessibility permission when reinstall 2025-11-27 17:35:15 +08:00
dijunkun a964c6bbf5 [fix] call log after log initialzation, refs #36, #29 2025-11-27 16:09:08 +08:00
dijunkun 239da373d0 [feat] attempt to rejoin once per second 2025-11-27 04:20:29 +08:00
dijunkun 217cfb091d [feat] display version info on startup 2025-11-27 04:18:08 +08:00
dijunkun 3c3c7b9ae0 [fix] fix crash when screen recording permission is not granted on macOS, refs #29 2025-11-27 03:32:16 +08:00
dijunkun f14bdb7fe8 [feat] optimize UpdateNotificationWindow UI appearance 2025-11-27 03:07:55 +08:00
dijunkun c0a98f97c3 [feat] optimize RequestPermissionWindow UI appearance 2025-11-27 02:40:33 +08:00
dijunkun 0ab6686eb8 [feat] use DrawToggleSwitch to request permission 2025-11-26 23:32:04 +08:00
dijunkun 76b475450b [feat] request macOS system permissions by showing a prompt on startup 2025-11-26 18:18:40 +08:00
dijunkun 5d1e1b5667 [fix] remove permissions on uninstall and request permissions during installation for MacOS 2025-11-26 16:11:49 +08:00
dijunkun c3b8b1374a [chore] update README 2025-11-25 16:30:14 +08:00
dijunkun 7c940d6b15 [ci] fix tag error in update-version-json.yml 2025-11-25 03:30:28 +08:00
dijunkun 86501b05dd [feat] show notification window if there is a new version avaliable 2025-11-25 01:20:16 +08:00
dijunkun 01ebed9b37 [ci] upload release notes to version.json 2025-11-25 01:19:12 +08:00
dijunkun 2188adb1f1 [chore] disable CROSSDESK_DEBUG in keyboard and mouse control 2025-11-24 16:47:33 +08:00
dijunkun 51409e16c8 [chore] update README 2025-11-23 01:54:54 +08:00
dijunkun 6ca3b58ae2 [fix] update MiniRTC to resolve occasional crash during connection shutdown, refs #29 2025-11-23 01:47:48 +08:00
dijunkun 692e176e34 [ci] use github.sha instead of hashFiles for xmake dependency cache 2025-11-23 00:35:26 +08:00
dijunkun 4fb7acaa61 [feat] set enable TURN by default 2025-11-23 00:02:04 +08:00
dijunkun c0d6429a54 [fix] resolve missing mouse cursor display when web client connects to Linux devices, refs #30 2025-11-22 23:57:49 +08:00
dijunkun 07c7c7f179 [chore] update README 2025-11-21 02:40:51 +08:00
dijunkun c5ceeb0d80 [ci] use China timezone for build date in version number 2025-11-21 02:33:39 +08:00
dijunkun 5ce0a891df [fix] resolve failures in connection destruction 2025-11-21 01:50:08 +08:00
dijunkun f94ef49210 [fix] release keyboard hook after remote control disconnects, refs #23 2025-11-21 00:56:01 +08:00
dijunkun 5d0a4d1385 [fix] fix mouse wheel and touchpad swipe commands, refs #9, #23 2025-11-21 00:55:19 +08:00
dijunkun dd482cee60 [fix] use static linking of libffi in glib to avoid version conflicts, fixes #16 2025-11-20 17:20:15 +08:00
dijunkun e3c2edfb1c [fix] fix daemon not working on Linux 2025-11-20 15:35:37 +08:00
dijunkun f3901d09ea [feat] add tooltip for the daemon option in the settings windows 2025-11-20 14:47:54 +08:00
Junkun Di 2b12749477 [chore] update README_EN.md 2025-11-20 13:05:14 +08:00
Junkun Di 759488f675 [chore] update README.md 2025-11-20 13:04:32 +08:00
dijunkun 4bb4240a9e [chore] update README 2025-11-20 11:15:34 +08:00
dijunkun 1457247a6a [feat] add build option USE_CUDA to enable or disable CUDA-based hardware codec acceleration and USE_CUDA=false by default 2025-11-19 23:15:56 +08:00
dijunkun 97ab9bfca5 [feat] add daemon support with automatic restart on crash 2025-11-19 22:09:51 +08:00
dijunkun 4dd3c3e073 [fix] clean display names by removing non-alphanumeric characters 2025-11-18 17:05:51 +08:00
dijunkun 4ba4f17a6b [feat] capture cursor when connected to a web client 2025-11-18 16:24:28 +08:00
dijunkun f5d0291b5a [fix] fix crash when Unhook KeyboardCapturer on MacOS 2025-11-18 14:07:18 +08:00
dijunkun 1a64c1afef [feat] support auto-start on boot 2025-11-18 13:50:15 +08:00
dijunkun 18f4973d0a [fix] remove duplicate 'v' prefix in GitHub release name 2025-11-14 16:10:00 +08:00
dijunkun 37ede5861c [fix] update MiniRTC to fix crash when multiple peers join to remote server 2025-11-14 14:37:15 +08:00
dijunkun 497454ac51 [ci] remove 'v' prefix from Debian package version 2025-11-13 15:04:24 +08:00
dijunkun 4ebb7a6a4d [chore] update version format 2025-11-13 14:32:35 +08:00
dijunkun 7d1910df71 [ci] append build date to artifact names and write download URLs to version.json 2025-11-13 14:13:54 +08:00
dijunkun 52e70a26f3 [chore] update README 2025-11-13 00:06:14 +08:00
dijunkun adb6cee326 [fix] fix version check issue 2025-11-12 00:21:18 +08:00
dijunkun 941b5e5cdc [ci] update version.json when new tag pushed 2025-11-12 00:11:32 +08:00
dijunkun c602dea58f [chore] update README 2025-11-11 22:30:17 +08:00
dijunkun e9ced9fa4f [ci] switch macos-13 to macos-15-intel due to the macOS-13 based runner images are being deprecated 2025-11-11 22:28:35 +08:00
dijunkun 6ab5e7487f [chore] update README 2025-11-11 21:59:50 +08:00
dijunkun e3143f3e7a [feat] add automatic version check 2025-11-11 15:38:31 +08:00
dijunkun 538c17d182 [feat] disable AV1 encoding when connected to a Web client 2025-11-11 10:52:28 +08:00
dijunkun 2ad32ec2b4 [feat] add VideoQuality configuration option to limit maximum video resolution 2025-11-11 10:07:35 +08:00
dijunkun b28f1dca81 [feat] update MiniRTC module 2025-11-11 01:32:40 +08:00
dijunkun 6947f7e1c3 Merge branch 'self-hosted-server' into libdatachannel 2025-11-11 01:18:24 +08:00
dijunkun b1df10c0de [fix] fix frame rate and video quality settings not being applied correctly, fixes #24 2025-11-11 01:11:33 +08:00
dijunkun 3817b222fd Merge branch 'libdatachannel' of https://github.com/kunkundi/crossdesk into libdatachannel 2025-11-11 01:00:19 +08:00
dijunkun 910cc9b587 [fix] stop devices control and capture when client peer destroyed 2025-11-11 00:59:54 +08:00
dijunkun 2ee3e93afe [feat] do not control mouse in debug mode 2025-11-11 00:56:23 +08:00
dijunkun 8875c6a6a1 [feat] update MiniRTC module 2025-11-11 00:53:10 +08:00
dijunkun 28062f5574 [config] use 60 fps streaming by default 2025-11-10 17:03:14 +08:00
dijunkun 017af3eea4 [feat] support multiple web clients connecting simultaneously 2025-11-10 16:54:56 +08:00
dijunkun 78eb069cc8 [feat] enable speaker capturer by default 2025-11-10 15:02:21 +08:00
dijunkun 0d591f769d [feat] send control commands via JSON 2025-11-06 17:31:06 +08:00
dijunkun d4726355a7 [feat] update minirtc: support web streaming by using libdatachannel 2025-11-06 02:54:03 +08:00
dijunkun b78c9cf7d1 [feat] optimize Windows display device names 2025-11-05 20:36:04 +08:00
dijunkun b3132db785 [fix] resolve issue where configuration settings were not saved 2025-11-03 10:55:19 +08:00
dijunkun 43db021326 [feat] use CROSSDESK_DEBUG compile-time variable to control config file path 2025-10-31 17:31:50 +08:00
dijunkun 2c622bc76e [ci] update GitHub Actions to use macos-13 runner instead of macos-15 for Intel builds 2025-10-27 22:31:23 +08:00
dijunkun b790c7d08e [chore] update README 2025-10-27 22:11:30 +08:00
dijunkun 0ca90d2516 [chore] move minirtc into submodules 2025-10-27 21:36:11 +08:00
dijunkun 401bfe4483 [refactor] add namespace 'crossdesk' to codebase 2025-10-27 21:09:39 +08:00
dijunkun 3b34c26555 [feat] enable custom configuration of Coturn server port 2025-10-27 16:04:40 +08:00
dijunkun b668b3c936 [chore] update README 2025-10-27 13:42:49 +08:00
dijunkun cc19ec125a [ci] update close-issue.yml 2025-10-27 11:04:36 +08:00
dijunkun ffa77fdf44 Merge branch 'run-in-bg' into self-hosted-server 2025-10-27 10:41:16 +08:00
dijunkun 47cf806532 [ci] add permissions to close-issue.yml 2025-10-25 17:06:14 +08:00
dijunkun 911dce2e71 [feat] optimize certificate selection table 2025-10-24 17:39:25 +08:00
dijunkun 9f80d4f69d Merge branch 'self-hosted-server' into run-in-bg 2025-10-24 14:16:18 +08:00
dijunkun cba644f055 [fix] fix TURN server authentication credentials, fixes #8 2025-10-24 11:41:23 +08:00
dijunkun f733fe9e49 Merge branch 'self-hosted-server' into run-in-bg 2025-10-24 11:05:07 +08:00
dijunkun 27263fe1db [ci] fix permission issue in close inactive issues script by updating token usage 2025-10-24 10:57:11 +08:00
dijunkun 698bf72a6c Merge branch 'self-hosted-server' into run-in-bg 2025-10-24 10:05:54 +08:00
dijunkun 0bd27d0b17 [ci] use GITHUB_SHORT_SHA instead of build number in version 2025-10-24 02:09:50 +08:00
dijunkun ee5612da8b [ci] resolve compilation issue 2025-10-23 23:30:52 +08:00
dijunkun c7a2023c88 [ci] add build ID to version number 2025-10-23 23:18:44 +08:00
dijunkun c031a8c145 [fix] adjust settings window height for different platforms 2025-10-23 23:04:31 +08:00
dijunkun 0bf83f07ad [fix] correct version display in about window 2025-10-23 23:01:38 +08:00
dijunkun 3638b712bd [ci] update close-issue.yml 2025-10-23 21:20:10 +08:00
dijunkun b2ab940f20 [feat] use no close select table 2025-10-23 17:55:30 +08:00
dijunkun 17f9536476 [chore] update README 2025-10-23 10:37:45 +08:00
dijunkun 0ef51e3faf [feat] add FAQ.md 2025-10-23 10:33:39 +08:00
dijunkun cccf5dadb2 Merge branch 'run-in-bg' into self-hosted-server 2025-10-22 17:23:08 +08:00
dijunkun 2f0b0ffc22 [feat] add configuration to minimize to system tray when clicking the close button, refs #4 2025-10-22 17:21:47 +08:00
dijunkun c7411b59f1 [chore] update README 2025-10-21 22:51:21 +08:00
dijunkun 8222782522 [chore] update README 2025-10-21 20:54:37 +08:00
dijunkun 5fed09c1aa [ci] only close inactive issues with no labels 2025-10-21 11:37:25 +08:00
dijunkun 8e499772f9 [ci] add GitHub Actions workflow to automatically close inactive issues 2025-10-21 11:29:31 +08:00
dijunkun 0da812e7e9 [chore] update README 2025-10-20 21:51:09 +08:00
dijunkun 3d67b6e9d6 [chore] update README 2025-10-20 11:18:35 +08:00
dijunkun 506b2893c6 [chore] update README 2025-10-20 11:04:41 +08:00
Junkun Di 56abe9e690 [chore] update README 2025-10-20 09:55:59 +08:00
dijunkun ab13fa582d [chore] update README 2025-10-20 01:36:42 +08:00
dijunkun b9e8192eee [feat] support self-hosted service, fixes #3 2025-10-20 01:02:44 +08:00
dijunkun 5590aaeb1e [feat] add support for self-hosted server configuration 2025-10-18 23:41:10 +08:00
dijunkun adfe14809f [ci] switch GitHub-hosted runner from macos-13 to macos-15-intel 2025-10-18 02:40:32 +08:00
dijunkun a21dbc8d69 Merge branch 'sdl3' into self-hosted-server 2025-10-18 02:26:01 +08:00
dijunkun 9d45e497f4 [config] disable SRTP by default 2025-10-18 02:09:40 +08:00
dijunkun e5891eb397 [fix] use static pcre linking to ensure this lib runs on machines without pcre, fixes #5 2025-10-18 01:59:35 +08:00
dijunkun b9c70f54d3 [feat] add self-hosted server configuration section in settings window 2025-10-17 17:22:31 +08:00
dijunkun 9cd617d078 [feat] add self-hosted server config item in settings windows 2025-10-16 17:42:49 +08:00
dijunkun 92fd7f2e89 [feat] remove vc runtime from nsis script since using static linking 2025-10-16 16:03:27 +08:00
dijunkun b8535fff6f [feat] switch to /MT static runtime to improve Windows compatibility 2025-10-16 12:40:53 +08:00
dijunkun 09f34a81ad [feat] add screen capture frame rate option in settings window 2025-10-15 17:28:36 +08:00
dijunkun 22cc552e85 [feat] set screen capture frame rate to 60 fps 2025-10-15 15:42:42 +08:00
dijunkun 69a4dfcbb9 [feat] add fps display in net traffic stats window 2025-10-15 11:26:45 +08:00
dijunkun e1390ca2d3 [chore] update README 2025-10-13 17:12:45 +08:00
dijunkun dccdcd1b6f [chore] update README 2025-10-13 16:48:46 +08:00
dijunkun 276c3a336f [chore] update README 2025-10-13 10:52:01 +08:00
dijunkun 08518a9409 [fix] resolve mouse control issue due to SRTP packet parsing 2025-10-11 23:57:45 +08:00
dijunkun f6b0767bb1 [chore] update README 2025-10-11 23:57:26 +08:00
Junkun Di 641fc84430 [chore] pdate README_EN 2025-10-11 17:50:41 +08:00
Junkun Di 4ce79b87a3 [chore] update README 2025-10-11 17:49:49 +08:00
dijunkun 477b204913 [chore] update README 2025-10-11 17:47:24 +08:00
dijunkun 98f349ea2f [chore] update README 2025-10-11 16:32:42 +08:00
dijunkun 47b1e15eef [chore] update README 2025-10-10 09:16:29 +08:00
dijunkun 590bf50924 [chore] update README 2025-10-09 16:36:41 +08:00
dijunkun 097633e47d [chore] add license 2025-10-09 16:03:05 +08:00
Junkun Di d9ba88107d [chore] update README.md 2025-10-09 15:29:06 +08:00
Junkun Di f6a6ef0b08 [chore] update README_CN.md 2025-10-09 15:28:06 +08:00
Junkun Di a93ee0c19e [chore] update README.md 2025-10-09 15:25:21 +08:00
dijunkun 7e73553aca [fix] fix line drawing in recent connections window 2025-10-09 15:23:37 +08:00
Junkun Di b858bd78c0 [chore] update README.md 2025-10-09 15:07:58 +08:00
dijunkun f10947edf9 Merge branch 'sdl3' of https://github.com/kunkundi/crossdesk into sdl3 2025-10-09 14:47:47 +08:00
dijunkun c723cca8f9 [chore] update README.md 2025-10-09 14:47:33 +08:00
dijunkun b8f8b07ebe [chore] remove password regenerate button 2025-10-01 01:30:04 +08:00
dijunkun f9c6e5a6ef [fix] correct packet loss in network statistics 2025-09-30 17:54:41 +08:00
dijunkun 15bf8ef8c0 [feat] show shield icon when SRTP is enabled 2025-09-30 17:26:42 +08:00
dijunkun 6565816c0e [fix] fix log path issue on first launch 2025-09-30 15:50:22 +08:00
dijunkun 2aa67ccd57 [feat] prompt user to close crossdesk.exe during install/uninstall on Windows 2025-09-30 15:27:34 +08:00
dijunkun 88c75f94e4 [feat] add SRTP switch in settings 2025-09-24 20:27:56 +08:00
dijunkun aea9505c4c [chore] move nvidia-cuda-toolkit from Depends to Recommends in linux amd64 package 2025-09-12 17:42:47 +08:00
dijunkun 646740aab6 [chore] update minirtc to latest 2025-09-12 17:28:39 +08:00
dijunkun a458836e6e [fix] resolve certs file loading failure on linux 2025-09-12 16:29:20 +08:00
dijunkun 5fe7df8ea8 [feat] ensure VC++ Redistributable is installed on Windows during setup 2025-09-12 12:49:35 +08:00
dijunkun fda3743f86 [feat] add run-after-install option for windows installer 2025-09-11 16:23:48 +08:00
dijunkun 9e4170b3a8 [fix] update minirtc to fix startup crash on Windows when CUDA is not supported or not installed by using explicit dynamic loading 2025-09-11 01:01:46 +08:00
dijunkun 43338aaf02 [fix] release all peers when settings modified 2025-09-10 22:53:07 +08:00
dijunkun 274b7fcedc [test] test libstdc++ 2025-09-10 15:46:51 +08:00
dijunkun 01a5660984 [fix] set YUV colorspace to SDL_COLORSPACE_BT601_LIMITED to resolve NV12 texture display issue 2025-09-08 09:52:16 +08:00
dijunkun a45118f785 [feat] remove internet shortcut installing for windows script 2025-09-05 18:51:16 +08:00
dijunkun b6631c3db0 [fix] fix crash due to wrong linux keycode value 2025-09-04 16:31:03 +08:00
dijunkun 84d164c3af [fix] compelete linux x11 keycode map 2025-09-04 15:46:09 +08:00
dijunkun 32815ce25a [feat] use crossdesk/ubuntu20.04:latest as build image to support more users 2025-09-03 18:40:29 +08:00
dijunkun 7c2b3f8c8d [fix] use x64 and amd64 instead of x86_64 in artifact name 2025-09-03 17:10:17 +08:00
dijunkun 309d9d6ed6 [fix] fix linux x86_64 package script no Size information issue 2025-09-03 15:55:16 +08:00
dijunkun 91ab21c5f2 [fix] fix function keys release handling issue 2025-09-02 18:58:54 +08:00
dijunkun b8369c4f0a [feat] remove redundant ImGui ConfigFlags to improve performance 2025-09-02 17:10:55 +08:00
dijunkun a068a32303 [fix] remove SDL3 input audio stream recording 2025-09-02 16:53:55 +08:00
dijunkun b6fe0da581 [feat] use SDL_WaitEventTimeout to refresh frames and reduce CPU usage 2025-09-02 16:45:04 +08:00
dijunkun 6e7e2697b5 [fix] fix dpi scaling 2025-09-02 15:48:05 +08:00
dijunkun 22084072b0 [feat] update icon files 2025-09-01 18:12:47 +08:00
dijunkun d5457373f4 [feat] use squircle icons 2025-08-29 17:53:47 +08:00
dijunkun 01ae299cde [feat] delete old files 2025-08-29 10:16:26 +08:00
dijunkun fbcd4c21cf [feat] use rsync instead of appleboy/scp-action to update artifacts 2025-08-29 09:56:20 +08:00
dijunkun cf9dc0a9a5 [fix] fix artifacts generation path on linux in github actions scripts 2025-08-28 23:29:18 +08:00
dijunkun 1b4f41af46 [feat] upload artifacts to chinese server for download 2025-08-28 19:16:11 +08:00
dijunkun 7f3425519b [fix] fix linux github actions building 2025-08-28 19:14:25 +08:00
dijunkun 434c92deb6 [fix] add crossdesk_128x128.png to icons 2025-08-28 18:37:26 +08:00
dijunkun e5eae1feb4 [feat] update icons 2025-08-28 18:23:02 +08:00
dijunkun 37e37d7d20 [fix] mv deb to /tmp in install process 2025-08-28 17:48:09 +08:00
dijunkun 062568dc96 [fix] fix SDL3 texture display error 2025-08-26 16:26:06 +08:00
dijunkun d60fdf9050 [feat] update SDL2 to SDL3 2025-08-25 19:46:30 +08:00
dijunkun 9912a88a13 [feat] github actions support linux aarch64 platform 2025-08-22 18:43:07 +08:00
dijunkun 8a8f2cd5d7 [feat] update minirtc to support linux aarch64 platform 2025-08-21 20:16:55 +08:00
dijunkun e77e16d9c2 [fix] Add validity check for props 2025-08-20 16:42:31 +08:00
dijunkun 1616d0ec33 [fix] Add validity check for props 2025-08-20 16:37:29 +08:00
dijunkun 374453775f [fix] fix connection status window gui display 2025-08-19 17:47:09 +08:00
dijunkun 6f8fd6a030 [fix] fix crash when transmission id does not exist 2025-08-19 16:33:29 +08:00
dijunkun c7166975b3 [fix] fix version number replace for pages 2025-08-15 20:52:42 +08:00
dijunkun 2ae5e5a969 [feat] do not generate dmg for macOS 2025-08-15 20:34:27 +08:00
dijunkun 85cdc995c5 [fix] fix artifacts name with version number 2025-08-15 20:07:18 +08:00
dijunkun b051c8a059 [fix] fix artifacts name with version number 2025-08-15 19:55:03 +08:00
dijunkun 508b7dc7a1 [feat] add script to update the version number in github pages 2025-08-15 19:41:04 +08:00
dijunkun f203566b81 [feat] use dynamic version number 2025-08-15 19:35:16 +08:00
dijunkun 8360c1725f [feat] add release scripts 2025-08-15 15:41:10 +08:00
dijunkun 3b00fdef71 [fix] fix github actions scripts 2025-08-14 16:58:29 +08:00
dijunkun f2664daaec [feat] add github actions scripts 2025-08-10 00:03:13 +08:00
dijunkun 1a1bbe3e4d [fix] fix cache file and cert file read 2025-08-09 23:59:53 +08:00
dijunkun 4c898c5f07 [fix] save log files into XDG_CACHE_HOME/CrossDesk/logs for Linux platform 2025-07-25 18:11:40 +08:00
dijunkun 5d704edbc8 [fix] use std::filesystem::create_directories instead of std::filesystem::create_directory to create folder 2025-07-24 15:52:52 +08:00
dijunkun b23038bac6 [feat] update signal server domain 2025-07-23 17:30:30 +08:00
dijunkun 147b9b2ddc [fix] fix thumbnail order by using std::vector instead of std::unordered_map 2025-07-23 16:38:29 +08:00
dijunkun 1327b995f2 [fix] fix compile error on MacOSX 2025-07-23 11:31:32 +08:00
dijunkun e8d7ec8daf [feat] save log and cache files into user folder 2025-07-22 18:55:12 +08:00
dijunkun 3bf68a396f [feat] add PathManager class in order to manage config/log/cache file path 2025-07-16 18:22:33 +08:00
kunkundi 29077fad5e Merge branch 'multi-stream' of https://github.com/kunkundi/crossdesk into multi-stream 2025-07-16 17:10:18 +08:00
kunkundi 69367bdadf [fix] fix same memory leak issue 2025-07-16 17:09:51 +08:00
dijunkun f650b5a6ef [feat] use unordered map to store recent connection info so that the most recent connections are shown at the front 2025-07-15 17:34:25 +08:00
kunkundi 75021b74ef [fix] use temp frame to store the audio frame that will be sent 2025-07-15 17:18:00 +08:00
dijunkun 205421621b [fix] fix local id when using as client 2025-07-15 16:35:05 +08:00
dijunkun 4bb5607702 [fix] fix restart audio capturer error on MacOSX 2025-07-15 16:05:57 +08:00
kunkundi 78c54136e2 [fix] fix crash when Stop() called in SpeakerCapturerLinux 2025-07-15 15:38:58 +08:00
kunkundi 8fe8f4fd7e [feat] audio capture supported on Linux 2025-07-11 17:17:05 +08:00
dijunkun c13e2613b6 [feat] audio capture supported on MacOSX 2025-07-02 19:25:21 +08:00
dijunkun e52ec6cde2 [fix] use domain name instead of ip address to enable tls connection 2025-07-01 17:38:24 +08:00
dijunkun ad6a24b230 [feat] add tls cert file path in configure parameters 2025-07-01 13:55:41 +08:00
dijunkun ad60815d83 [fix] fix thumbnails deletion 2025-07-01 11:13:24 +08:00
dijunkun c47a90bf9c [feat] update project name 2025-06-25 17:33:54 +08:00
dijunkun 3901e26c37 [fix] fix thumbnail filename which stores remote id, remote host name and remote password 2025-06-20 18:42:29 +08:00
dijunkun 41c27139a0 [feat] password modification supported 2025-06-20 17:50:04 +08:00
dijunkun a31ca21ef4 [feat] receive id and password when login to server in the first time 2025-06-20 00:57:56 +08:00
dijunkun 57939ccd00 [feat] update submodule info 2025-06-18 00:06:47 +08:00
dijunkun fc14f7b9c6 [fix] register minirtc as submodule properly 2025-06-17 23:29:02 +08:00
dijunkun cfcf6dd9cb [feat] replace submodule projectx with minirtc at new path 2025-06-17 17:11:43 +08:00
dijunkun 854c3a72c7 [feat] modify project name to DeskPort 2025-06-17 14:24:41 +08:00
dijunkun 8004d25ca3 [feat] limit screen capturing to 30 fps 2025-06-07 02:46:51 +08:00
dijunkun b04dfd188a [fix] fix SCStream stop error 2025-06-03 10:44:52 +08:00
dijunkun 383ace2493 [fix] only receive remote host info once 2025-06-03 10:33:32 +08:00
dijunkun 094204361c [feat] enable screen switch on Linux platform 2025-05-29 18:09:34 +08:00
dijunkun d72c6d9df7 [feat] enable mouse dragging for MacOSx 2025-05-29 17:05:56 +08:00
dijunkun 05d73ebe9a [feat] add notification text in stream windows when connection failed/disconnected/closed 2025-05-29 16:51:18 +08:00
dijunkun a8b5e934b8 [feat] implementation for ScreenCapturerSck::Destroy() and ScreenCapturerSck::Stop() 2025-05-29 15:49:42 +08:00
dijunkun 920677a433 [fix] use black to fill the blank areas around the thumbnail 2025-05-29 15:02:43 +08:00
dijunkun b86d3d42ee [fix] fix color space for thumbnail 2025-05-29 14:17:33 +08:00
dijunkun 818dab764f [fix] do not recreate screen capturer when reload configuration file 2025-05-28 19:15:02 +08:00
dijunkun 7ea26854af [fix] fix strncpy error 2025-05-28 17:25:39 +08:00
dijunkun f34b55b88a [fix] do not need to call SDL_CloseAudioDevice() before SDL_Quit() 2025-05-28 16:02:37 +08:00
dijunkun 67168f7735 [fix] destroy screen capturer only when clean up 2025-05-27 10:17:25 +08:00
dijunkun 6e69c37056 [feat] use display name as video stream id 2025-05-26 15:29:46 +08:00
dijunkun 8f5dd21e75 [fix] remove data length check in OnReceiveDataBufferCb 2025-05-22 18:09:23 +08:00
dijunkun e2dfeb1186 [fix] fix RemoteAction read from received data 2025-05-22 17:18:06 +08:00
dijunkun 96c7d3174b [feat] improve the performance of ScreenCapturerSck 2025-05-22 17:17:15 +08:00
dijunkun 97f6c18296 [feat] update ScreenCapturerSck 2025-05-20 19:11:17 +08:00
dijunkun 9138ca771f [fix] do not send mouse click event when cursor is on control bar and display selectable 2025-05-16 19:06:25 +08:00
dijunkun abc6b17a3b [fix] display index shown in control bar should start from 1 2025-05-16 18:51:57 +08:00
dijunkun 8e0524bf60 [feat] display switch supported on MacOSx platform 2025-05-16 18:49:20 +08:00
dijunkun 6ebf583a13 [fix] fix compile error on MacOSx 2025-05-15 19:54:17 +08:00
dijunkun eca4f614c8 [feat] cursor mapping in different displays supported 2025-05-15 19:47:08 +08:00
dijunkun 11358e0b60 [feat] enable mouse control for multi-display 2025-05-15 18:37:59 +08:00
dijunkun 0a1014dded [fix] use serialize and deserialize function to process RemoteAction::HostInfo 2025-05-15 17:52:40 +08:00
dijunkun a6beb48b1f [feat] display switch supported on Windows platform 2025-05-15 16:37:03 +08:00
dijunkun 5eff530ab9 [fix] fix ScreenCapturerWgc crash during clean up 2025-05-15 15:27:44 +08:00
dijunkun e6e237279c [feat] update rtc module 2025-05-13 21:47:05 +08:00
dijunkun 6fe46f6181 [feat] add a=m lines in sdp for multi-stream 2025-05-12 22:09:08 +08:00
dijunkun 9b5023645c [feat] display selection supported on Windows platform 2025-05-09 22:30:56 +08:00
dijunkun c2da4ebcb7 [feat] add remote display selection button in control bar 2025-05-09 17:23:27 +08:00
dijunkun dc05f2405f [feat] add display selection method for Windows platform 2025-05-08 17:40:14 +08:00
dijunkun e2a469ed65 [feat] remove dependence on ffmpeg for MacOSx 2025-05-08 11:33:04 +08:00
dijunkun e89d385f99 [fix] remove redundant link flags on Linux platform 2025-05-08 11:07:04 +08:00
dijunkun 0a61dcc2be [fix] update keyboard converter 2025-05-07 19:47:09 +08:00
dijunkun 250fd49406 [feat] mouse/keyboard control and screen capture supported by using X11 on Linux platform 2025-05-07 19:37:41 +08:00
dijunkun 93bd5b2660 [fix] fix control bar display error in fullscreen mode when multiple connections established 2025-05-06 19:49:08 +08:00
dijunkun d05ff9f905 [fix] update rtc module 2025-05-06 18:58:52 +08:00
dijunkun f3451a5fa1 [fix] fix compile error on Linux 2025-05-06 18:39:30 +08:00
dijunkun a9084ba98d [fix] fix control bar layout and position in stream window 2025-04-30 18:18:55 +08:00
dijunkun 893051f9b3 [fix] fix crash due to invalid iterator 2025-04-30 15:16:32 +08:00
dijunkun dfbd4317b7 [feat] use tab bar to manage stream windows 2025-04-29 22:16:10 +08:00
dijunkun 532ad0eb51 [feat] support multi-stream and enable stream windows docking 2025-04-28 20:49:11 +08:00
dijunkun 184983d857 [fix] fix FindThumbnailPath() 2025-04-27 18:46:45 +08:00
dijunkun c33e4bbe0e [fix] use relative percentage-based mouse mapping instead of absolute positions 2025-04-27 14:02:20 +08:00
dijunkun 4b9e86c424 [fix] fix recent connection deletion 2025-04-27 10:53:44 +08:00
dijunkun f7f8ddd925 [fix] fix log error 2025-04-18 15:39:31 +08:00
dijunkun 188b1758f2 [feat] remove screen resolution info in HostInfo 2025-04-17 16:58:45 +08:00
dijunkun 9705374b9a [feat] save thumbnail as black picture if have not received a full frame 2025-04-16 16:47:30 +08:00
dijunkun 22aed6ea53 [fix] send host info when connected 2025-04-16 16:13:54 +08:00
dijunkun 44c5fde086 [fix] send host info when connected 2025-04-16 15:36:25 +08:00
dijunkun 2cd5a9dd76 [fix] do not send click event if cursor clicks the button which is on control bar 2025-04-16 14:47:44 +08:00
dijunkun fa73447f88 [fix] fix mouse wheel mapping on Windows 2025-04-16 14:33:11 +08:00
dijunkun 536fe17055 [fix] fix wheel event grabbing 2025-04-15 17:32:23 +08:00
dijunkun 662cbbc3cc [feat] mouse middle button and wheel supported 2025-04-15 14:26:34 +08:00
dijunkun 69a8503ee1 [fix] need to DestroyPeer if NoSuchTransmissionId 2025-04-15 10:28:19 +08:00
dijunkun b906bfcafd [fix] fix audio command sending 2025-04-14 17:33:35 +08:00
dijunkun f891a047d6 [fix] flush STREAM_FRASH event when stream closed 2025-04-14 17:15:00 +08:00
dijunkun dce32672a6 [fix] fix cursor mapping 2025-04-14 16:59:48 +08:00
dijunkun 2774991107 [fix] only send hostname and resolution before sending first frame 2025-04-14 16:49:31 +08:00
dijunkun b7ce8b6299 [fix] fix render resolution 2025-04-14 16:31:46 +08:00
dijunkun 700fb2ec14 [feat] send server resolution before sending first frame 2025-04-14 16:12:55 +08:00
dijunkun 62d14587cd [fix] fix compile warning 2025-04-11 16:09:11 +08:00
dijunkun 824d9243cc [fix] fix join problem that when join to a server which does not exist in recent connections 2025-04-10 17:35:21 +08:00
dijunkun 5351b4da0e [fix] do not show stream window if the client is only in server mode 2025-04-10 17:19:19 +08:00
dijunkun fcd0488624 [fix] fix control bar position when stream window created 2025-04-10 16:46:53 +08:00
dijunkun 193e905b28 [fix] save password only when join the connection successfully 2025-04-09 17:31:59 +08:00
dijunkun f48085c69a [fix] fix connection error when reinput password 2025-04-09 17:17:30 +08:00
dijunkun cf078be53f [feat] separate function Run() into several functions 2025-04-09 16:51:33 +08:00
dijunkun badcd6a05c [fix] fix mouse contorl error 2025-04-09 15:47:24 +08:00
dijunkun d828bd736d [feat] use peer map to manage multiple client instances 2025-04-08 17:34:33 +08:00
dijunkun 1e014bdae3 [fix] fix crash due to encoder releasing 2025-03-25 17:37:12 +08:00
dijunkun 334ab182db [fix] fix crash when try to close connection 2025-03-24 17:40:44 +08:00
dijunkun f52de76bfc [feat] update rtc api 2025-03-19 18:38:13 +08:00
dijunkun 6c7d0e8cab [feat] support FIR and NACK 2025-03-07 18:37:26 +08:00
dijunkun 7229ae856e [fix] fix video capture timestamp 2025-02-28 15:53:03 +08:00
dijunkun 597d760d24 [feat] fix crash and update rtc module 2025-02-06 17:37:18 +08:00
dijunkun bcf61e1ada [fix] fix crash due to sub stream window properties 2025-02-05 23:31:33 +08:00
dijunkun 08e596714b [fix] fix h264 rtp packetization error 2025-02-05 17:29:26 +08:00
dijunkun bff577ba34 [feat] update rtc module 2025-01-23 17:29:26 +08:00
dijunkun 4df935b9d2 [fix] fix log name conflict 2025-01-22 17:34:35 +08:00
dijunkun 9bb560314b [fix] use reinterpret_cast to convert u8"x" to const char* 2024-12-18 17:29:13 +08:00
dijunkun 1a0c5e8b42 [feat] use client_properties_ and server_properties_ to store streams properties 2024-12-03 17:22:15 +08:00
dijunkun 011919d0e7 [feat] use SubStreamWindowProperties to store sub stream properties 2024-12-02 17:30:51 +08:00
dijunkun 418ab7a1d2 [fix] fix net traffic stats display 2024-12-02 11:03:55 +08:00
dijunkun 6a2c9af316 [feat] loss rate display supported 2024-12-01 17:00:59 +08:00
dijunkun eaabf478cc [feat] update net statistics module 2024-11-29 17:54:15 +08:00
dijunkun ffe3ca76af [feat] switch rtc module into new branch 'qos' 2024-11-28 18:27:34 +08:00
dijunkun c5a6302220 [fix] update rtc module 2024-11-28 15:16:48 +08:00
dijunkun 9b2f81690f [fix] fix stream window scale error 2024-11-27 20:28:42 +08:00
dijunkun 9621e6b570 [fix] fix right shift key mapping on MacOSX 2024-11-27 17:33:54 +08:00
dijunkun ce3ae03bef [fix] prevent cursor relocation when stream window resized 2024-11-27 17:24:45 +08:00
dijunkun e0457213ea [fix] fix display errors when stream window resized 2024-11-27 16:14:14 +08:00
dijunkun 10cdc440a0 [fix] fix key press/release event 2024-11-27 14:34:54 +08:00
dijunkun ddc62c90bb [fix] fix all unused variables and type conversions on Windows 2024-11-27 11:17:43 +08:00
dijunkun 9e70d0e8fc [fix] fix all unused variables and type conversions on MacOSX 2024-11-27 10:57:09 +08:00
dijunkun 4533d53ba8 [fix] fix all unused variables and type conversions 2024-11-26 23:31:06 +08:00
dijunkun 0caa243006 [fix] fix unused variables and type conversions 2024-11-26 17:31:37 +08:00
dijunkun 1e58abdfdd [feat] rewrite log module 2024-11-26 16:05:28 +08:00
dijunkun 370ac08d09 [fix] use new rtc api 2024-11-26 15:06:55 +08:00
dijunkun 31b6b2736c [fix] fix control and shift keys convertion from Win to MacOSX 2024-11-25 17:29:49 +08:00
dijunkun abd22ab7f1 [fix] fix Win/MacOSX keycodes convertion 2024-11-25 17:15:22 +08:00
dijunkun 5ab68988aa [fix] fix stream window grabbing cannot be released after connection closed 2024-11-22 18:12:36 +08:00
dijunkun ba3edcc02a [feat] keyboard control supported on MacOSX 2024-11-22 18:05:13 +08:00
dijunkun 8414a57a5b [feat] keyboard control supported on Windows 2024-11-22 17:17:33 +08:00
dijunkun 3f777e4662 [fix] fix compile error 2024-11-22 16:45:14 +08:00
dijunkun 52828183a1 [feat] keyboard capture supported on Windows 2024-11-22 16:39:01 +08:00
dijunkun df7489f8e2 [fix] update imgui to v1.91.5-docking to fix: inputText cannot input text after add a space in remote id 2024-11-21 18:40:42 +08:00
dijunkun 4fea7d86e1 [feat] cursor will move into remote id input box automaticlly if the last input remote id does not exist 2024-11-21 16:20:25 +08:00
dijunkun cb17b7c8db [fix] fix setting item [enable turn] 2024-11-21 16:05:10 +08:00
dijunkun cf7ef89bf2 [fix] fix cursor position when stream window initialization 2024-11-21 10:34:04 +08:00
dijunkun 2d2a578800 [fix] fix control window position when stream window size changed 2024-11-20 19:17:33 +08:00
dijunkun 0ba12f3ccf [fix] only display client side net status if connected to itself 2024-11-19 22:33:59 +08:00
dijunkun 5ac603977d [fix] fix net traffic stats display 2024-11-19 17:31:31 +08:00
dijunkun 25d5a80bee [fix] reset net traffic stats after connection closed 2024-11-19 17:26:01 +08:00
dijunkun c9d452a025 [feat] disable settings modification during streaming 2024-11-19 17:21:27 +08:00
dijunkun 8132d62c02 [feat] show net traffic stats in control bar 2024-11-19 16:56:30 +08:00
dijunkun ca32ebeefe [feat] net traffic stats supported 2024-11-18 17:33:09 +08:00
dijunkun 5bf5e9ee25 [feat] change UI layouts 2024-11-18 16:08:54 +08:00
dijunkun bf097008e7 [feat] use SDL_WINDOW_HIDDEN to delay showing the main window to avoid black window during initialization 2024-11-18 15:10:02 +08:00
dijunkun 59b1208321 [feat] load different size fonts in initialization 2024-11-15 18:19:54 +08:00
dijunkun 84194188f8 [fix] fix redundant recent connection cache file due to remember_password_ flag not being set correctly 2024-11-14 17:26:08 +08:00
dijunkun a067441fb9 [feat] change recent connections layout 2024-11-14 17:13:38 +08:00
dijunkun 6eac8380b6 [feat] generate random AES128 key and iv during initialization, save them in cache file and load when program starts 2024-11-14 00:49:30 +08:00
dijunkun 5aed8317ca [feat] quick connecting supported 2024-11-13 23:27:06 +08:00
dijunkun 9aed7a19cf [fix] fix AES encrypt and decrypt 2024-11-13 17:58:59 +08:00
dijunkun c0154be1aa [fix] use APIs in evp.h to encrypt and decrypt 2024-11-13 00:47:54 +08:00
dijunkun f9d024e971 [feat] use AES to encrypt image names 2024-11-12 17:30:28 +08:00
dijunkun 526eb4bb31 [feat] add trash and connect buttons on recent connection images 2024-11-11 17:05:47 +08:00
dijunkun f9347cbd49 [feat] use confirm window to confirm recent connections deletion 2024-11-11 10:49:07 +08:00
dijunkun b6671bdbe7 [feat] delete recent connection supported 2024-11-08 17:52:19 +08:00
dijunkun edcf5d408c [feat] use horizontal scroll bar to show all recent connections 2024-11-08 14:51:58 +08:00
dijunkun 8c8731909e [feat] remote host names will be shown below thumbnails 2024-11-07 17:30:55 +08:00
dijunkun de721ac6e3 [feat] use a list to show thumbnails of recent connections 2024-11-07 16:58:25 +08:00
dijunkun 963f1da1d8 [fix] fix redefinition error on MacOSX 2024-11-07 16:32:35 +08:00
dijunkun 4c6159e4d4 [feat] write and load thumbnails supported 2024-11-07 16:29:02 +08:00
dijunkun e3c2e9ec6d [fix] fix png images write and read 2024-11-07 02:38:35 +08:00
dijunkun 02022bdcdf [feat] add recent connections window 2024-11-06 17:28:11 +08:00
dijunkun 19ea426efc [feat] change UI layouts 2024-11-05 17:29:39 +08:00
dijunkun 863070a8a7 [feat] enable window grab when mouse control enabled 2024-11-04 17:29:26 +08:00
dijunkun 44f9e6a8c9 [fix] fix crash due to multi-context fonts release 2024-11-04 16:13:20 +08:00
dijunkun 087d5d7e52 [feat] use an additional window to show video streams 2024-11-01 20:30:06 +08:00
dijunkun 26fa53f867 [fix] fix imgui layout error 2024-11-01 15:57:15 +08:00
dijunkun d18af6cbc6 [fix] fix client id generation 2024-10-30 17:25:41 +08:00
dijunkun b5bb62bd22 [feat] support new screen capture method by using ScreenCaptureKit on MacOSX 2024-10-18 17:20:52 +08:00
dijunkun 9ed3ab9929 [fix] fix the fullscreen error when closing the connection 2024-09-19 16:41:59 +08:00
dijunkun dca18762e0 [fix] use original screen render resolution to capturing and fix cursor mapping error 2024-09-13 17:08:58 +08:00
dijunkun fed7c3b103 [fix] fix cursor mapping error 2024-09-13 16:04:19 +08:00
dijunkun d246b7a04d [fix] fix the issue where the title bar is displayed incorrectly when in fullscreen mode 2024-09-13 15:10:23 +08:00
dijunkun a49ca813e0 [fix] fix black screen after close the connection 2024-09-13 10:35:53 +08:00
dijunkun 0c688efaee [fix] fix buttons position when control bar in the right 2024-09-12 17:22:13 +08:00
dijunkun be3561d46f [fix] optimize the first graph rendering time when open this program 2024-09-12 17:17:07 +08:00
dijunkun c3af40a3f0 [feat] add close button in control bar 2024-09-12 16:22:02 +08:00
dijunkun d493b9a131 [feat] make the window centered on the screen after closed 2024-09-12 13:57:51 +08:00
dijunkun 4e4e84ae4d [fix] fix window size when closed after resized 2024-09-12 13:51:11 +08:00
dijunkun fea545e5e7 [fix] do not forget to destroy the texture 2024-09-11 17:35:27 +08:00
dijunkun 9096769a85 [fix] fix render stream blurry problem 2024-09-11 11:22:17 +08:00
dijunkun 04ab157ecb [fix] fix crash due to invalid pointer 2024-09-10 17:33:55 +08:00
dijunkun 2331f08283 [fix] fix cursor mapping error due to the client render aspect ratio different from the server screen aspect ratio 2024-09-06 19:36:33 +08:00
dijunkun 9f8f99f21b [fix] fix cursor mapping error due to ffmpeg default screen capture resolution different from the real screen resolution 2024-09-06 19:32:30 +08:00
dijunkun 56dadb6a49 Merge branch 'rt_desk' of github.com:dijunkun/continuous-desk into rt_desk 2024-09-06 17:38:43 +08:00
dijunkun 59c9ca8d53 [fix] fix render area cannot fit the resolution of the receiving video stream 2024-09-06 17:38:09 +08:00
dijunkun f16a4e8aa2 [feat] support original resolution screen capture on MacOSX 2024-09-06 15:20:06 +08:00
dijunkun 890615e13a [fix] fix crash during termination 2024-09-06 13:07:20 +08:00
dijunkun 2f72e3957e [feat] support dynamic resolution codec 2024-09-05 17:29:27 +08:00
dijunkun 1292018f51 [fix] fix crash when signal server close the connection actively 2024-09-04 17:03:40 +08:00
dijunkun 8ae9513104 [feat] only a six-char password will be accepted 2024-09-03 17:29:46 +08:00
dijunkun c1efe2f4ac [feat] do not capture cursor 2024-09-03 17:00:57 +08:00
dijunkun 1210a0b631 [fix] fix crash caused by accessing invalid memory 2024-09-03 16:24:36 +08:00
dijunkun 39863c597e [feat] allow user to set customized password 2024-09-03 15:50:38 +08:00
dijunkun 8a964f0030 [feat] add option 'enable TURN service' in settings menu 2024-09-02 17:29:03 +08:00
dijunkun 74e29f25bf [fix] do not use smart pointer to manage std::thread objects 2024-09-02 16:33:01 +08:00
dijunkun 1e5bea2b1e [feat] put ice agent into ice worker thread and use message queue to handle events 2024-08-28 17:31:27 +08:00
dijunkun d8297ebb74 [feat] use fix random password otherwise user regenerates one 2024-08-28 10:28:11 +08:00
dijunkun 93d7f71cf2 [feat] support use param to control enable TURN or not 2024-08-27 17:06:56 +08:00
dijunkun 887a217828 [fix] fix fonts missing 2024-08-27 17:04:11 +08:00
dijunkun 89b12136e4 [fix] Optimizing video encoding speed for software encoders 2024-08-20 17:18:29 +08:00
dijunkun def7025abf [fix] fix connection status display 2024-08-20 10:21:34 +08:00
dijunkun 35af5aab43 [fix] fix control bar border color 2024-08-19 17:09:19 +08:00
dijunkun 9ea67df0fd [fix] fix title bar icon error when leaves maximized state 2024-08-19 14:16:21 +08:00
dijunkun 72fda8a728 [feat] let keyboard focus on input widget when needs to input password 2024-08-19 11:05:08 +08:00
dijunkun 070b48d7a7 [fix] fix mouse and audio capture buttons cannot be disabled once enabled 2024-08-16 17:30:44 +08:00
dijunkun 6168009cef [feat] support building xcode app on MacOSX 2024-08-16 17:19:17 +08:00
dijunkun 06a7243ac1 [fix] fix mouse click event sending when control bar hovered 2024-08-16 15:06:42 +08:00
dijunkun c8602b0d89 [fix] fix cursor position error 2024-08-16 14:52:44 +08:00
dijunkun e3c730fd5f [fix] fix screen capture error in client mode 2024-08-16 14:22:08 +08:00
dijunkun b252cb6ddd [style] use self-draw icon for mouse and audio_capture disable buttons 2024-08-16 13:55:48 +08:00
dijunkun 8ca1e8e5a1 [style] reset menu bar line size 2024-08-16 09:35:09 +08:00
dijunkun a7d45b78c8 [feat] use self-draw icon for title bar 2024-08-15 17:38:18 +08:00
dijunkun 018231eee4 [feat] add protocol to control audio capture 2024-08-15 14:50:47 +08:00
dijunkun 4704d494ec [feat] add audio capture button in control bar 2024-08-15 11:25:19 +08:00
dijunkun 65927c2091 [feat] support speaker capture on Windows 2024-08-15 11:04:06 +08:00
dijunkun 574b9d10ab [fix] let temproary setting values equal to setting values when loading from cache file 2024-08-14 16:50:49 +08:00
dijunkun ff510a3b44 [fix] fix peer object delete 2024-08-14 16:39:08 +08:00
dijunkun 4d3c864950 [fix] fix client id cannot read from cache file 2024-08-13 17:17:35 +08:00
dijunkun 2cde54cf30 [fix] call memset() before using strncpy() 2024-08-13 17:07:19 +08:00
dijunkun d1f3d11318 [fix] use SDL_RestoreWindow() to reset the window when closed during streaming 2024-08-13 16:32:17 +08:00
dijunkun 436228946b [feat] do not show menu button during streaming 2024-08-13 16:21:31 +08:00
dijunkun 2b4083ee10 [feat] expand control bar by default 2024-08-13 11:26:18 +08:00
dijunkun e3abb4e3de [fix] fix recreate peer failed due to is_create_connection_ flag not reset 2024-08-13 11:15:28 +08:00
dijunkun 4b7cd1005b [fix] fix send error when ice state change from ready to connected 2024-08-09 16:54:14 +08:00
dijunkun 03ea96096d [feat] add space automaticlly for remote id input box 2024-08-09 11:33:13 +08:00
dijunkun 0ea8916426 [fix] fix settings error when load from cache file 2024-08-09 10:56:16 +08:00
dijunkun 43b36eb893 [fix] use proper std::chrono clock 2024-08-09 10:23:51 +08:00
dijunkun 03b6a187b3 [feat] split remote id into chunks of three characters separated by space 2024-08-08 16:34:55 +08:00
dijunkun 664412dd4e [feat] enable Enter key pressing for ImGui::InputText() method 2024-08-08 15:56:20 +08:00
dijunkun b37e08a202 [fix] fix client id empty error when run the program firstly 2024-08-08 15:26:21 +08:00
dijunkun a05d72ec67 [feat] lock the cache file when write/read it 2024-08-08 15:24:54 +08:00
dijunkun f77e9fe6a8 [feat] remove 'I/l/O/o/0' from password generator 2024-08-08 15:22:51 +08:00
dijunkun 1f9614e060 [feat] use h264 codec by default 2024-08-08 15:15:58 +08:00
dijunkun 50d92a763a [fix] fix leave transmission error when exit program 2024-08-07 17:33:05 +08:00
dijunkun ec23656334 [fix] fix client id error when connect to itself 2024-08-07 09:55:59 +08:00
dijunkun 880c2949c3 [feat] Use server to generate transmission id and client id 2024-08-06 17:27:40 +08:00
dijunkun 07f5fe81c8 [fix] fix control bar cannot stick to right side when out of y-axis region 2024-08-06 11:24:10 +08:00
dijunkun 5a992b6589 [fix] fix control bar width 2024-08-06 10:35:25 +08:00
dijunkun 8e03e8e79b [feat] make control bar stick to left/right border 2024-08-05 17:28:39 +08:00
dijunkun ceb3d9fe20 [feat] make control bar can only move along left border of the main window 2024-08-02 17:31:01 +08:00
dijunkun 0dc0b87bc4 [fix] fix control bar initial postion 2024-08-02 16:46:39 +08:00
dijunkun 3a4284fece [fix] fix read cache file failed 2024-08-02 16:15:18 +08:00
dijunkun 502a90f121 [fix] fix program cannot exit when click close button due to screen capture thread is running 2024-08-02 14:38:31 +08:00
dijunkun 88cd4aca4a [fix] fix title bar display error when streaming 2024-08-02 13:57:12 +08:00
dijunkun 3395004f93 [fix] fix compile error on Macosx and Linux 2024-08-02 13:56:22 +08:00
dijunkun e4c05e1f4d [feat] enable movement for control bar 2024-08-02 12:30:50 +08:00
dijunkun d17c70c2c8 [feat] remove menu bar and move menu button to title bar 2024-08-01 17:28:39 +08:00
dijunkun 7b42923418 [feat] use self designed title bar instead of system default title bar 2024-07-31 17:43:02 +08:00
dijunkun 5b6bdee25a [feat] add callback to notify the travsesal mode 2024-07-30 17:32:12 +08:00
dijunkun 05deb73c29 [feat] Support trickle ice 2024-07-29 16:48:22 +08:00
dijunkun 3685acc549 [feat] set window resizable only in streaming state 2024-07-25 10:10:37 +08:00
dijunkun 8f5a53937a [fix] fix control bar display and button postion 2024-07-24 17:10:05 +08:00
dijunkun b9c5db41ab [fix] show connection status windows when connection status changed 2024-07-24 16:27:58 +08:00
dijunkun a99a4230af Add module: speaker capture 2024-07-24 16:16:13 +08:00
dijunkun f446154747 1.Fix texture update crash; 2.Do not show control window when in server mode 2024-07-19 14:54:53 +08:00
dijunkun 5a1e2c5ed9 Use speaker as audio input 2024-07-19 14:10:35 +08:00
dijunkun ff6f295fac Do not use rc file on MacOS 2024-07-18 16:06:35 +08:00
dijunkun 3111b3a641 Add icon 2024-07-18 15:58:28 +08:00
dijunkun 20bb13ce85 Chinese support in connection status window 2024-07-18 14:46:19 +08:00
dijunkun 5aa05f3a13 Redesign elements styles 2024-07-18 11:02:35 +08:00
dijunkun c911aa2eb1 Add about window 2024-07-17 16:22:45 +08:00
dijunkun d0cd2fe9ab Fix log instance mismatch 2024-07-17 14:45:30 +08:00
dijunkun 9702805331 Make control bar scrollable 2024-07-05 16:05:50 +08:00
dijunkun 872152f1be 1.Enable random password; 2.Request user to input password when password is incorrect 2024-07-03 15:07:40 +08:00
dijunkun b822221d7f Add a button which can copy local id to clipboard 2024-07-03 11:03:04 +08:00
dijunkun 95ad605b36 Add signal and p2p connection status windows 2024-07-02 17:29:39 +08:00
dijunkun af32e25149 Use minimized compressed fonts header file 2024-07-02 11:19:50 +08:00
dijunkun e63b384d1e Set dpi scaling to solve display errot when using high dpi displayer 2024-07-01 16:31:39 +08:00
dijunkun 7f25f7426c Fix remote window height size error 2024-07-01 11:24:58 +08:00
dijunkun eed93ea953 Set utf-8 encoding flag in xmake.lua 2024-07-01 10:20:32 +08:00
dijunkun b5f8e92526 Solve the warning of method ImGui::Text() 2024-06-28 15:11:40 +08:00
dijunkun af04b0571e Use UTF-8 to save files 2024-06-28 12:49:56 +08:00
dijunkun 75452a3e76 1.Use compressed OPPOSans-Regular[3500 chinese characters]; 2.Use same layout style on different platforms 2024-06-28 12:30:09 +08:00
dijunkun 3f717f1df2 Use binary font headerfile instead of ttf file 2024-06-28 10:01:34 +08:00
dijunkun ad6f2c2c70 Implementation for menu bar 2024-06-27 17:36:13 +08:00
dijunkun 8076e7f662 Fix stream render with menu bar 2024-06-26 14:58:15 +08:00
dijunkun be78496992 Separate stream window from main window 2024-06-25 14:47:54 +08:00
dijunkun a3f745d441 Use fix ratio to render frame in window 2024-06-25 11:12:10 +08:00
dijunkun e693d920d3 Use sub windows to render main window 2024-06-24 17:35:25 +08:00
dijunkun 0f1b89eda9 Test tabbar in ImGui 2024-06-19 17:33:44 +08:00
dijunkun 172b8836fd Use FontAwesome6 to render icons 2024-06-18 17:28:02 +08:00
dijunkun 71178ffa33 Separate render window from main window 2024-06-17 17:31:57 +08:00
dijunkun 95a014a601 Not allow clicking connect button if remote id is empty 2024-06-14 17:01:58 +08:00
dijunkun 34d6bac345 Update Windows platform layout style 2024-06-14 16:02:55 +08:00
dijunkun 399785409c Use element style header file to control layout 2024-06-14 15:37:16 +08:00
dijunkun 5f1d9b6912 Fix language localization error 2024-06-14 13:55:05 +08:00
dijunkun d963a0cf38 1.The mouse control button allowed to be clicked Only when connection established; 2.Fix display resolution error after exit fullscreen 2024-06-14 10:48:35 +08:00
dijunkun f9c1bc48b4 Add control/release mouse button 2024-06-13 17:36:02 +08:00
dijunkun 2906d05a4b Do not send mouse click event when cursor hovers over subwindows 2024-06-13 16:56:03 +08:00
dijunkun 053a0f86ad Add mouse control flag 2024-06-13 16:36:11 +08:00
dijunkun 6c2363b239 Clear render buffer when connection closed 2024-06-13 16:30:25 +08:00
dijunkun 167514fed8 Do not collapse menu window when connection established 2024-06-13 16:07:22 +08:00
dijunkun 342eb0c386 Reset connection_established_ flag when connection closed 2024-06-13 16:06:02 +08:00
dijunkun 52c7099dbe Fix crash when connecting to local desk 2024-06-13 15:49:26 +08:00
dijunkun 12faf7cd2d Do not reset is_create_connection_ when click disconnect button 2024-06-07 18:13:09 +08:00
dijunkun 6d921a3309 Fix server mode screen capture error 2024-06-07 16:30:18 +08:00
dijunkun 5a690ebbb6 Do not use 'S-' or 'C-' as the prefix for the user id of a peer 2024-06-07 16:27:05 +08:00
dijunkun 4b3839aa34 Only server can capture screen and control mouse 2024-06-07 14:07:22 +08:00
dijunkun efb165b56f 1.Add CreateConnectionPeer method in order to recreate peer instance; 2.Fix settings OK/Cancel button position 2024-06-06 17:19:16 +08:00
dijunkun 0047b4ecc5 Recreate peer instance after settings changed 2024-06-06 15:11:02 +08:00
dijunkun 844710af7c Fix settings button value mismatch 2024-06-06 14:34:16 +08:00
dijunkun 562d54090a Use 'ImGuiWindowFlags_NoSavedSettings' for settings window 2024-06-06 09:57:37 +08:00
dijunkun f7fd37651e Reset settings window position before it is opened 2024-06-06 09:55:08 +08:00
dijunkun 280f59f97d Enable movement of settings window 2024-06-05 17:33:42 +08:00
dijunkun 0683ad9d27 Use Combo instead of RadioButton for settings 2024-06-05 17:30:23 +08:00
dijunkun e061e3b4d7 Support read configure params from input directly 2024-06-04 17:38:55 +08:00
dijunkun eaedcb8d06 Fix crash caused by the release of screen capturer 2024-06-04 16:27:34 +08:00
dijunkun e7e6380adc Start capturing screen when connection established 2024-06-03 23:48:53 +08:00
dijunkun 1f50483b50 Save settings into cache file 2024-06-03 17:02:20 +08:00
dijunkun 6f703c8267 Use OOP to refactor main function 2024-06-03 15:23:37 +08:00
dijunkun d150c374b5 Reset main window width/height ratio automatically when width/height is changed 2024-06-03 11:30:55 +08:00
dijunkun f29b2ee09d Test user date in peer instance and callback functions 2024-05-30 17:27:49 +08:00
dijunkun 0a934e8c01 Fix LNK1561 error on Winodws 2024-05-30 16:33:50 +08:00
dijunkun 2163aa87d4 The connection can use only one peer to realize server and client 2024-05-30 16:12:53 +08:00
dijunkun 5d8408d892 Use abstraction to refactor remote desk gui 2024-05-29 17:33:41 +08:00
dijunkun 93d0e3a5d0 Auto collapse menu bar when connection established 2024-05-28 17:37:06 +08:00
dijunkun b4a5e91bc9 Support fullscreen 2024-05-28 16:27:04 +08:00
dijunkun 759078ef7f 1.Use PingFang.ttc as Chinese default fonts on MacOS;2.Fix link error for FFmpeg 2024-05-28 15:25:16 +08:00
dijunkun 905539a6eb 1.Use Windows font file 'simhei.ttf'; 2.Add test button for fullscreen 2024-05-27 17:06:09 +08:00
dijunkun f1512812ad Support localization(Simplified Chinese[source-han-sans-regular]) 2024-05-24 17:15:44 +08:00
dijunkun 5f1cf89649 Fix crash during termination on windows 2024-05-24 15:48:37 +08:00
dijunkun f291ad189a 1.Remove sdl2 from thirdparty since it is already required by imgui; 2.Update imgui to v1.90.6; 3.Update spdlog to v 1.14.1 2024-05-24 15:10:58 +08:00
dijunkun 8807636372 Fix crash caused by screen capturer or mouse controller init failed on Linux and MacOS 2024-05-23 15:48:10 +08:00
dijunkun 70be1d8afc Update submodule projectx 2024-05-22 16:39:27 +08:00
dijunkun 1f76aa427d Change submodule projectx url 2024-05-22 16:35:30 +08:00
dijunkun 134cbf8b75 Restore ffmpeg dependency for Linux and MacOS due to screen capture needs ffmpeg on these platforms 2024-05-22 14:06:12 +08:00
dijunkun 669b944cfd Remove resampling process during SDL2 capture audio stream 2024-05-21 17:01:08 +08:00
dijunkun 9962829885 Fix ARGB to NV12 error caused by uv stride 2024-05-20 10:47:44 +08:00
dijunkun 1393615f01 Remove dependency on FFmpeg 2024-05-17 17:55:57 +08:00
dijunkun d58ae3a6b1 Fix AV1 codec on MacOS 2024-05-10 14:45:12 +08:00
dijunkun a188729af6 Support AV1 stream transmitting over RTP 2024-05-09 17:05:38 +08:00
dijunkun 422478bd9a Support AV1 codec 2024-04-19 17:37:00 +08:00
dijunkun d8980f0082 WGC screen capturer needs c++17 or above 2023-12-22 16:07:32 +08:00
dijunkun e88bb017fa 1.Using c++14; 2.Using {} to initialize std::atomic 2023-12-22 15:46:54 +08:00
dijunkun 87466d6074 Update thirdparty library 2023-12-22 14:14:08 +08:00
Di Junkun fbbbfc5e6a Update README_CN.md 2023-12-21 15:02:12 +08:00
Di Junkun d2cefd1827 Update README.md 2023-12-21 14:59:44 +08:00
Di Junkun a350e06529 Update README.md 2023-12-21 14:56:18 +08:00
Di Junkun 8c742ffa08 Update README.md 2023-12-21 14:34:11 +08:00
Di Junkun 475005b8a4 Update README.md 2023-12-20 15:54:54 +08:00
dijunkun 4da5188759 Update README.md 2023-12-20 15:19:44 +08:00
Di Junkun d8df4df5ae Update README.md 2023-12-20 15:17:53 +08:00
dijunkun fa05bbc8f8 Update README.md 2023-12-20 13:00:39 +08:00
Di Junkun 927f1a6d49 Update README.md 2023-12-20 09:34:43 +08:00
dijunkun 1d87f61d9f Update README.md 2023-12-19 17:33:16 +08:00
dijunkun ce546b77f5 Hide cursor when remote peer connected 2023-12-18 16:52:49 +08:00
dijunkun b9e69cde51 Remove unused variables 2023-12-18 16:17:55 +08:00
dijunkun e3987b4a42 Fix remote action type undefined error 2023-12-18 16:06:53 +08:00
dijunkun 0034359431 Update submodule 2023-12-18 15:27:11 +08:00
dijunkun cec275bbe0 Add 1 second time interval for retry join transmission 2023-12-18 15:10:41 +08:00
dijunkun fe68464cd2 Fix remote id hint error 2023-12-18 13:43:08 +08:00
dijunkun 181c473625 Use SDL to get screen resolution 2023-12-18 11:15:55 +08:00
dijunkun 2fc89923ae Use factory method to create screen capturer 2023-12-15 17:29:17 +08:00
dijunkun 9276d5bfec Fix compile error 2023-12-14 17:14:52 +08:00
dijunkun 95ef8fe8b9 Use factory method to create mouse controller on MacOS 2023-12-14 17:02:43 +08:00
dijunkun 3ab0e0136e Use factory method to create mouse controller on Windows 2023-12-14 16:40:10 +08:00
dijunkun daecc0d1e9 Use factory method to create mouse controller on Linux 2023-12-14 16:27:13 +08:00
dijunkun bfecf47226 Fix cross platform compile error 2023-12-13 17:32:02 +08:00
dijunkun 09c42dd7ed 1.Add linux mouse control test;2.Fix unused variables warnning 2023-12-13 17:26:08 +08:00
dijunkun a8a3b88514 Use uinput to control mouse and keyboard on Linux 2023-12-07 19:00:34 -08:00
dijunkun 2d6cfb5c76 Support cursor control on MacOS 2023-12-06 15:24:01 +08:00
dijunkun ed8b536ac0 Add signal connection status 'NoSuchTransmissionId' 2023-12-04 14:04:36 +08:00
dijunkun 5e2d27e9d2 Fix ffmpeg link error on MacOS 2023-12-04 11:20:30 +08:00
dijunkun 47a2dc85f9 Fix screen capture on MacOS 2023-12-01 17:16:38 +08:00
dijunkun 5febe99bc2 Support screen capture on MacOS 2023-12-01 16:54:17 +08:00
664 changed files with 157462 additions and 3760 deletions
+22
View File
@@ -0,0 +1,22 @@
**
!.dockerignore
!docker/
!docker/linux-build/
!docker/linux-build/**
# Dependency manifests and local xmake package recipes are the only project
# files needed while pre-warming the build image.
!xmake.lua
!apps/
!apps/desktop/
!apps/desktop/xmake/
!apps/desktop/xmake/**
!deps/thirdparty/
!deps/thirdparty/**
!deps/submodules/
!deps/submodules/xmake.lua
!deps/submodules/minirtc/
!deps/submodules/minirtc/xmake.lua
!deps/submodules/minirtc/thirdparty/
!deps/submodules/minirtc/thirdparty/**
+3
View File
@@ -0,0 +1,3 @@
*.h linguist-language=C++
*.cpp linguist-language=C++
*.lua linguist-language=Xmake
+35
View File
@@ -0,0 +1,35 @@
---
name: 问题反馈
about: 请在此提交问题报告,以便持续优化产品。
title: ''
labels: bug
assignees: kunkundi
---
**描述问题**
清晰简洁地描述遇到的错误。
**复现步骤**
复现该问题的步骤:
1. 前往 '...'
2. 点击 '....'
3. 出现错误
**预期行为**
清晰简洁地描述你期望发生的行为。
**截图**
如果适用,请添加截图以帮助说明问题。
**桌面端信息(请填写以下内容):**
- 操作系统: [例如 Windows 11]
- 版本: [例如 v1.1.10]
**移动端信息(请填写以下内容):**
- 设备: [例如 iPhone 17]
- 操作系统: [例如 iOS 26.1]
- 浏览器: [例如 系统浏览器、Safari]
**补充信息**
在此添加与问题相关的其他上下文内容。
+28
View File
@@ -0,0 +1,28 @@
---
name: 需求建议
about: 请在此提交功能需求或改进建议,以便后续迭代参考。
title: ''
labels: enhancement
assignees: kunkundi
---
**功能/改进建议描述**
清晰简洁地描述希望新增的功能或改进的内容。
**使用场景 / 背景**
说明该功能或改进的使用场景,以及解决后带来的价值。
**预期效果**
描述你认为最理想的功能表现或改进效果。
**参考示例(可选)**
提供类似功能截图、参考链接或其他说明,帮助更好理解需求。
**优先级(可选)**
- [ ] 高
- [ ] 中
- [ ] 低
**补充信息(可选)**
其他相关信息或特殊要求。
+29
View File
@@ -0,0 +1,29 @@
name: Ensure minimum Xmake version
description: Keep a compatible Xmake installation, or install the minimum required version.
inputs:
minimum-version:
description: Minimum supported Xmake version (major.minor.patch).
required: true
runs:
using: composite
steps:
- name: Check installed Xmake version
id: check
shell: bash
env:
XMAKE_MIN_VERSION: ${{ inputs.minimum-version }}
run: bash "$GITHUB_ACTION_PATH/check-version.sh"
- name: Install or upgrade Xmake
if: steps.check.outputs.needs-upgrade == 'true'
uses: xmake-io/github-action-setup-xmake@v1
with:
xmake-version: ${{ inputs.minimum-version }}
- name: Verify Xmake meets the minimum version
shell: bash
env:
XMAKE_MIN_VERSION: ${{ inputs.minimum-version }}
run: bash "$GITHUB_ACTION_PATH/check-version.sh" --verify
@@ -0,0 +1,98 @@
#!/usr/bin/env bash
set -euo pipefail
export LC_ALL=C
verify=false
if [[ $# -eq 1 && "$1" == "--verify" ]]; then
verify=true
elif [[ $# -ne 0 ]]; then
echo "Usage: $0 [--verify]" >&2
exit 2
fi
minimum_version="${XMAKE_MIN_VERSION:-}"
if [[ ! "$minimum_version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "XMAKE_MIN_VERSION must be a numeric major.minor.patch version, for example 3.1.1." >&2
exit 2
fi
version_at_least() {
local -a installed_parts required_parts
local index installed_component required_component
IFS=. read -r -a installed_parts <<< "$1"
IFS=. read -r -a required_parts <<< "$2"
for index in 0 1 2; do
installed_component="${installed_parts[$index]}"
required_component="${required_parts[$index]}"
# Strip leading zeroes and compare lengths first, avoiding both octal
# interpretation and integer overflow in Bash's arithmetic expansion.
while [[ ${#installed_component} -gt 1 && "$installed_component" == 0* ]]; do
installed_component="${installed_component#0}"
done
while [[ ${#required_component} -gt 1 && "$required_component" == 0* ]]; do
required_component="${required_component#0}"
done
if [[ ${#installed_component} -gt ${#required_component} ]]; then
return 0
elif [[ ${#installed_component} -lt ${#required_component} ]]; then
return 1
elif [[ "$installed_component" > "$required_component" ]]; then
return 0
elif [[ "$installed_component" < "$required_component" ]]; then
return 1
fi
done
return 0
}
detected_version=""
needs_upgrade=true
reason="xmake was not found on PATH"
if command -v xmake >/dev/null 2>&1; then
if version_output="$(xmake --root --version 2>&1)"; then
# Xmake can color individual words and version components. Strip ANSI
# CSI sequences before matching, using only Bash 3.2 builtins.
ansi_pattern=$'\033''\[[0-?]*[ -/]*[@-~]'
while [[ "$version_output" =~ $ansi_pattern ]]; do
version_output="${version_output//"${BASH_REMATCH[0]}"/}"
done
version_pattern='(^|[[:space:]])xmake[[:space:]]+v([0-9]+\.[0-9]+\.[0-9]+)([+][[:alnum:].-]+)?([,[:space:]]|$)'
while IFS= read -r line; do
if [[ "$line" =~ $version_pattern ]]; then
detected_version="${BASH_REMATCH[2]}"
break
fi
done <<< "$version_output"
if [[ -z "$detected_version" ]]; then
reason="xmake --root --version did not report a recognizable Xmake version"
elif version_at_least "$detected_version" "$minimum_version"; then
needs_upgrade=false
else
reason="installed Xmake $detected_version is below $minimum_version"
fi
else
reason="xmake --root --version failed with exit code $?"
fi
fi
if [[ -n "${GITHUB_OUTPUT:-}" ]]; then
{
printf 'needs-upgrade=%s\n' "$needs_upgrade"
printf 'detected-version=%s\n' "$detected_version"
} >> "$GITHUB_OUTPUT"
else
printf 'needs-upgrade=%s\n' "$needs_upgrade"
printf 'detected-version=%s\n' "$detected_version"
fi
if [[ "$needs_upgrade" == true ]]; then
if [[ "$verify" == true ]]; then
echo "Xmake verification failed: $reason. Ensure Xmake $minimum_version or newer is installed and on PATH." >&2
exit 1
fi
echo "Xmake upgrade required: $reason. Install Xmake $minimum_version or newer."
else
echo "Keeping installed Xmake $detected_version; it meets the minimum version $minimum_version."
fi
@@ -0,0 +1,154 @@
"""Regression coverage for independent and combined release metadata."""
import copy
import json
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
import update_version_manifest as manifest
class ManifestTest(unittest.TestCase):
def setUp(self):
temporary = tempfile.TemporaryDirectory(prefix="crossdesk-manifest-")
self.addCleanup(temporary.cleanup)
self.root = Path(temporary.name)
self.artifacts = self.root / "release"
self.artifacts.mkdir()
self.current = {
"version": "1.6.0-20260930", "latest_version": "1.6.0-20260930",
"releaseDate": "2026-09-30", "releaseNotes": "Desktop notes", "patch": 0,
"downloads": {"windows-x64": {"url": "https://downloads.crossdesk.cn/existing.exe"}},
"custom": {"keep": True},
}
def files(self, *names):
for path in self.artifacts.iterdir():
path.unlink()
for name in names:
(self.artifacts / name).write_bytes(b"release fixture")
return manifest.artifact_downloads(self.artifacts)
def merge(self, tag, downloads, current=None):
return manifest.merge_release(current or self.current, tag, tag, "Release notes", downloads)
def test_mobile_preserves_desktop_metadata_and_downloads(self):
downloads = self.files("crossdesk-android-arm64-unsigned-v1.6.0-20261002.apk")
original = copy.deepcopy(self.current)
result = self.merge("android-v1.6.0-20261002", downloads)
for key, value in original.items():
if key != "downloads":
self.assertEqual(result[key], value)
self.assertEqual(result["downloads"]["windows-x64"], original["downloads"]["windows-x64"])
self.assertEqual(result["downloads"]["android-arm64"]["url"],
"https://downloads.crossdesk.cn/crossdesk-android-arm64-unsigned-v1.6.0-20261002.apk")
self.assertEqual(result["downloads"]["android-arm64"]["version"], "1.6.0-20261002")
self.assertEqual(result["downloads"]["android-arm64"]["releaseDate"], "2026-10-02")
self.assertNotIn("platforms", result)
self.assertEqual(self.current, original)
def test_sequential_platform_releases_retain_each_other(self):
for order in (("ios", "android"), ("android", "ios")):
result = copy.deepcopy(self.current)
for platform in order:
version, extension = ("0.0.2", "zip") if platform == "ios" else ("1.6.0", "apk")
downloads = self.files(f"crossdesk-{platform}-arm64-unsigned-v{version}-20261002.{extension}")
result = self.merge(f"{platform}-v{version}-20261002", downloads, result)
self.assertNotIn("platforms", result)
self.assertEqual(result["version"], self.current["version"])
self.assertTrue({"windows-x64", "ios-arm64", "android-arm64"} <= result["downloads"].keys())
self.assertEqual(result["downloads"]["ios-arm64"]["version"], "0.0.2-20261002")
self.assertEqual(result["downloads"]["android-arm64"]["version"], "1.6.0-20261002")
def test_combined_release_records_independent_mobile_versions(self):
downloads = self.files("crossdesk-win-x64-v1.6.1-20261002.exe",
"crossdesk-win-x64-portable-v1.6.1-20261002.zip",
"crossdesk-ios-arm64-unsigned-v0.0.2-20261002.zip",
"crossdesk-android-arm64-unsigned-v1.6.0-20261002.apk")
result = self.merge("v1.6.1-20261002", downloads)
self.assertEqual(result["version"], "1.6.1-20261002")
self.assertEqual(result["downloads"]["ios-arm64"]["version"], "0.0.2-20261002")
self.assertEqual(result["downloads"]["android-arm64"]["version"], "1.6.0-20261002")
self.assertNotIn("platforms", result)
def test_obsolete_platforms_are_removed_on_any_release(self):
for tag, artifact in (
("android-v1.6.0-20261002", "crossdesk-android-arm64-unsigned-v1.6.0-20261002.apk"),
("v1.6.1-20261002", "crossdesk-win-x64-v1.6.1-20261002.exe"),
):
downloads = self.files(artifact)
expected = self.merge(tag, downloads)
for obsolete in ({"ios": {"version": "0.0.1"}}, []):
current = {**copy.deepcopy(self.current), "platforms": obsolete}
original = copy.deepcopy(current)
self.assertEqual(self.merge(tag, downloads, current), expected)
self.assertEqual(current, original)
def test_mobile_tag_must_match_artifact_and_platform(self):
downloads = self.files("crossdesk-android-arm64-unsigned-v1.6.0-20261002.apk")
for tag in ("android-v1.7.0-20261002", "ios-v1.6.0-20261002"):
with self.assertRaises(ValueError):
self.merge(tag, downloads)
def test_signed_android_release_updates_existing_unsigned_download(self):
unsigned = self.files("crossdesk-android-arm64-unsigned-v1.6.0-20261002.apk")
current = self.merge("android-v1.6.0-20261002", unsigned)
signed = self.files("crossdesk-android-arm64-v1.6.0-20261002.apk")
result = self.merge("android-v1.6.0-20261002", signed, current)
self.assertEqual(result["downloads"]["android-arm64"]["url"],
"https://downloads.crossdesk.cn/crossdesk-android-arm64-v1.6.0-20261002.apk")
self.assertEqual(result["version"], self.current["version"])
self.assertEqual(result["downloads"]["windows-x64"], self.current["downloads"]["windows-x64"])
self.assertNotIn("platforms", result)
def test_signed_android_is_preferred_when_release_retains_unsigned_apk(self):
downloads = self.files("crossdesk-android-arm64-unsigned-v1.6.0-20261002.apk",
"crossdesk-android-arm64-v1.6.0-20261002.apk")
self.assertEqual(downloads["android-arm64"]["filename"],
"crossdesk-android-arm64-v1.6.0-20261002.apk")
with self.assertRaises(ValueError):
self.files("crossdesk-android-arm64-unsigned-v1.6.0-20261001.apk",
"crossdesk-android-arm64-v1.6.0-20261002.apk")
def test_invalid_current_manifest_is_rejected(self):
downloads = self.files("crossdesk-android-arm64-unsigned-v1.6.0-20261002.apk")
for current in ([], {}, {"downloads": []}):
with self.assertRaises(ValueError):
manifest.merge_release(current, "android-v1.6.0-20261002", "Android", "", downloads)
def test_missing_duplicate_and_invalid_artifacts_are_rejected(self):
for names in ((), ("crossdesk-android-arm64-unsigned-v1.6.0-20260230.apk",),
("crossdesk-android-arm64-unsigned-v1.6.0-20261001.apk",
"crossdesk-android-arm64-unsigned-v1.6.0-20261002.apk")):
with self.assertRaises(ValueError):
self.files(*names)
def test_hotfix_version_and_date_formats(self):
for value in ("v1.6.0-2-20261002", "v1.6.0-20261002-2"):
info = manifest.version_info(value)
self.assertEqual(info["patch"], 2)
self.assertEqual(info["releaseDate"], "2026-10-02")
def test_cli_preserves_literal_notes_and_release_metadata(self):
self.files("crossdesk-win-x64-v1.6.1-20261002.exe")
notes = '中文 release notes\n"quoted" $(not-a-command) $HOME `literal`'
release = {"tagName": "v1.6.1-20261002", "name": "Desktop release", "body": notes}
(self.root / "current.json").write_text(json.dumps(self.current))
(self.root / "release.json").write_text(json.dumps(release))
output = self.root / "version.json"
subprocess.run([sys.executable, str(Path(manifest.__file__)),
"--current", str(self.root / "current.json"), "--output", str(output),
"--artifacts", str(self.artifacts), "--release-json", str(self.root / "release.json")],
check=True, capture_output=True, text=True)
result = json.loads(output.read_text())
self.assertEqual(result["releaseNotes"], notes)
self.assertEqual(result["releaseName"], "Desktop release")
self.assertEqual(result["tagName"], "v1.6.1-20261002")
self.assertNotIn("platforms", result)
if __name__ == "__main__":
unittest.main()
+157
View File
@@ -0,0 +1,157 @@
"""Exercise CI Xmake selection with isolated executable and Actions-output mocks."""
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
SCRIPT = Path(__file__).resolve().parents[1] / "actions/ensure-xmake/check-version.sh"
BASH = shutil.which("bash")
@unittest.skipUnless(BASH, "Bash is required to exercise the CI version check")
class XmakeVersionCheckTest(unittest.TestCase):
def check(self, version_output=None, *, minimum="3.1.1", status=0, arguments=()):
with tempfile.TemporaryDirectory(prefix="crossdesk-xmake-check-") as directory:
root = Path(directory)
output_file = root / "github-output"
output_file.write_text("existing-output=preserved\n", encoding="utf-8")
arguments_file = root / "arguments"
if version_output is not None:
executable = root / "xmake"
executable.write_text(
"#!/bin/sh\n"
'printf "%s\\n" "$@" > "$XMAKE_TEST_ARGUMENTS"\n'
'printf "%s" "$XMAKE_TEST_OUTPUT"\n'
'exit "$XMAKE_TEST_STATUS"\n',
encoding="utf-8",
)
executable.chmod(0o755)
environment = {
**os.environ,
# The checker only needs shell builtins. Isolating PATH also
# guarantees that missing-tool tests cannot find a real xmake.
"PATH": str(root),
"GITHUB_OUTPUT": str(output_file),
"XMAKE_TEST_ARGUMENTS": str(arguments_file),
"XMAKE_TEST_OUTPUT": version_output or "",
"XMAKE_TEST_STATUS": str(status),
}
if minimum is None:
environment.pop("XMAKE_MIN_VERSION", None)
else:
environment["XMAKE_MIN_VERSION"] = minimum
result = subprocess.run(
[BASH, str(SCRIPT), *arguments],
env=environment,
capture_output=True,
text=True,
check=False,
)
outputs = dict(
line.split("=", 1)
for line in output_file.read_text(encoding="utf-8").splitlines()
)
invocation = (
arguments_file.read_text(encoding="utf-8").splitlines()
if arguments_file.exists() else None
)
self.assertEqual(outputs["existing-output"], "preserved")
return result, outputs, invocation
def test_keeps_minimum_and_newer_versions(self):
for version in ("3.1.1", "3.1.2", "3.1.10", "3.2.0", "3.10.0", "4.0.0"):
with self.subTest(version=version):
result, outputs, invocation = self.check(f"xmake v{version}\n")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(outputs["needs-upgrade"], "false")
self.assertEqual(outputs["detected-version"], version)
self.assertEqual(invocation, ["--root", "--version"])
self.assertIn("Keeping installed Xmake", result.stdout)
def test_older_versions_require_upgrade(self):
for version in ("3.1.0", "3.0.99", "2.99.99"):
with self.subTest(version=version):
result, outputs, _ = self.check(f"xmake v{version}\n")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(outputs["needs-upgrade"], "true")
self.assertIn("Install Xmake 3.1.1 or newer", result.stdout)
def test_components_are_compared_numerically(self):
for installed, minimum, expected in (
("3.1.10", "3.1.9", "false"),
("3.1.9", "3.1.10", "true"),
("3.2.0", "3.1.99", "false"),
("3.1.99", "3.2.0", "true"),
("3.01.009", "3.1.9", "false"),
("3.1.999999999999999999999", "3.1.9", "false"),
):
with self.subTest(installed=installed, minimum=minimum):
result, outputs, _ = self.check(f"xmake v{installed}", minimum=minimum)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(outputs["needs-upgrade"], expected)
def test_parses_ansi_colors_build_suffix_and_windows_line_endings(self):
result, outputs, _ = self.check(
"Xmake banner\r\n"
"\x1b[1;38;5;10mxmake\x1b[0m v\x1b[1m3.1.10\x1b[0m+HEAD.abcdef, A build utility\r\n"
)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(outputs["needs-upgrade"], "false")
self.assertEqual(outputs["detected-version"], "3.1.10")
def test_missing_broken_and_unrecognizable_tools_require_upgrade(self):
cases = (
(None, 0),
("xmake v9.9.9\n", 17),
("", 0),
("xmake version unknown\n", 0),
("xmake v3.1\n", 0),
("xmake v3.1.1invalid\n", 0),
("xmake v3.1.1-rc.1\n", 0),
("otherxmake v9.9.9\n", 0),
)
for output, status in cases:
with self.subTest(output=output, status=status):
result, outputs, _ = self.check(output, status=status)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(outputs["needs-upgrade"], "true")
self.assertEqual(outputs["detected-version"], "")
self.assertIn("Install Xmake 3.1.1 or newer", result.stdout)
def test_verification_fails_when_install_did_not_provide_required_version(self):
for output, status in ((None, 0), ("xmake v3.1.0", 0), ("unknown", 0), ("xmake v3.1.1", 5)):
with self.subTest(output=output, status=status):
result, outputs, _ = self.check(output, status=status, arguments=("--verify",))
self.assertEqual(result.returncode, 1)
self.assertEqual(outputs["needs-upgrade"], "true")
self.assertIn("Xmake verification failed", result.stderr)
self.assertIn("3.1.1 or newer", result.stderr)
def test_verification_accepts_newer_version(self):
result, outputs, _ = self.check("xmake v4.0.0", arguments=("--verify",))
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(outputs["needs-upgrade"], "false")
def test_invalid_minimum_fails_before_running_xmake(self):
for minimum in (None, "", "3.1", "v3.1.1", "3.1.1+HEAD", "3.1.1\n", "3.a.1"):
with self.subTest(minimum=minimum):
result, outputs, invocation = self.check("xmake v3.1.1", minimum=minimum)
self.assertEqual(result.returncode, 2)
self.assertNotIn("needs-upgrade", outputs)
self.assertIsNone(invocation)
self.assertIn("XMAKE_MIN_VERSION", result.stderr)
def test_unknown_arguments_fail_before_running_xmake(self):
result, outputs, invocation = self.check("xmake v3.1.1", arguments=("--install",))
self.assertEqual(result.returncode, 2)
self.assertNotIn("needs-upgrade", outputs)
self.assertIsNone(invocation)
self.assertIn("Usage:", result.stderr)
if __name__ == "__main__":
unittest.main()
+128
View File
@@ -0,0 +1,128 @@
#!/usr/bin/env python3
"""Merge a release's server downloads into the shared version.json."""
import argparse
import datetime
import json
from pathlib import Path
import re
DOWNLOAD_BASE = "https://downloads.crossdesk.cn/"
ARTIFACTS = {
"windows-x64": ("win-x64", "exe"),
"windows-x64-portable": ("win-x64-portable", "zip"),
"macos-x64": ("macos-x64", "pkg"),
"macos-arm64": ("macos-arm64", "pkg"),
"linux-amd64": ("linux-amd64", "deb"),
"linux-arm64": ("linux-arm64", "deb"),
"linux-amd64-virtual-desktop-xfce": ("virtual-desktop-xfce-linux-amd64", "deb"),
"linux-arm64-virtual-desktop-xfce": ("virtual-desktop-xfce-linux-arm64", "deb"),
"ios-arm64": ("ios-arm64-unsigned", "zip"),
"android-arm64": ("android-arm64(?:-unsigned)?", "apk"),
}
def version_info(version, fallback_date=None):
version = version.removeprefix("v")
base = r"[0-9]+(?:\.[0-9]+){1,3}"
for pattern in (
rf"(?P<base>{base})-(?P<patch>[0-9]+)-(?P<date>[0-9]{{8}})",
rf"(?P<base>{base})-(?P<date>[0-9]{{8}})(?:-(?P<patch>[0-9]+))?",
rf"(?P<base>{base})(?:-(?P<patch>[0-9]+))?",
):
match = re.fullmatch(pattern, version)
if match:
fields = match.groupdict()
date = fields.get("date")
release_date = (datetime.datetime.strptime(date, "%Y%m%d").date().isoformat()
if date else fallback_date)
if not release_date:
raise ValueError(f"Release date is missing for {version}")
datetime.date.fromisoformat(release_date)
return {"latest_version": version, "version": version,
"releaseDate": release_date, "patch": int(fields.get("patch") or 0)}
raise ValueError(f"Invalid release version: {version}")
def artifact_downloads(directory):
downloads = {}
for path in sorted(Path(directory).iterdir()):
if not path.is_file():
continue
for key, (prefix, extension) in ARTIFACTS.items():
match = re.fullmatch(rf"crossdesk-{prefix}-v([0-9][0-9.\-]*)\.{extension}", path.name)
if not match:
continue
metadata = version_info(match[1])
if key in downloads:
previous = downloads[key]
if (key != "android-arm64" or previous["version"] != metadata["version"]
or ("-unsigned-" in previous["filename"]) == ("-unsigned-" in path.name)):
raise ValueError(f"Multiple release artifacts for {key}")
# Older releases may retain their unsigned APK after adding a signed one.
if "-unsigned-" in path.name:
continue
downloads[key] = {"url": DOWNLOAD_BASE + path.name, "filename": path.name,
"version": metadata["version"], "releaseDate": metadata["releaseDate"]}
break
if not downloads:
raise ValueError("No supported release artifacts found")
return downloads
def merge_release(current, tag, name, notes, downloads, published_date=None):
if not isinstance(current, dict) or not isinstance(current.get("downloads"), dict):
raise ValueError("Current version.json must contain a downloads object")
mobile = re.fullmatch(r"(ios|android)-(v.+)", tag)
if mobile:
platform, version = mobile.groups()
expected_key = f"{platform}-arm64"
if set(downloads) != {expected_key}:
raise ValueError(f"{tag} must contain only the {expected_key} release artifact")
metadata = version_info(version, published_date)
if downloads[expected_key]["version"] != metadata["version"]:
raise ValueError("Mobile source tag does not match the artifact version")
else:
if not tag.startswith("v"):
raise ValueError(f"Expected a version tag, got {tag!r}")
metadata = version_info(tag, published_date)
result = dict(current)
result.pop("platforms", None)
result["downloads"] = {**current["downloads"], **downloads}
if not mobile:
result.update({**metadata, "releaseName": name, "releaseNotes": notes, "tagName": tag})
return result
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--current", required=True, type=Path)
parser.add_argument("--output", required=True, type=Path)
parser.add_argument("--artifacts", required=True, type=Path)
parser.add_argument("--tag")
parser.add_argument("--name")
parser.add_argument("--notes", type=Path)
parser.add_argument("--release-json", type=Path)
args = parser.parse_args()
if args.release_json:
release = json.loads(args.release_json.read_text())
tag = release["tagName"]
name = release.get("name") or tag
notes = release.get("body") or ""
published_date = (release.get("publishedAt") or "").split("T")[0] or None
else:
if not args.tag or not args.name or not args.notes:
parser.error("Supply --release-json or --tag, --name and --notes")
tag, name, notes = args.tag, args.name, args.notes.read_text()
published_date = None
current = json.loads(args.current.read_text())
downloads = artifact_downloads(args.artifacts)
result = merge_release(current, tag, name, notes, downloads, published_date)
args.output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n")
print(f"Updated {tag}: {', '.join(downloads)}")
if __name__ == "__main__":
main()
+254
View File
@@ -0,0 +1,254 @@
name: Build Android
on:
workflow_dispatch:
inputs:
patch:
description: "Optional patch number, matching the main build workflow."
required: false
type: string
default: "0"
workflow_call:
inputs:
source_tag:
description: "Existing source tag for a standalone Android release."
required: false
type: string
default: ""
patch:
description: "Optional patch number from the main build workflow."
required: false
type: string
default: "0"
outputs:
version:
description: "Android artifact version; combined releases match the desktop tag."
value: ${{ jobs.build.outputs.version }}
pull_request:
paths:
- ".github/workflows/build-android.yml"
- ".github/workflows/build.yml"
- ".github/workflows/release-mobile.yml"
- ".github/workflows/sign-android.yml"
- ".gitmodules"
- "LICENSE"
- "PRIVACY.md"
- "apps/android/**"
- "apps/ios/CrossDeskMobile/Resources/ThirdPartyLicenses.json"
- "apps/ios/licenses/**"
- "apps/ios/scripts/generate_third_party_licenses.py"
- "deps/submodules/minirtc"
- "libs/wire/**"
permissions:
contents: read
jobs:
build:
name: Build on Android (arm64)
runs-on: ubuntu-24.04
timeout-minutes: 120
outputs:
version: ${{ steps.package.outputs.version }}
env:
# Exercise the minimum supported version; local builds may use newer Xmake.
XMAKE_MIN_VERSION: "3.1.1"
CROSSDESK_SOURCE_TAG: ${{ inputs.source_tag || '' }}
CROSSDESK_RELEASE_BUILD: ${{ inputs.source_tag && 'YES' || 'NO' }}
steps:
- name: Checkout code
uses: actions/checkout@v5
with:
fetch-depth: 0
ref: ${{ inputs.source_tag || github.ref }}
submodules: recursive
persist-credentials: false
- name: Set up Java
uses: actions/setup-java@v5
with:
distribution: temurin
java-version: "17"
- name: Set up Python
uses: actions/setup-python@v6
with:
python-version: "3.13"
cache: pip
# Python build dependencies are declared in this workflow. This file
# also exists when source_tag checks out an older Android release.
cache-dependency-path: .github/workflows/build-android.yml
- name: Install native build tools
run: |
crossdesk_missing_packages=()
for crossdesk_package in build-essential cmake ninja-build pkg-config autoconf automake libtool nasm; do
if [[ "$(dpkg-query -W -f='${Status}' "${crossdesk_package}" 2>/dev/null || true)" != "install ok installed" ]]; then
crossdesk_missing_packages+=("${crossdesk_package}")
fi
done
if (( ${#crossdesk_missing_packages[@]} )); then
sudo apt-get update
sudo apt-get install -y --no-install-recommends "${crossdesk_missing_packages[@]}"
fi
python3 -m pip install setuptools wheel
# Use an isolated SDK directory so the cache contains only this toolchain,
# rather than every SDK/NDK version preinstalled on the runner.
- name: Select Android SDK directory
run: |
echo "ANDROID_HOME=${RUNNER_TEMP}/crossdesk-android-sdk" >> "${GITHUB_ENV}"
echo "ANDROID_SDK_ROOT=${RUNNER_TEMP}/crossdesk-android-sdk" >> "${GITHUB_ENV}"
- name: Restore Android SDK
id: android-sdk-cache
uses: actions/cache/restore@v5
with:
path: ${{ env.ANDROID_HOME }}
key: ${{ runner.os }}-${{ runner.arch }}-ubuntu24.04-android-sdk-v1-cli12266719-api36-build36.0.0-ndk28.2.13676358
- name: Set up Android SDK
if: steps.android-sdk-cache.outputs.cache-hit != 'true'
uses: android-actions/setup-android@v3
with:
cmdline-tools-version: "12266719"
log-accepted-android-sdk-licenses: false
packages: "platform-tools platforms;android-36 build-tools;36.0.0 ndk;28.2.13676358"
# Save immediately after installation, even if a later APK build fails.
- name: Save Android SDK
if: steps.android-sdk-cache.outputs.cache-hit != 'true'
uses: actions/cache/save@v5
with:
path: ${{ env.ANDROID_HOME }}
key: ${{ steps.android-sdk-cache.outputs.cache-primary-key }}
- name: Add Android tools to PATH
run: |
echo "${ANDROID_HOME}/cmdline-tools/16.0/bin" >> "${GITHUB_PATH}"
echo "${ANDROID_HOME}/platform-tools" >> "${GITHUB_PATH}"
- name: Install xmake
uses: xmake-io/github-action-setup-xmake@v1
with:
xmake-version: ${{ env.XMAKE_MIN_VERSION }}
actions-cache-folder: .xmake-toolchain-cache
actions-cache-key: ${{ runner.os }}-${{ runner.arch }}-ubuntu24.04-android-xmake${{ env.XMAKE_MIN_VERSION }}
- name: Cache Xmake package repository
uses: actions/cache@v5
with:
path: apps/android/.native/global/.xmake/repositories/xmake-repo
key: ${{ runner.os }}-${{ runner.arch }}-android-xmake-repo-v1-${{ hashFiles('apps/android/scripts/build_native.py') }}
# Cache installed packages only. build_native.py checks Xmake >= 3.1.1 and pins
# its own package repository; never reuse another platform's build/config.
- name: Cache native dependencies
uses: actions/cache@v5
with:
path: apps/android/.native/packages
key: ${{ runner.os }}-${{ runner.arch }}-android-arm64-native-v1-${{ hashFiles('apps/android/scripts/build_native.py', 'apps/android/native/xmake.lua', 'deps/submodules/minirtc/xmake.lua', 'deps/submodules/minirtc/thirdparty/**') }}
- name: Set up Gradle
uses: gradle/actions/setup-gradle@v6
with:
cache-provider: basic
cache-read-only: ${{ github.event_name == 'pull_request' }}
- name: Verify shared license catalog
run: python3 -B apps/ios/scripts/generate_third_party_licenses.py
- name: Resolve Android version
shell: python
env:
PATCH_NUMBER: ${{ inputs.patch || '0' }}
run: |
import datetime
import os
from pathlib import Path
import re
import runpy
resolver = Path("apps/android/scripts/release_version.py")
if resolver.exists():
runpy.run_path(str(resolver), run_name="__main__")
else:
# Older standalone releases predate the resolver and Gradle properties.
# Keep their original package version when retrying an existing tag.
tag = os.environ["CROSSDESK_SOURCE_TAG"]
match = re.fullmatch(r"android-v([0-9]+\.[0-9]+\.[0-9]+)-([0-9]{8})", tag)
config = Path("apps/android/app/build.gradle").read_text()
name = re.search(r"versionName\s+'([^']+)'", config)
code = re.search(r"versionCode\s+([0-9]+)", config)
if not match or not name or not code or match[1] != name[1]:
raise ValueError("Legacy Android sources require a matching standalone release tag")
datetime.datetime.strptime(match[2], "%Y%m%d")
with open(os.environ["GITHUB_ENV"], "a") as stream:
stream.write(f"ANDROID_VERSION_NAME={name[1]}\nANDROID_VERSION_CODE={code[1]}\n"
f"ANDROID_ARTIFACT_VERSION={tag.removeprefix('android-')}\n")
- name: Build APKs
working-directory: apps/android
run: |
./gradlew --no-daemon --stacktrace \
-PcrossdeskVersionName="${ANDROID_VERSION_NAME}" \
-PcrossdeskVersionCode="${ANDROID_VERSION_CODE}" \
:app:assembleDebug :app:assembleRelease
- name: Verify APKs
working-directory: apps/android
run: |
for APK in app/build/outputs/apk/debug/app-debug.apk app/build/outputs/apk/release/app-release-unsigned.apk; do
python3 -B test/verify_apk.py "${APK}" \
--aapt2 "${ANDROID_HOME}/build-tools/36.0.0/aapt2" \
--version-name "${ANDROID_VERSION_NAME}" --version-code "${ANDROID_VERSION_CODE}"
done
"${ANDROID_HOME}/build-tools/36.0.0/apksigner" verify app/build/outputs/apk/debug/app-debug.apk
- name: Package APKs with the resolved Android version
id: package
shell: python
run: |
import json
import os
from pathlib import Path
import shutil
apk_dir = Path("apps/android/app/build/outputs/apk")
version = os.environ["ANDROID_ARTIFACT_VERSION"]
for variant in ("debug", "release"):
metadata = json.loads((apk_dir / variant / "output-metadata.json").read_text())
for element in metadata["elements"]:
if (element["versionName"] != os.environ["ANDROID_VERSION_NAME"] or
element["versionCode"] != int(os.environ["ANDROID_VERSION_CODE"])):
raise ValueError(f"Unexpected Android {variant} version: {element}")
output = Path(os.environ["RUNNER_TEMP"]) / "crossdesk-android"
for variant, source in (
("unsigned", "release/app-release-unsigned.apk"),
("debug", "debug/app-debug.apk"),
):
destination = output / variant
destination.mkdir(parents=True, exist_ok=True)
shutil.copyfile(apk_dir / source, destination / f"crossdesk-android-arm64-{variant}-{version}.apk")
with open(os.environ["GITHUB_OUTPUT"], "a") as stream:
stream.write(f"version={version}\n")
with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as stream:
stream.write(f"Android {version}: arm64, API 26+, 16 KB aligned.\n\n"
"Debug APK uses an ephemeral CI debug key; it is for testing and may require uninstalling an existing build. "
"The Release APK is unsigned and needs your own signing before installation.\n\n"
"Debug and Release APKs built and packaged; APK checks passed.\n")
- name: Upload unsigned Release APK
uses: actions/upload-artifact@v6
with:
name: crossdesk-android-arm64-unsigned-${{ steps.package.outputs.version }}
path: ${{ runner.temp }}/crossdesk-android/unsigned/*.apk
if-no-files-found: error
- name: Upload Debug APK
uses: actions/upload-artifact@v6
with:
name: crossdesk-android-arm64-debug-${{ steps.package.outputs.version }}
path: ${{ runner.temp }}/crossdesk-android/debug/*.apk
if-no-files-found: error
retention-days: 14
+272
View File
@@ -0,0 +1,272 @@
name: Build iOS
on:
workflow_dispatch:
inputs:
patch:
description: "Optional patch number, matching the main build workflow."
required: false
type: string
default: "0"
workflow_call:
inputs:
source_tag:
description: "Existing source tag for a standalone iOS release."
required: false
type: string
default: ""
patch:
description: "Optional patch number from the main build workflow."
required: false
type: string
default: "0"
outputs:
version:
description: "iOS artifact version; combined releases match the desktop tag."
value: ${{ jobs.build.outputs.version }}
pull_request:
paths:
- ".github/workflows/build-ios.yml"
- ".github/workflows/build.yml"
- ".github/workflows/release-mobile.yml"
- ".gitmodules"
- "LICENSE"
- "apps/ios/**"
- "deps/submodules/minirtc"
- "libs/wire/**"
- "xmake.lua"
permissions:
contents: read
jobs:
build:
name: Build on iOS (arm64)
runs-on: macos-26
timeout-minutes: 120
outputs:
version: ${{ steps.ios_version.outputs.version }}
env:
GITHUB_TOKEN: ${{ github.token }}
CROSSDESK_SOURCE_TAG: ${{ inputs.source_tag || '' }}
IOS_DEPLOYMENT_TARGET: "16.0"
EXPECTED_IOS_SDK: "26.5"
# Exercise the minimum supported version; local builds may use newer Xmake.
XMAKE_MIN_VERSION: "3.1.1"
XMAKE_REPO_REVISION: "121109352da272cd1a3d4ed52f2dcda34f839955"
steps:
- name: Extract version number
shell: bash
env:
PATCH_NUMBER: ${{ inputs.patch || '0' }}
run: |
VERSION_REF="${CROSSDESK_SOURCE_TAG:-${GITHUB_REF##*/}}"
VERSION_REF="${VERSION_REF#ios-}"
VERSION_BASE="${VERSION_REF#v}"
BUILD_DATE=$(TZ=Asia/Shanghai date +%Y%m%d)
if [[ ! "${PATCH_NUMBER}" =~ ^[0-9]+$ ]]; then
PATCH_NUMBER=0
fi
if [[ "${VERSION_BASE}" =~ ^([0-9]+(\.[0-9]+){1,3})-([0-9]+)-([0-9]{8})$ ]]; then
VERSION_BASE="${BASH_REMATCH[1]}"
PATCH_NUMBER="${BASH_REMATCH[3]}"
BUILD_DATE="${BASH_REMATCH[4]}"
elif [[ "${VERSION_BASE}" =~ ^([0-9]+(\.[0-9]+){1,3})-([0-9]{8})-([0-9]+)$ ]]; then
VERSION_BASE="${BASH_REMATCH[1]}"
BUILD_DATE="${BASH_REMATCH[3]}"
PATCH_NUMBER="${BASH_REMATCH[4]}"
elif [[ "${VERSION_BASE}" =~ ^([0-9]+(\.[0-9]+){1,3})-([0-9]{8})$ ]]; then
VERSION_BASE="${BASH_REMATCH[1]}"
BUILD_DATE="${BASH_REMATCH[3]}"
elif [[ "${VERSION_BASE}" =~ ^([0-9]+(\.[0-9]+){1,3})-([0-9]+)$ && "${PATCH_NUMBER}" == "0" ]]; then
VERSION_BASE="${BASH_REMATCH[1]}"
PATCH_NUMBER="${BASH_REMATCH[3]}"
fi
if [[ "${PATCH_NUMBER}" != "0" ]]; then
VERSION_NUM="v${VERSION_BASE}-${PATCH_NUMBER}-${BUILD_DATE}"
else
VERSION_NUM="v${VERSION_BASE}-${BUILD_DATE}"
fi
echo "VERSION_NUM=${VERSION_NUM}" >> "${GITHUB_ENV}"
echo "VERSION_NUM=${VERSION_NUM}"
- name: Select Xcode 26.6
shell: bash
run: |
sudo xcode-select -s /Applications/Xcode_26.6.app/Contents/Developer
xcodebuild -version
SDK_VERSION="$(xcrun --sdk iphoneos --show-sdk-version)"
if [[ "${SDK_VERSION}" != "${EXPECTED_IOS_SDK}" ]]; then
echo "Unexpected iOS SDK: expected ${EXPECTED_IOS_SDK}, got ${SDK_VERSION}" >&2
exit 1
fi
- name: Checkout code
uses: actions/checkout@v5
with:
fetch-depth: 0
ref: ${{ inputs.source_tag || github.ref }}
- name: Select corresponding source tag
shell: bash
run: |
if [[ -n "${CROSSDESK_SOURCE_TAG}" ]]; then
echo "CROSSDESK_RELEASE_BUILD=YES" >> "${GITHUB_ENV}"
elif [[ "${GITHUB_REF_TYPE}" == "tag" ]]; then
echo "CROSSDESK_SOURCE_TAG=${GITHUB_REF_NAME}" >> "${GITHUB_ENV}"
echo "CROSSDESK_RELEASE_BUILD=YES" >> "${GITHUB_ENV}"
fi
- name: Resolve iOS version
id: ios_version
shell: bash
run: |
if [[ "${CROSSDESK_SOURCE_TAG}" == v* ]]; then
# Combined releases share the desktop version, including the date
# and optional hotfix suffix in the artifact filename.
IOS_VERSION_BASE="${VERSION_NUM#v}"
IOS_VERSION_BASE="${IOS_VERSION_BASE%%-*}"
else
IOS_VERSION_BASE="$(xcodebuild \
-project apps/ios/CrossDeskMobile.xcodeproj \
-scheme CrossDeskMobile \
-configuration Release \
-destination 'generic/platform=iOS' \
-showBuildSettings CODE_SIGNING_ALLOWED=NO | \
awk '$1 == "MARKETING_VERSION" && $2 == "=" { print $3 }')"
VERSION_NUM="v${IOS_VERSION_BASE}-${VERSION_NUM##*-}"
fi
if [[ ! "${IOS_VERSION_BASE}" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "Invalid iOS marketing version: ${IOS_VERSION_BASE}" >&2
exit 1
fi
if [[ "${CROSSDESK_SOURCE_TAG}" == ios-v* && "${CROSSDESK_SOURCE_TAG#ios-}" != "${VERSION_NUM}" ]]; then
echo "iOS source tag does not match the app version: ${CROSSDESK_SOURCE_TAG} vs ${VERSION_NUM}" >&2
exit 1
fi
echo "IOS_VERSION_BASE=${IOS_VERSION_BASE}" >> "${GITHUB_ENV}"
echo "VERSION_NUM=${VERSION_NUM}" >> "${GITHUB_ENV}"
echo "version=${VERSION_NUM}" >> "${GITHUB_OUTPUT}"
- name: Initialize submodules
run: git submodule update --init --recursive
- name: Cache xmake dependencies
uses: actions/cache@v5
with:
path: apps/ios/.xmake/packages
key: "${{ runner.os }}-xmake${{ env.XMAKE_MIN_VERSION }}-deps-ios-arm64-source-v1-xcode26.6-xrepo1211093-min16-${{ github.run_id }}"
restore-keys: |
${{ runner.os }}-xmake${{ env.XMAKE_MIN_VERSION }}-deps-ios-arm64-source-v1-xcode26.6-xrepo1211093-min16-
- name: Set up Python
uses: actions/setup-python@v6
with:
python-version: "3.13"
- name: Verify iOS license catalog
run: python3 -B apps/ios/scripts/generate_third_party_licenses.py
- name: Install xmake
uses: xmake-io/github-action-setup-xmake@v1
with:
xmake-version: "${{ env.XMAKE_MIN_VERSION }}"
- name: Verify minimum xmake version
shell: bash
run: |
xmake --version | tee "${RUNNER_TEMP}/xmake-version.txt"
python3 -B apps/ios/scripts/generate_third_party_licenses.py \
--xmake-version "${RUNNER_TEMP}/xmake-version.txt"
- name: Pin xmake package repository
shell: bash
run: |
xmake repo -u
XMAKE_REPO_DIR="${HOME}/.xmake/repositories/xmake-repo"
git -C "${XMAKE_REPO_DIR}" fetch --depth=1 origin "${XMAKE_REPO_REVISION}"
git -C "${XMAKE_REPO_DIR}" checkout --detach "${XMAKE_REPO_REVISION}"
test "$(git -C "${XMAKE_REPO_DIR}" rev-parse HEAD)" = "${XMAKE_REPO_REVISION}"
- name: Build CrossDesk Mobile
shell: bash
run: |
DERIVED_DATA="${RUNNER_TEMP}/CrossDeskMobileDerivedData"
echo "DERIVED_DATA=${DERIVED_DATA}" >> "${GITHUB_ENV}"
xcodebuild \
-project apps/ios/CrossDeskMobile.xcodeproj \
-scheme CrossDeskMobile \
-configuration Release \
-destination 'generic/platform=iOS' \
-derivedDataPath "${DERIVED_DATA}" \
CODE_SIGNING_ALLOWED=NO \
CODE_SIGNING_REQUIRED=NO \
COMPILER_INDEX_STORE_ENABLE=NO \
MARKETING_VERSION="${IOS_VERSION_BASE}" \
IPHONEOS_DEPLOYMENT_TARGET="${IOS_DEPLOYMENT_TARGET}" \
build
- name: Verify CrossDesk Mobile
shell: bash
run: |
APP_PATH="${DERIVED_DATA}/Build/Products/Release-iphoneos/CrossDeskMobile.app"
EXECUTABLE_PATH="${APP_PATH}/CrossDeskMobile"
INFO_PLIST="${APP_PATH}/Info.plist"
if [[ ! -x "${EXECUTABLE_PATH}" ]]; then
echo "CrossDeskMobile executable is missing from ${APP_PATH}" >&2
exit 1
fi
xcrun lipo "${EXECUTABLE_PATH}" -verify_arch arm64
APP_VERSION=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' "${INFO_PLIST}")
if [[ "${APP_VERSION}" != "${IOS_VERSION_BASE}" ]]; then
echo "Unexpected iOS app version: expected ${IOS_VERSION_BASE}, got ${APP_VERSION}" >&2
exit 1
fi
MINIMUM_OS=$(/usr/libexec/PlistBuddy -c 'Print :MinimumOSVersion' "${INFO_PLIST}")
if [[ "${MINIMUM_OS}" != "${IOS_DEPLOYMENT_TARGET}" ]]; then
echo "Unexpected minimum iOS version: expected ${IOS_DEPLOYMENT_TARGET}, got ${MINIMUM_OS}" >&2
exit 1
fi
VERIFY_FLAGS=()
if [[ "${CROSSDESK_RELEASE_BUILD:-NO}" == "YES" ]]; then
VERIFY_FLAGS+=(--require-release)
fi
python3 apps/ios/scripts/verify_app_bundle.py "${APP_PATH}" "${VERIFY_FLAGS[@]}"
xcrun lipo -info "${EXECUTABLE_PATH}"
echo "Minimum iOS version: ${MINIMUM_OS}"
- name: Package CrossDesk Mobile
shell: bash
run: |
APP_PATH="${DERIVED_DATA}/Build/Products/Release-iphoneos/CrossDeskMobile.app"
PACKAGE_DIR="${RUNNER_TEMP}/crossdesk-ios-arm64-unsigned-${VERSION_NUM}"
PACKAGE_FILE="${GITHUB_WORKSPACE}/crossdesk-ios-arm64-unsigned-${VERSION_NUM}.zip"
mkdir -p "${PACKAGE_DIR}"
cp -R "${APP_PATH}" "${PACKAGE_DIR}/"
cp apps/ios/licenses/sources.json "${PACKAGE_DIR}/ThirdPartySources.json"
cp apps/ios/licenses/OPEN_SOURCE_NOTICE.txt "${PACKAGE_DIR}/OPEN_SOURCE_NOTICE.txt"
cp "${APP_PATH}/SourceMetadata.json" "${PACKAGE_DIR}/SourceMetadata.json"
DSYM_PATH="${DERIVED_DATA}/Build/Products/Release-iphoneos/CrossDeskMobile.app.dSYM"
if [[ -d "${DSYM_PATH}" ]]; then
cp -R "${DSYM_PATH}" "${PACKAGE_DIR}/"
fi
ditto -c -k --sequesterRsrc --keepParent "${PACKAGE_DIR}" "${PACKAGE_FILE}"
echo "PACKAGE_FILE=${PACKAGE_FILE}" >> "${GITHUB_ENV}"
- name: Upload build artifact
uses: actions/upload-artifact@v6
with:
name: crossdesk-ios-arm64-unsigned-${{ env.VERSION_NUM }}
path: ${{ env.PACKAGE_FILE }}
if-no-files-found: error
+157
View File
@@ -0,0 +1,157 @@
name: Build Linux Build Image
on:
push:
branches:
- ci/linux-build-image
paths:
- .dockerignore
- .gitmodules
- .github/workflows/build-linux-image.yml
- docker/linux-build/**
- xmake.lua
- xmake/**
- deps/thirdparty/**
- deps/submodules/xmake.lua
- deps/submodules/minirtc
- deps/submodules/minirtc/xmake.lua
- deps/submodules/minirtc/thirdparty/**
workflow_dispatch:
permissions:
contents: read
concurrency:
group: linux-build-image-${{ github.ref }}
cancel-in-progress: true
env:
IMAGE_NAME: crossdesk/ubuntu20.04
STACK_TAG: buildenv-cuda12.6.3-gcc10-cmake3.31.6-pipewire0.3.48-xmake3.1.1-rust1.92.0
CMAKE_VERSION: 3.31.6
XMAKE_VERSION: 3.1.1
RUST_VERSION: 1.92.0
RUSTUP_VERSION: 1.28.2
jobs:
build:
name: Build candidate (${{ matrix.arch }})
runs-on: ${{ matrix.runner }}
timeout-minutes: 180
strategy:
fail-fast: false
matrix:
include:
- arch: amd64
platform: linux/amd64
runner: ubuntu-24.04
base_image: nvidia/cuda:12.6.3-devel-ubuntu20.04
- arch: arm64
platform: linux/arm64
runner: ubuntu-24.04-arm
base_image: ubuntu:20.04
steps:
- name: Set candidate tag
id: image
run: |
CANDIDATE_TAG="${IMAGE_NAME}:${STACK_TAG}-${GITHUB_SHA}-${{ matrix.arch }}"
echo "CANDIDATE_TAG=${CANDIDATE_TAG}" >> "${GITHUB_ENV}"
echo "candidate=${CANDIDATE_TAG}" >> "${GITHUB_OUTPUT}"
- name: Checkout source
uses: actions/checkout@v5
with:
submodules: recursive
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Log in to Docker Hub
uses: docker/login-action@v4
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Build and push candidate
uses: docker/build-push-action@v7
with:
context: .
file: docker/linux-build/Dockerfile
platforms: ${{ matrix.platform }}
push: true
pull: true
tags: ${{ steps.image.outputs.candidate }}
cache-from: type=registry,ref=${{ env.IMAGE_NAME }}:${{ env.STACK_TAG }}
cache-to: type=inline
provenance: false
sbom: false
build-args: |
BASE_IMAGE=${{ matrix.base_image }}
CMAKE_VERSION=${{ env.CMAKE_VERSION }}
XMAKE_VERSION=${{ env.XMAKE_VERSION }}
RUST_VERSION=${{ env.RUST_VERSION }}
RUSTUP_VERSION=${{ env.RUSTUP_VERSION }}
verify:
name: Verify candidate (${{ matrix.arch }})
needs: build
runs-on: ${{ matrix.runner }}
timeout-minutes: 30
strategy:
fail-fast: false
matrix:
include:
- arch: amd64
runner: ubuntu-24.04
- arch: arm64
runner: ubuntu-24.04-arm
steps:
- name: Set candidate tag
run: |
CANDIDATE_TAG="${IMAGE_NAME}:${STACK_TAG}-${GITHUB_SHA}-${{ matrix.arch }}"
echo "CANDIDATE_TAG=${CANDIDATE_TAG}" >> "${GITHUB_ENV}"
- name: Log in to Docker Hub
uses: docker/login-action@v4
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Verify tools, architecture, and Ubuntu baseline
run: |
docker pull "${CANDIDATE_TAG}"
docker run --rm \
--env EXPECTED_ARCH="${{ matrix.arch }}" \
"${CANDIDATE_TAG}" \
verify-crossdesk-build-image
publish:
name: Publish multi-arch image
needs: verify
runs-on: ubuntu-24.04
timeout-minutes: 20
steps:
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Log in to Docker Hub
uses: docker/login-action@v4
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Promote verified candidates
run: |
AMD64_IMAGE="${IMAGE_NAME}:${STACK_TAG}-${GITHUB_SHA}-amd64"
ARM64_IMAGE="${IMAGE_NAME}:${STACK_TAG}-${GITHUB_SHA}-arm64"
docker buildx imagetools create \
--tag "${IMAGE_NAME}:${STACK_TAG}" \
--tag "${IMAGE_NAME}:sha-${GITHUB_SHA}" \
--tag "${IMAGE_NAME}:latest" \
"${AMD64_IMAGE}" \
"${ARM64_IMAGE}"
- name: Inspect published manifest
run: |
docker buildx imagetools inspect "${IMAGE_NAME}:${STACK_TAG}"
+769
View File
@@ -0,0 +1,769 @@
name: Build and Release
on:
push:
branches:
- "**"
- "!ci/linux-build-image"
tags:
- "*"
- "!ios-v*"
- "!android-v*"
workflow_dispatch:
inputs:
patch:
description: "Hotfix patch number, for example 1 or 2. Use 0 for a normal build."
required: false
default: "0"
sign_windows_test:
description: "Submit the Windows installer to SignPath using test-signing."
required: false
type: boolean
default: false
permissions:
actions: read
contents: write
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
XMAKE_MIN_VERSION: "3.1.1"
jobs:
build-linux:
name: Build Linux (${{ matrix.arch }})
runs-on: ${{ matrix.runner }}
strategy:
matrix:
include:
- arch: amd64
runner: ubuntu-24.04
# Keep using the published dependency image; upgrade Xmake if needed.
image: crossdesk/ubuntu20.04:buildenv-cuda12.6.3-gcc10-cmake3.31.6-pipewire0.3.48-xmake3.0.9-rust1.92.0
package_script: ./apps/desktop/scripts/linux/pkg_amd64.sh
- arch: arm64
runner: ubuntu-24.04-arm
image: crossdesk/ubuntu20.04:buildenv-cuda12.6.3-gcc10-cmake3.31.6-pipewire0.3.48-xmake3.0.9-rust1.92.0
package_script: ./apps/desktop/scripts/linux/pkg_arm64.sh
container:
image: ${{ matrix.image }}
options: --user root
steps:
- name: Extract version number
shell: bash
run: |
VERSION_REF="${GITHUB_REF##*/}"
VERSION_BASE="${VERSION_REF#v}"
PATCH_NUMBER="${{ github.event.inputs.patch }}"
BUILD_DATE_OVERRIDE=""
if [[ ! "${PATCH_NUMBER}" =~ ^[0-9]+$ ]]; then
PATCH_NUMBER=0
fi
if [[ "${VERSION_BASE}" =~ ^([0-9]+(\.[0-9]+){1,3})-([0-9]+)-([0-9]{8})$ ]]; then
VERSION_BASE="${BASH_REMATCH[1]}"
PATCH_NUMBER="${BASH_REMATCH[3]}"
BUILD_DATE_OVERRIDE="${BASH_REMATCH[4]}"
elif [[ "${VERSION_BASE}" =~ ^([0-9]+(\.[0-9]+){1,3})-([0-9]{8})-([0-9]+)$ ]]; then
VERSION_BASE="${BASH_REMATCH[1]}"
BUILD_DATE_OVERRIDE="${BASH_REMATCH[3]}"
PATCH_NUMBER="${BASH_REMATCH[4]}"
elif [[ "${VERSION_BASE}" =~ ^([0-9]+(\.[0-9]+){1,3})-([0-9]{8})$ ]]; then
VERSION_BASE="${BASH_REMATCH[1]}"
BUILD_DATE_OVERRIDE="${BASH_REMATCH[3]}"
elif [[ "${VERSION_BASE}" =~ ^([0-9]+(\.[0-9]+){1,3})-([0-9]+)$ && "${PATCH_NUMBER}" == "0" ]]; then
VERSION_BASE="${BASH_REMATCH[1]}"
PATCH_NUMBER="${BASH_REMATCH[3]}"
fi
echo "VERSION_BASE=${VERSION_BASE}" >> $GITHUB_ENV
echo "PATCH_NUMBER=${PATCH_NUMBER}" >> $GITHUB_ENV
echo "BUILD_DATE_OVERRIDE=${BUILD_DATE_OVERRIDE}" >> $GITHUB_ENV
- name: Set legal Debian version
shell: bash
run: |
BUILD_DATE="${BUILD_DATE_OVERRIDE}"
if [[ -z "${BUILD_DATE}" ]]; then
BUILD_DATE=$(TZ=Asia/Shanghai date +%Y%m%d)
fi
if [[ ! "${VERSION_BASE}" =~ ^[0-9] ]]; then
VERSION_BASE="0.0.0-${VERSION_BASE}"
fi
if [[ "${PATCH_NUMBER}" != "0" ]]; then
LEGAL_VERSION="v${VERSION_BASE}-${PATCH_NUMBER}-${BUILD_DATE}"
else
LEGAL_VERSION="v${VERSION_BASE}-${BUILD_DATE}"
fi
echo "LEGAL_VERSION=${LEGAL_VERSION}" >> $GITHUB_ENV
echo "BUILD_DATE=${BUILD_DATE}" >> $GITHUB_ENV
- name: Checkout code
uses: actions/checkout@v5
with:
submodules: recursive
- name: Ensure minimum Xmake version
uses: ./.github/actions/ensure-xmake
with:
minimum-version: ${{ env.XMAKE_MIN_VERSION }}
- name: Verify Linux build image
shell: bash
env:
EXPECTED_ARCH: ${{ matrix.arch }}
run: bash docker/linux-build/verify-build-image.sh
- name: Ensure Wayland build dependencies
shell: bash
run: |
if pkg-config --exists dbus-1 libdrm && \
test -f /opt/crossdesk-pipewire-sdk/include/pipewire-0.3/pipewire/pipewire.h && \
test -f /opt/crossdesk-pipewire-sdk/include/spa-0.2/spa/param/video/format-utils.h; then
exit 0
fi
apt-get update
apt-get install -y --no-install-recommends \
libdbus-1-dev \
libdrm-dev
rm -rf /var/lib/apt/lists/*
install-crossdesk-pipewire-sdk
pkg-config --exists dbus-1 libdrm
test -f /opt/crossdesk-pipewire-sdk/include/pipewire-0.3/pipewire/pipewire.h
test -f /opt/crossdesk-pipewire-sdk/include/spa-0.2/spa/param/video/format-utils.h
- name: Build CrossDesk
env:
CUDA_PATH: /usr/local/cuda
XMAKE_GLOBALDIR: /data
run: |
xmake f --CROSSDESK_VERSION=${LEGAL_VERSION} --USE_CUDA=true --USE_WAYLAND=true \
--cc=gcc-10 --cxx=g++-10 --root -y
xmake b -vy --root crossdesk
- name: Install Linux headless runtime dependencies
run: |
apt-get update
apt-get install -y --no-install-recommends xvfb xfce4 dbus
- name: Package
run: |
chmod +x ${{ matrix.package_script }}
${{ matrix.package_script }} ${LEGAL_VERSION}
- name: Verify Ubuntu 20.04 package dependency resolution
run: |
apt-get update
for PACKAGE in crossdesk crossdesk-virtual-desktop-xfce; do
apt-get install --simulate "${GITHUB_WORKSPACE}/${PACKAGE}-linux-${{ matrix.arch }}-${LEGAL_VERSION}.deb"
done
- name: Verify packaged Ubuntu 20.04 glibc baseline
run: |
for PACKAGE in crossdesk crossdesk-virtual-desktop-xfce; do
PACKAGE_FILE="${GITHUB_WORKSPACE}/${PACKAGE}-linux-${{ matrix.arch }}-${LEGAL_VERSION}.deb"
VERIFY_DIR="${RUNNER_TEMP}/${PACKAGE}-glibc-${{ matrix.arch }}"
install -d "${VERIFY_DIR}"
dpkg-deb --extract "${PACKAGE_FILE}" "${VERIFY_DIR}"
verify-crossdesk-glibc-baseline "${VERIFY_DIR}" 2.31
done
- name: Stage Linux release artifacts
shell: bash
run: |
mkdir -p linux-artifacts
for PACKAGE in crossdesk crossdesk-virtual-desktop-xfce; do
FILE="${PACKAGE}-linux-${{ matrix.arch }}-${LEGAL_VERSION}.deb"
if [[ ! -s "${FILE}" ]]; then
echo "::error::Missing or empty Linux package: ${FILE}"
exit 1
fi
cp "${FILE}" linux-artifacts/
done
- name: Upload artifact
uses: actions/upload-artifact@v6
with:
name: crossdesk-linux-${{ matrix.arch }}-${{ env.LEGAL_VERSION }}
# A single relative directory avoids container translation of multiline
# absolute paths and keeps both package filenames at the artifact root.
path: linux-artifacts/
if-no-files-found: error
# macOS
build-macos:
name: Build on macOS
runs-on: ${{ matrix.runner }}
env:
MACOSX_DEPLOYMENT_TARGET: "14.0"
EXPECTED_MACOS_SDK: "26.5"
strategy:
matrix:
include:
- arch: x64
binary_arch: x86_64
runner: macos-26-intel
cache-key: intel-macos26-xcode26.6-min14
out-dir: ./build/macosx/x86_64/release/crossdesk
package_script: ./apps/desktop/scripts/macos/pkg_x64.sh
- arch: arm64
binary_arch: arm64
runner: macos-26
cache-key: arm-macos26-xcode26.6-min14
out-dir: ./build/macosx/arm64/release/crossdesk
package_script: ./apps/desktop/scripts/macos/pkg_arm64.sh
steps:
- name: Extract version number
id: version
shell: bash
run: |
VERSION_REF="${GITHUB_REF##*/}"
VERSION_BASE="${VERSION_REF#v}"
BUILD_DATE=$(TZ=Asia/Shanghai date +%Y%m%d)
PATCH_NUMBER="${{ github.event.inputs.patch }}"
if [[ ! "${PATCH_NUMBER}" =~ ^[0-9]+$ ]]; then
PATCH_NUMBER=0
fi
if [[ "${VERSION_BASE}" =~ ^([0-9]+(\.[0-9]+){1,3})-([0-9]+)-([0-9]{8})$ ]]; then
VERSION_BASE="${BASH_REMATCH[1]}"
PATCH_NUMBER="${BASH_REMATCH[3]}"
BUILD_DATE="${BASH_REMATCH[4]}"
elif [[ "${VERSION_BASE}" =~ ^([0-9]+(\.[0-9]+){1,3})-([0-9]{8})-([0-9]+)$ ]]; then
VERSION_BASE="${BASH_REMATCH[1]}"
BUILD_DATE="${BASH_REMATCH[3]}"
PATCH_NUMBER="${BASH_REMATCH[4]}"
elif [[ "${VERSION_BASE}" =~ ^([0-9]+(\.[0-9]+){1,3})-([0-9]{8})$ ]]; then
VERSION_BASE="${BASH_REMATCH[1]}"
BUILD_DATE="${BASH_REMATCH[3]}"
elif [[ "${VERSION_BASE}" =~ ^([0-9]+(\.[0-9]+){1,3})-([0-9]+)$ && "${PATCH_NUMBER}" == "0" ]]; then
VERSION_BASE="${BASH_REMATCH[1]}"
PATCH_NUMBER="${BASH_REMATCH[3]}"
fi
if [[ "${PATCH_NUMBER}" != "0" ]]; then
VERSION_NUM="v${VERSION_BASE}-${PATCH_NUMBER}-${BUILD_DATE}"
else
VERSION_NUM="v${VERSION_BASE}-${BUILD_DATE}"
fi
echo "VERSION_NUM=${VERSION_NUM}" >> $GITHUB_ENV
echo "VERSION_NUM=${VERSION_NUM}"
echo "BUILD_DATE=${BUILD_DATE}" >> $GITHUB_ENV
echo "PATCH_NUMBER=${PATCH_NUMBER}" >> $GITHUB_ENV
- name: Select Xcode 26.6
shell: bash
run: |
sudo xcode-select -s /Applications/Xcode_26.6.app/Contents/Developer
xcodebuild -version
SDK_VERSION="$(xcrun --sdk macosx --show-sdk-version)"
if [[ "${SDK_VERSION}" != "${EXPECTED_MACOS_SDK}" ]]; then
echo "Unexpected macOS SDK: expected ${EXPECTED_MACOS_SDK}, got ${SDK_VERSION}" >&2
exit 1
fi
- name: Cache xmake dependencies
uses: actions/cache@v5
with:
path: ~/.xmake/packages
key: "${{ runner.os }}-xmake-deps-${{ matrix.cache-key }}-${{ github.run_id }}"
restore-keys: |
${{ runner.os }}-xmake-deps-${{ matrix.cache-key }}-
- name: Checkout code
uses: actions/checkout@v5
- name: Initialize submodules
run: git submodule update --init --recursive
- name: Ensure minimum Xmake version
uses: ./.github/actions/ensure-xmake
with:
minimum-version: ${{ env.XMAKE_MIN_VERSION }}
- name: Update xmake repositories
run: xmake repo -u
- name: Build CrossDesk
run: |
xmake f --target_minver=${MACOSX_DEPLOYMENT_TARGET} --CROSSDESK_VERSION=${VERSION_NUM} --USE_CUDA=false -vyD
xmake b -vy crossdesk
- name: Package CrossDesk app
run: |
chmod +x ${{ matrix.package_script }}
${{ matrix.package_script }} ${VERSION_NUM}
- name: Verify packaged app
shell: bash
run: |
PACKAGE_FILE="${GITHUB_WORKSPACE}/crossdesk-macos-${{ matrix.arch }}-${VERSION_NUM}.pkg"
VERIFY_DIR="$(mktemp -d "${RUNNER_TEMP}/crossdesk-macos-pkg.XXXXXX")"
trap 'rm -rf "${VERIFY_DIR}"' EXIT
pkgutil --expand-full "${PACKAGE_FILE}" "${VERIFY_DIR}/expanded"
APP_PATH="$(find "${VERIFY_DIR}/expanded" -type d -name 'CrossDesk.app' -print -quit)"
if [[ -z "${APP_PATH}" ]]; then
echo "CrossDesk.app is missing from ${PACKAGE_FILE}" >&2
exit 1
fi
./apps/desktop/scripts/macos/verify_app.sh "${APP_PATH}" "${{ matrix.binary_arch }}" "${EXPECTED_MACOS_SDK}"
- name: Upload build artifacts
uses: actions/upload-artifact@v6
with:
name: crossdesk-macos-${{ matrix.arch }}-${{ env.VERSION_NUM }}
path: crossdesk-macos-${{ matrix.arch }}-${{ env.VERSION_NUM }}.pkg
- name: Move files to release dir
run: |
mkdir -p release
cp crossdesk-macos-${{ matrix.arch }}-${{ env.VERSION_NUM }}.pkg release/
# iOS (also available as a standalone workflow)
build-ios:
name: Build iOS
uses: ./.github/workflows/build-ios.yml
with:
patch: ${{ inputs.patch || '0' }}
permissions:
contents: read
# Android (also available as a standalone workflow)
build-android:
name: Build Android
uses: ./.github/workflows/build-android.yml
with:
patch: ${{ inputs.patch || '0' }}
permissions:
contents: read
# Windows
build-windows-x64:
name: Build on Windows x64
runs-on: windows-2022
env:
XMAKE_GLOBALDIR: D:\xmake_global
steps:
- name: Extract version number
shell: pwsh
run: |
$ref = $env:GITHUB_REF
$version = $ref -replace '^refs/(tags|heads)/', ''
$version = $version -replace '^v', ''
$version = $version -replace '/', '-'
$BUILD_DATE = ([System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), "China Standard Time")).ToString("yyyyMMdd")
$PATCH_NUMBER = "${{ github.event.inputs.patch }}"
if ($PATCH_NUMBER -notmatch '^[0-9]+$') {
$PATCH_NUMBER = "0"
}
if ($version -match '^([0-9]+(\.[0-9]+){1,3})-([0-9]+)-([0-9]{8})$') {
$version = $Matches[1]
$PATCH_NUMBER = $Matches[3]
$BUILD_DATE = $Matches[4]
} elseif ($version -match '^([0-9]+(\.[0-9]+){1,3})-([0-9]{8})-([0-9]+)$') {
$version = $Matches[1]
$BUILD_DATE = $Matches[3]
$PATCH_NUMBER = $Matches[4]
} elseif ($version -match '^([0-9]+(\.[0-9]+){1,3})-([0-9]{8})$') {
$version = $Matches[1]
$BUILD_DATE = $Matches[3]
} elseif ($version -match '^([0-9]+(\.[0-9]+){1,3})-([0-9]+)$' -and $PATCH_NUMBER -eq "0") {
$version = $Matches[1]
$PATCH_NUMBER = $Matches[3]
}
if ($PATCH_NUMBER -ne "0") {
$VERSION_NUM = "v$version-$PATCH_NUMBER-$BUILD_DATE"
} else {
$VERSION_NUM = "v$version-$BUILD_DATE"
}
echo "VERSION_NUM=$VERSION_NUM" >> $env:GITHUB_ENV
echo "BUILD_DATE=$BUILD_DATE" >> $env:GITHUB_ENV
echo "PATCH_NUMBER=$PATCH_NUMBER" >> $env:GITHUB_ENV
- name: Cache xmake dependencies
uses: actions/cache@v5
with:
path: D:\xmake_global\.xmake\packages
key: "${{ runner.os }}-xmake-deps-intel-${{ github.run_id }}"
restore-keys: |
${{ runner.os }}-xmake-deps-intel-
- name: Checkout code
uses: actions/checkout@v5
- name: Initialize submodules
run: git submodule update --init --recursive
- name: Ensure minimum Xmake version
uses: ./.github/actions/ensure-xmake
with:
minimum-version: ${{ env.XMAKE_MIN_VERSION }}
- name: Prepare CUDA dependencies
working-directory: ${{ runner.temp }}
run: |
xmake repo -u
xmake create cuda
Push-Location cuda
xmake g --theme=plain
$cudaPath = ""
$packagesPath = "D:\xmake_global\.xmake\packages"
if (Test-Path $packagesPath) {
Write-Host "Packages directory exists: $packagesPath"
try {
$info = xmake require --info "cuda 12.6.3" 2>$null
if ($null -ne $info -and $info -ne "") {
$cudaPath = (($info | Select-String installdir).ToString() -replace '.*installdir:\s*','').Trim()
}
} catch {}
} else {
Write-Host "Packages directory not found: $packagesPath"
Write-Host "Installing CUDA package..."
xmake require -vy "cuda 12.6.3"
$info = xmake require --info "cuda 12.6.3"
$cudaPath = (($info | Select-String installdir).ToString() -replace '.*installdir:\s*','').Trim()
}
echo "CUDA_PATH=$cudaPath" >> $env:GITHUB_ENV
Write-Host "Resolved CUDA_PATH = $cudaPath"
Pop-Location
- name: Download INetC plugin
shell: powershell
run: |
$url = "https://github.com/DigitalMediaServer/NSIS-INetC-plugin/releases/download/v1.0.5.7/InetC.zip"
$out = "$env:RUNNER_TEMP\InetC.zip"
Invoke-WebRequest -Uri $url -OutFile $out
Expand-Archive $out -DestinationPath "$env:RUNNER_TEMP\InetC" -Force
$source = "$env:RUNNER_TEMP\InetC\x86-unicode\INetC.dll"
$target = "C:\Program Files (x86)\NSIS\Plugins\x86-unicode\INetC.dll"
Write-Host "Copying $source to $target"
Copy-Item $source $target -Force
- name: Copy nsProcess plugin to NSIS folder
run: |
$nsisPluginDir = "C:\Program Files (x86)\NSIS\Plugins\x86-unicode"
copy "${{ github.workspace }}\apps\desktop\scripts\windows\nsProcess.dll" $nsisPluginDir
- name: Build CrossDesk
run: |
xmake f --CROSSDESK_VERSION=${{ env.VERSION_NUM }} --USE_CUDA=true -y
xmake b -vy crossdesk
- name: Package
shell: pwsh
run: |
& "${{ github.workspace }}\apps\desktop\scripts\windows\pkg_x64.ps1" $env:VERSION_NUM
- name: Upload unsigned Windows installer for test signing
if: github.event_name == 'workflow_dispatch' && inputs.sign_windows_test
id: upload-unsigned-windows-installer
uses: actions/upload-artifact@v7
with:
path: ${{ github.workspace }}/apps/desktop/scripts/windows/crossdesk-win-x64-${{ env.VERSION_NUM }}.exe
archive: false
if-no-files-found: error
retention-days: 1
- name: Sign Windows installer with SignPath test certificate
if: github.event_name == 'workflow_dispatch' && inputs.sign_windows_test
uses: signpath/github-action-submit-signing-request@v2
with:
api-token: ${{ secrets.SIGNPATH_API_TOKEN }}
organization-id: ${{ vars.SIGNPATH_ORGANIZATION_ID }}
project-slug: crossdesk
signing-policy-slug: test-signing
github-artifact-id: ${{ steps.upload-unsigned-windows-installer.outputs.artifact-id }}
wait-for-completion: true
output-artifact-directory: ${{ github.workspace }}\signpath\signed-installer
skip-decompress: true
parameters: |
version: ${{ toJSON(env.VERSION_NUM) }}
- name: Verify and use test-signed Windows installer
if: github.event_name == 'workflow_dispatch' && inputs.sign_windows_test
shell: pwsh
run: |
$installerName = "crossdesk-win-x64-${{ env.VERSION_NUM }}.exe"
$signedInstaller = Join-Path "${{ github.workspace }}\signpath\signed-installer" $installerName
$destination = Join-Path "${{ github.workspace }}\apps\desktop\scripts\windows" $installerName
if (!(Test-Path $signedInstaller)) {
throw "SignPath did not return the signed installer: $signedInstaller"
}
$signature = Get-AuthenticodeSignature $signedInstaller
if (!$signature.SignerCertificate -or $signature.Status -eq "NotSigned") {
throw "SignPath returned an installer without an Authenticode signature."
}
Write-Host "Signer: $($signature.SignerCertificate.Subject)"
Write-Host "Signature status: $($signature.Status)"
Copy-Item $signedInstaller $destination -Force
- name: Build Portable CrossDesk
run: |
xmake f --CROSSDESK_VERSION=${{ env.VERSION_NUM }} --USE_CUDA=true --CROSSDESK_PORTABLE=true -y
xmake b -vy crossdesk
- name: Package Portable
shell: pwsh
run: |
$buildDir = "${{ github.workspace }}\build\windows\x64\release"
$portableDir = "${{ github.workspace }}\portable"
New-Item -ItemType Directory -Force -Path $portableDir
$portableFiles = @(
@("crossdesk.exe", "CrossDesk.exe"),
@("crossdesk_service.exe", "crossdesk_service.exe"),
@("crossdesk_session_helper.exe", "crossdesk_session_helper.exe"),
@("crossdesk_privacy_cursor_helper.exe", "crossdesk_privacy_cursor_helper.exe"),
@("crossdesk_privacy_window.dll", "crossdesk_privacy_window.dll"),
@("slint_cpp.dll", "slint_cpp.dll")
)
foreach ($file in $portableFiles) {
$source = Join-Path $buildDir $file[0]
$destination = Join-Path $portableDir $file[1]
if (!(Test-Path $source)) {
throw "Missing portable package file: $source"
}
Copy-Item $source $destination -Force
}
Copy-Item (Join-Path $buildDir "*.dll") $portableDir -Force
# Bundled Amyuni usbmmidd_v2 virtual display driver (headless hosts)
$driverDir = Join-Path $buildDir "usbmmidd_v2"
if (!(Test-Path (Join-Path $driverDir "deviceinstaller64.exe"))) {
throw "Missing bundled usbmmidd_v2 driver package: $driverDir"
}
Copy-Item $driverDir (Join-Path $portableDir "usbmmidd_v2") -Recurse -Force
foreach ($file in $portableFiles) {
$packagedFile = Join-Path $portableDir $file[1]
if (!(Test-Path $packagedFile)) {
throw "Portable package is missing: $packagedFile"
}
}
Compress-Archive -Path "$portableDir\*" -DestinationPath "${{ github.workspace }}\crossdesk-win-x64-portable-${{ env.VERSION_NUM }}.zip"
- name: Upload artifact
uses: actions/upload-artifact@v6
with:
name: crossdesk-win-x64-${{ env.VERSION_NUM }}
path: ${{ github.workspace }}/apps/desktop/scripts/windows/crossdesk-win-x64-${{ env.VERSION_NUM }}.exe
- name: Upload portable artifact
uses: actions/upload-artifact@v6
with:
name: crossdesk-win-x64-portable-${{ env.VERSION_NUM }}
path: ${{ github.workspace }}/crossdesk-win-x64-portable-${{ env.VERSION_NUM }}.zip
sign-android:
name: Sign Android release
needs: build-android
if: startsWith(github.ref, 'refs/tags/v')
uses: ./.github/workflows/sign-android.yml
with:
version: ${{ needs.build-android.outputs.version }}
secrets:
ANDROID_KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }}
ANDROID_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }}
ANDROID_KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }}
ANDROID_KEY_PASSWORD: ${{ secrets.ANDROID_KEY_PASSWORD }}
release:
name: Publish Release
if: startsWith(github.ref, 'refs/tags/v')
needs: [build-linux, build-macos, build-ios, build-android, sign-android, build-windows-x64]
runs-on: ubuntu-latest
concurrency:
group: publish-release-metadata
cancel-in-progress: false
steps:
- name: Checkout repository
uses: actions/checkout@v5
- name: Download all artifacts
uses: actions/download-artifact@v8
with:
path: artifacts
- name: Extract version number
id: version
shell: bash
run: |
VERSION_REF="${GITHUB_REF##*/}"
VERSION_BASE="${VERSION_REF#v}"
BUILD_DATE=$(TZ=Asia/Shanghai date +%Y%m%d)
PATCH_NUMBER="${{ github.event.inputs.patch }}"
if [[ ! "${PATCH_NUMBER}" =~ ^[0-9]+$ ]]; then
PATCH_NUMBER=0
fi
if [[ "${VERSION_BASE}" =~ ^([0-9]+(\.[0-9]+){1,3})-([0-9]+)-([0-9]{8})$ ]]; then
VERSION_BASE="${BASH_REMATCH[1]}"
PATCH_NUMBER="${BASH_REMATCH[3]}"
BUILD_DATE="${BASH_REMATCH[4]}"
elif [[ "${VERSION_BASE}" =~ ^([0-9]+(\.[0-9]+){1,3})-([0-9]{8})-([0-9]+)$ ]]; then
VERSION_BASE="${BASH_REMATCH[1]}"
BUILD_DATE="${BASH_REMATCH[3]}"
PATCH_NUMBER="${BASH_REMATCH[4]}"
elif [[ "${VERSION_BASE}" =~ ^([0-9]+(\.[0-9]+){1,3})-([0-9]{8})$ ]]; then
VERSION_BASE="${BASH_REMATCH[1]}"
BUILD_DATE="${BASH_REMATCH[3]}"
elif [[ "${VERSION_BASE}" =~ ^([0-9]+(\.[0-9]+){1,3})-([0-9]+)$ && "${PATCH_NUMBER}" == "0" ]]; then
VERSION_BASE="${BASH_REMATCH[1]}"
PATCH_NUMBER="${BASH_REMATCH[3]}"
fi
BUILD_DATE_ISO="${BUILD_DATE:0:4}-${BUILD_DATE:4:2}-${BUILD_DATE:6:2}"
if [[ "${PATCH_NUMBER}" != "0" ]]; then
VERSION_NUM="${VERSION_BASE}-${PATCH_NUMBER}-${BUILD_DATE}"
else
VERSION_NUM="${VERSION_BASE}-${BUILD_DATE}"
fi
VERSION_WITH_V="v${VERSION_NUM}"
echo "VERSION_NUM=${VERSION_NUM}" >> $GITHUB_OUTPUT
echo "VERSION_WITH_V=${VERSION_WITH_V}" >> $GITHUB_OUTPUT
echo "VERSION_BASE=${VERSION_BASE}" >> $GITHUB_OUTPUT
echo "BUILD_DATE=${BUILD_DATE}" >> $GITHUB_OUTPUT
echo "BUILD_DATE_ISO=${BUILD_DATE_ISO}" >> $GITHUB_OUTPUT
echo "PATCH_NUMBER=${PATCH_NUMBER}" >> $GITHUB_OUTPUT
- name: Prepare release notes
run: |
cat > "$RUNNER_TEMP/release-notes.md" << EOF
## Corresponding source
Source for these binaries: [${GITHUB_REF_NAME}](https://github.com/${GITHUB_REPOSITORY}/tree/${GITHUB_SHA}).
Clone that version with recursive submodules. The repository includes the build scripts and dependency patches.
[iOS source, modification and rebuild instructions](https://github.com/${GITHUB_REPOSITORY}/blob/${GITHUB_SHA}/apps/ios/README.md).
The iOS archive also contains the exact source revision and third-party source catalog with archive checksums.
[Android source and rebuild instructions](https://github.com/${GITHUB_REPOSITORY}/blob/${GITHUB_SHA}/apps/android/README.md).
The Android arm64 Release APK is signed with the CrossDesk publishing key and can be installed directly.
It includes the exact application and MiniRTC revisions, license documents and native build recipes.
## Linux packages
Choose one package for your architecture; both contain the complete CrossDesk application:
- Standard (recommended): crossdesk-linux-ARCH-VERSION.deb, for existing desktops.
- Virtual desktop: crossdesk-virtual-desktop-xfce-linux-ARCH-VERSION.deb, which additionally installs Xfce, Xvfb and D-Bus session tools through APT.
The packages replace each other and preserve user settings. Installation does not switch your default desktop or start a virtual session.
[Linux setup and switching packages](https://github.com/${GITHUB_REPOSITORY}/blob/${GITHUB_SHA}/docs/HEADLESS_EN.md).
## Code signing policy
Free code signing provided by [SignPath.io](https://signpath.io/), certificate by [SignPath Foundation](https://signpath.org/).
EOF
- name: Rename artifacts
run: |
mkdir -p release
cp artifacts/crossdesk-macos-x64-${{ steps.version.outputs.VERSION_WITH_V }}/* release/crossdesk-macos-x64-${{ steps.version.outputs.VERSION_WITH_V }}.pkg
cp artifacts/crossdesk-macos-arm64-${{ steps.version.outputs.VERSION_WITH_V }}/* release/crossdesk-macos-arm64-${{ steps.version.outputs.VERSION_WITH_V }}.pkg
for ARCH in amd64 arm64; do
for PACKAGE in crossdesk crossdesk-virtual-desktop-xfce; do
FILE="${PACKAGE}-linux-${ARCH}-${{ steps.version.outputs.VERSION_WITH_V }}.deb"
cp "artifacts/crossdesk-linux-${ARCH}-${{ steps.version.outputs.VERSION_WITH_V }}/${FILE}" "release/${FILE}"
done
done
cp artifacts/crossdesk-ios-arm64-unsigned-${{ needs.build-ios.outputs.version }}/* release/crossdesk-ios-arm64-unsigned-${{ needs.build-ios.outputs.version }}.zip
cp artifacts/crossdesk-android-arm64-${{ needs.build-android.outputs.version }}/*.apk release/crossdesk-android-arm64-${{ needs.build-android.outputs.version }}.apk
cp artifacts/crossdesk-win-x64-${{ steps.version.outputs.VERSION_WITH_V }}/* release/crossdesk-win-x64-${{ steps.version.outputs.VERSION_WITH_V }}.exe
cp artifacts/crossdesk-win-x64-portable-${{ steps.version.outputs.VERSION_WITH_V }}/* release/crossdesk-win-x64-portable-${{ steps.version.outputs.VERSION_WITH_V }}.zip
- name: List release files
run: ls -lh release/
- name: Upload to Versioned GitHub Release
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ steps.version.outputs.VERSION_WITH_V }}
# The pushed tag already determines the release source commit.
target_commitish: ${{ github.event.repository.default_branch }}
name: Release ${{ steps.version.outputs.VERSION_WITH_V }}
draft: false
prerelease: false
files: release/*
generate_release_notes: false
body_path: ${{ runner.temp }}/release-notes.md
- name: Create or update 'latest' tag
run: |
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git tag -f latest
git push origin latest --force
- name: Upload to GitHub Release (latest)
uses: softprops/action-gh-release@v2
with:
tag_name: latest
name: Latest Release
draft: false
prerelease: false
files: release/*
generate_release_notes: false
body_path: ${{ runner.temp }}/release-notes.md
- name: Upload artifacts to server
uses: burnett01/rsync-deployments@5.2
with:
switches: -avzr --progress
path: release/*
remote_path: /var/www/html/downloads/
remote_host: ${{ secrets.SERVER_HOST }}
remote_user: ${{ secrets.SERVER_USER }}
remote_key: ${{ secrets.SERVER_KEY }}
- name: Download current version.json
run: |
curl --fail --silent --show-error --retry 3 --max-time 30 \
-H 'Cache-Control: no-cache' \
https://version.crossdesk.cn/version.json -o current-version.json
- name: Generate version.json for all platforms
env:
RELEASE_TAG: ${{ steps.version.outputs.VERSION_WITH_V }}
run: |
python3 .github/scripts/update_version_manifest.py \
--current current-version.json --output version.json --artifacts release \
--tag "${RELEASE_TAG}" --name "Release ${RELEASE_TAG}" \
--notes "${RUNNER_TEMP}/release-notes.md"
- name: Upload version.json to server
uses: burnett01/rsync-deployments@5.2
with:
switches: -avzr
path: version.json
remote_path: /var/www/html/version/
remote_host: ${{ secrets.SERVER_HOST }}
remote_user: ${{ secrets.SERVER_USER }}
remote_key: ${{ secrets.SERVER_KEY }}
+69
View File
@@ -0,0 +1,69 @@
name: Close Inactive Issues
on:
schedule:
# run every day at midnight
- cron: "0 0 * * *"
workflow_dispatch:
permissions:
issues: write
pull-requests: write
contents: read
jobs:
close_inactive_issues:
runs-on: ubuntu-latest
steps:
- name: Check inactive issues and close them
uses: actions/github-script@v7
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
script: |
const inactivePeriod = 7 * 24 * 60 * 60 * 1000; // 7 days
const now = Date.now();
// paginate through all open issues (listForRepo also returns PRs)
const issues = await github.paginate(github.rest.issues.listForRepo, {
owner: context.repo.owner,
repo: context.repo.repo,
state: 'open',
});
for (const issue of issues) {
// skip pull requests (they are also returned by listForRepo)
if (issue.pull_request) continue;
// skip labeled issues
if (issue.labels.length > 0) {
console.log(`Skipping issue #${issue.number} (Has labels).`);
continue;
}
// last activity time = the issue's own updated_at, which is
// refreshed on comments, labels, etc. This avoids relying on
// fetching comments and is accurate even when comments are edited.
const lastActivityTime = new Date(issue.updated_at).getTime();
// check inactivity
if (now - lastActivityTime > inactivePeriod) {
console.log(`Closing inactive issue: #${issue.number} (No activity for 7 days)`);
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issue.number,
body: "This issue has been automatically closed due to inactivity for 7 days."
});
await github.rest.issues.update({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issue.number,
state: 'closed',
});
} else {
console.log(`Skipping issue #${issue.number} (Active within 7 days).`);
}
}
+194
View File
@@ -0,0 +1,194 @@
name: Release Mobile
on:
push:
tags:
- "ios-v*"
- "android-v*"
workflow_dispatch:
inputs:
source_tag:
description: "Existing tag: ios-v0.0.1-20261002 or android-v0.1.0-20261002."
required: true
type: string
permissions:
contents: read
jobs:
prepare:
name: Validate mobile source tag
runs-on: ubuntu-24.04
outputs:
platform: ${{ steps.source.outputs.platform }}
tag: ${{ steps.source.outputs.tag }}
version: ${{ steps.source.outputs.version }}
sha: ${{ steps.source.outputs.sha }}
steps:
- name: Checkout repository
uses: actions/checkout@v5
with:
fetch-depth: 0
persist-credentials: false
- name: Resolve source tag
id: source
shell: python
env:
SOURCE_TAG: ${{ inputs.source_tag || github.ref_name }}
run: |
import datetime
import os
import re
import subprocess
tag = os.environ["SOURCE_TAG"]
match = re.fullmatch(r"(ios|android)-(v[0-9]+\.[0-9]+\.[0-9]+-([0-9]{8}))", tag)
if not match:
raise ValueError("Use an existing ios-v<app-version>-YYYYMMDD or android-v<app-version>-YYYYMMDD tag")
datetime.datetime.strptime(match[3], "%Y%m%d")
sha = subprocess.check_output(
["git", "rev-parse", "--verify", f"refs/tags/{tag}^{{commit}}"], text=True).strip()
with open(os.environ["GITHUB_OUTPUT"], "a") as stream:
stream.write(f"platform={match[1]}\ntag={tag}\nversion={match[2]}\nsha={sha}\n")
build-ios:
name: Build iOS release
needs: prepare
if: needs.prepare.outputs.platform == 'ios'
uses: ./.github/workflows/build-ios.yml
with:
source_tag: ${{ needs.prepare.outputs.tag }}
build-android:
name: Build Android release
needs: prepare
if: needs.prepare.outputs.platform == 'android'
uses: ./.github/workflows/build-android.yml
with:
source_tag: ${{ needs.prepare.outputs.tag }}
sign-android:
name: Sign Android release
needs: [prepare, build-android]
if: needs.prepare.outputs.platform == 'android'
uses: ./.github/workflows/sign-android.yml
with:
version: ${{ needs.build-android.outputs.version }}
secrets:
ANDROID_KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }}
ANDROID_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }}
ANDROID_KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }}
ANDROID_KEY_PASSWORD: ${{ secrets.ANDROID_KEY_PASSWORD }}
release:
name: Publish mobile release
needs: [prepare, build-ios, build-android, sign-android]
if: ${{ !cancelled() && (needs.build-ios.result == 'success' || needs.sign-android.result == 'success') }}
runs-on: ubuntu-24.04
permissions:
contents: write
concurrency:
group: publish-release-metadata
cancel-in-progress: false
env:
PLATFORM: ${{ needs.prepare.outputs.platform }}
SOURCE_TAG: ${{ needs.prepare.outputs.tag }}
SOURCE_SHA: ${{ needs.prepare.outputs.sha }}
VERSION: ${{ needs.prepare.outputs.version }}
BUILD_VERSION: ${{ needs.build-ios.outputs.version || needs.build-android.outputs.version }}
steps:
- name: Checkout publishing scripts
uses: actions/checkout@v5
- name: Verify release version
shell: bash
run: |
if [[ "${BUILD_VERSION}" != "${VERSION}" ]]; then
echo "Source tag version ${VERSION} does not match the app version ${BUILD_VERSION}" >&2
exit 1
fi
- name: Download mobile release artifact
uses: actions/download-artifact@v8
with:
name: crossdesk-${{ env.PLATFORM }}-arm64${{ env.PLATFORM == 'ios' && '-unsigned' || '' }}-${{ env.VERSION }}
path: release
- name: Prepare release notes
shell: bash
run: |
if [[ "${PLATFORM}" == "ios" ]]; then
PLATFORM_NAME="iOS"
SIGNING_NOTE="The arm64 ZIP contains an unsigned app, source metadata, third-party sources and any generated dSYM. Sign the app before device installation."
else
PLATFORM_NAME="Android"
SIGNING_NOTE="The arm64 Release APK is signed with the CrossDesk publishing key and can be installed directly. It includes source metadata, license documents and native build recipes."
fi
cat > "${RUNNER_TEMP}/mobile-release-notes.md" << EOF
${PLATFORM_NAME} ${VERSION}
${SIGNING_NOTE}
Source: [${SOURCE_TAG}](https://github.com/${GITHUB_REPOSITORY}/tree/${SOURCE_SHA}).
Clone this tag with recursive submodules to obtain the corresponding source.
[Source and rebuild instructions](https://github.com/${GITHUB_REPOSITORY}/blob/${SOURCE_SHA}/apps/${PLATFORM}/README.md).
EOF
- name: Publish GitHub Release
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ env.SOURCE_TAG }}
# prepare requires an existing tag; this does not move its source commit.
# Using the default branch lets GITHUB_TOKEN update older release metadata.
target_commitish: ${{ github.event.repository.default_branch }}
name: ${{ env.PLATFORM == 'ios' && 'iOS' || 'Android' }} ${{ env.VERSION }}
draft: false
prerelease: false
make_latest: "false"
files: release/*
fail_on_unmatched_files: true
generate_release_notes: false
body_path: ${{ runner.temp }}/mobile-release-notes.md
- name: Upload mobile artifact to download server
uses: burnett01/rsync-deployments@5.2
with:
switches: -avzr --progress
path: release/*
remote_path: /var/www/html/downloads/
remote_host: ${{ secrets.SERVER_HOST }}
remote_user: ${{ secrets.SERVER_USER }}
remote_key: ${{ secrets.SERVER_KEY }}
- name: Download current version.json
shell: bash
run: |
curl --fail --silent --show-error --retry 3 --max-time 30 \
-H 'Cache-Control: no-cache' \
https://version.crossdesk.cn/version.json -o current-version.json
- name: Update mobile version and download URL
shell: bash
env:
RELEASE_NAME: ${{ env.PLATFORM == 'ios' && 'iOS' || 'Android' }} ${{ env.VERSION }}
run: |
python3 .github/scripts/update_version_manifest.py \
--current current-version.json --output version.json --artifacts release \
--tag "${SOURCE_TAG}" --name "${RELEASE_NAME}" \
--notes "${RUNNER_TEMP}/mobile-release-notes.md"
- name: Upload version.json to server
uses: burnett01/rsync-deployments@5.2
with:
switches: -avzr
path: version.json
remote_path: /var/www/html/version/
remote_host: ${{ secrets.SERVER_HOST }}
remote_user: ${{ secrets.SERVER_USER }}
remote_key: ${{ secrets.SERVER_KEY }}
- name: Summarize release
shell: bash
run: |
echo "Published [${SOURCE_TAG}](https://github.com/${GITHUB_REPOSITORY}/releases/tag/${SOURCE_TAG}), uploaded its ${PLATFORM} artifact to the download server, and updated version.json." >> "${GITHUB_STEP_SUMMARY}"
+153
View File
@@ -0,0 +1,153 @@
name: Sign Android Release
on:
workflow_call:
inputs:
version:
description: "Android artifact version, for example v1.6.0-20261002."
required: true
type: string
secrets:
ANDROID_KEYSTORE_BASE64:
required: true
ANDROID_KEYSTORE_PASSWORD:
required: true
ANDROID_KEY_ALIAS:
required: true
ANDROID_KEY_PASSWORD:
required: true
workflow_dispatch:
inputs:
source_tag:
description: "Existing Android release to sign without rebuilding, for example android-v1.6.0-20261002."
required: true
type: string
permissions:
contents: read
jobs:
sign:
name: Sign and verify Android APK
runs-on: ubuntu-24.04
timeout-minutes: 15
env:
VERSION: ${{ inputs.version }}
SOURCE_TAG: ${{ inputs.source_tag }}
steps:
- name: Validate signing configuration
shell: python
env:
ANDROID_KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }}
ANDROID_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }}
ANDROID_KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }}
ANDROID_KEY_PASSWORD: ${{ secrets.ANDROID_KEY_PASSWORD }}
run: |
import os
names = ("ANDROID_KEYSTORE_BASE64", "ANDROID_KEYSTORE_PASSWORD",
"ANDROID_KEY_ALIAS", "ANDROID_KEY_PASSWORD")
missing = [name for name in names if not os.environ.get(name)]
if missing:
raise ValueError("Missing repository signing secrets: " + ", ".join(missing))
- name: Resolve artifact version
id: version
shell: python
run: |
import datetime
import os
import re
version = os.environ["VERSION"]
if os.environ["GITHUB_EVENT_NAME"] == "workflow_dispatch" and not version:
tag = os.environ["SOURCE_TAG"]
if not tag.startswith("android-v"):
raise ValueError("Use an existing android-v<app-version>-YYYYMMDD release")
version = tag.removeprefix("android-")
match = re.fullmatch(r"v[0-9]+\.[0-9]+\.[0-9]+-([0-9]{8})", version)
if not match:
raise ValueError("Invalid Android artifact version")
datetime.datetime.strptime(match[1], "%Y%m%d")
with open(os.environ["GITHUB_OUTPUT"], "a") as stream:
stream.write(f"version={version}\n")
- name: Download unsigned build artifact
if: github.event_name != 'workflow_dispatch' || inputs.version != ''
uses: actions/download-artifact@v8
with:
name: crossdesk-android-arm64-unsigned-${{ steps.version.outputs.version }}
path: unsigned
- name: Download unsigned APK from existing release
if: github.event_name == 'workflow_dispatch' && inputs.version == ''
env:
GH_TOKEN: ${{ github.token }}
APK_VERSION: ${{ steps.version.outputs.version }}
run: |
gh release view "${SOURCE_TAG}" --repo "${GITHUB_REPOSITORY}" \
--json isDraft,isPrerelease > release.json
python3 - <<'PY'
import json
from pathlib import Path
release = json.loads(Path('release.json').read_text())
if release['isDraft'] or release['isPrerelease']:
raise ValueError('Use a published stable Android release')
PY
gh release download "${SOURCE_TAG}" --repo "${GITHUB_REPOSITORY}" \
--pattern "crossdesk-android-arm64-unsigned-${APK_VERSION}.apk" --dir unsigned
- name: Set up Java
uses: actions/setup-java@v5
with:
distribution: temurin
java-version: "17"
- name: Set up Android signing tools
uses: android-actions/setup-android@v3
with:
packages: "build-tools;36.0.0"
# This job never checks out or executes application source with the key present.
- name: Align, sign and verify Release APK
env:
APK_VERSION: ${{ steps.version.outputs.version }}
ANDROID_KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }}
ANDROID_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }}
ANDROID_KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }}
ANDROID_KEY_PASSWORD: ${{ secrets.ANDROID_KEY_PASSWORD }}
run: |
umask 077
crossdesk_signing_dir="$(mktemp -d "${RUNNER_TEMP}/crossdesk-signing.XXXXXX")"
trap 'rm -rf -- "${crossdesk_signing_dir}"' EXIT
printf '%s' "${ANDROID_KEYSTORE_BASE64}" | base64 --decode > "${crossdesk_signing_dir}/release.keystore"
crossdesk_tools="${ANDROID_HOME}/build-tools/36.0.0"
crossdesk_output="${RUNNER_TEMP}/crossdesk-android-signed"
mkdir -p "${crossdesk_output}"
"${crossdesk_tools}/zipalign" -P 16 -f -v 4 \
"unsigned/crossdesk-android-arm64-unsigned-${APK_VERSION}.apk" \
"${crossdesk_signing_dir}/aligned.apk"
"${crossdesk_tools}/apksigner" sign \
--ks "${crossdesk_signing_dir}/release.keystore" \
--ks-key-alias "${ANDROID_KEY_ALIAS}" \
--ks-pass env:ANDROID_KEYSTORE_PASSWORD --key-pass env:ANDROID_KEY_PASSWORD \
--out "${crossdesk_output}/crossdesk-android-arm64-${APK_VERSION}.apk" \
"${crossdesk_signing_dir}/aligned.apk"
"${crossdesk_tools}/apksigner" verify --verbose --print-certs \
"${crossdesk_output}/crossdesk-android-arm64-${APK_VERSION}.apk"
"${crossdesk_tools}/zipalign" -c -P 16 -v 4 \
"${crossdesk_output}/crossdesk-android-arm64-${APK_VERSION}.apk"
- name: Upload signed Release APK
uses: actions/upload-artifact@v6
with:
name: crossdesk-android-arm64-${{ steps.version.outputs.version }}
path: ${{ runner.temp }}/crossdesk-android-signed/*.apk
if-no-files-found: error
- name: Summarize signing
env:
APK_VERSION: ${{ steps.version.outputs.version }}
run: |
echo "Android ${APK_VERSION}: Release APK signed with the fixed publishing key; APK signature and 16 KB ZIP alignment verified." >> "${GITHUB_STEP_SUMMARY}"
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" && -z "${VERSION}" ]]; then
echo "Signed an existing release without rebuilding. Download the signed Actions artifact to publish it." >> "${GITHUB_STEP_SUMMARY}"
fi
+86
View File
@@ -0,0 +1,86 @@
name: Update version.json from Release
on:
release:
types: [published, edited]
workflow_dispatch:
inputs:
source_tag:
description: "Existing version tag whose assets and metadata should be uploaded to the server."
required: true
type: string
permissions:
contents: read
jobs:
update-version-json:
name: Upload release downloads and update version.json
if: github.event_name == 'workflow_dispatch' || (github.event.release.tag_name != 'latest' && !github.event.release.prerelease)
runs-on: ubuntu-24.04
concurrency:
group: publish-release-metadata
cancel-in-progress: false
env:
GH_TOKEN: ${{ github.token }}
RELEASE_TAG: ${{ inputs.source_tag || github.event.release.tag_name }}
steps:
- name: Checkout publishing scripts
uses: actions/checkout@v5
with:
ref: ${{ github.event.repository.default_branch }}
- name: Download release information and assets
shell: bash
run: |
python3 - <<'PY'
import os
import re
if not re.fullmatch(r'(?:ios-|android-)?v[0-9]+(?:\.[0-9]+){1,3}(?:-[0-9]+)*', os.environ['RELEASE_TAG']):
raise ValueError('Use a desktop, iOS or Android version tag')
PY
gh release view "${RELEASE_TAG}" --repo "${GITHUB_REPOSITORY}" \
--json tagName,name,body,publishedAt,isDraft,isPrerelease > release.json
python3 - <<'PY'
import json
from pathlib import Path
release = json.loads(Path('release.json').read_text())
if release['isDraft'] or release['isPrerelease']:
raise ValueError('Only published stable releases update version.json')
PY
gh release download "${RELEASE_TAG}" --repo "${GITHUB_REPOSITORY}" \
--pattern 'crossdesk-*' --dir release
- name: Upload release assets to download server
uses: burnett01/rsync-deployments@5.2
with:
switches: -avzr --progress
path: release/*
remote_path: /var/www/html/downloads/
remote_host: ${{ secrets.SERVER_HOST }}
remote_user: ${{ secrets.SERVER_USER }}
remote_key: ${{ secrets.SERVER_KEY }}
- name: Download current version.json
shell: bash
run: |
curl --fail --silent --show-error --retry 3 --max-time 30 \
-H 'Cache-Control: no-cache' \
https://version.crossdesk.cn/version.json -o current-version.json
- name: Merge release version and download URLs
shell: bash
run: |
python3 .github/scripts/update_version_manifest.py \
--current current-version.json --output version.json --artifacts release \
--release-json release.json
- name: Upload version.json to server
uses: burnett01/rsync-deployments@5.2
with:
switches: -avzr
path: version.json
remote_path: /var/www/html/version/
remote_host: ${{ secrets.SERVER_HOST }}
remote_user: ${{ secrets.SERVER_USER }}
remote_key: ${{ secrets.SERVER_KEY }}
+6 -1
View File
@@ -1,10 +1,15 @@
# Xmake cache
.xmake/
.xmake-toolchain-cache/
build/
apps/ios/Vendor/
apps/ios/DerivedData*/
apps/ios/.xmake/
xcuserdata/
*.xcuserstate
# MacOS Cache
.DS_Store
# VSCode cache
.vscode
continuous-desk.code-workspace
+3 -3
View File
@@ -1,3 +1,3 @@
[submodule "thirdparty/projectx"]
path = thirdparty/projectx
url = git@github.com:dijunkun/projectx.git
[submodule "deps/submodules/minirtc"]
path = deps/submodules/minirtc
url = https://github.com/kunkundi/minirtc.git
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+163
View File
@@ -0,0 +1,163 @@
# CrossDesk Privacy Policy
Last updated: October 10, 2026
[中文](#中文) | [English](#english)
## 中文
更新日期:2026 年 10 月 10 日
CrossDesk 重视您的个人信息与隐私保护。本政策说明我们在提供远程桌面服务时如何处理相关信息,以及您可以如何管理授权、保存的内容和数据请求。请在使用前阅读并了解本政策。
### 一、适用范围
本政策适用于 CrossDesk 桌面客户端、iOS 与 Android 客户端,以及由 CrossDesk 项目维护者(以下简称“我们”)提供的默认网络服务。
如果您选择自行部署或使用其他运营者提供的服务器,该服务器所处理的信息、保存期限及安全管理由相应运营者负责。请在使用前了解其隐私政策。本政策中有关客户端本地数据处理的说明仍适用。
### 二、我们处理的信息及用途
**设备连接与身份验证。** 为登记设备、验证连接权限、查询在线状态及建立远程连接,客户端与服务端会处理设备 ID、认证信息及在线状态。服务端还会保存设备身份及认证校验信息、在线与离线时间、客户端版本与平台、设备关联记录,并生成必要的运行和安全日志,用于维持服务、排查故障及防止滥用。
**必要的网络信息。** 建立连接、网络地址转换穿透及中继转发需要处理 IP 地址、端口等网络信息。这些信息用于通信和网络诊断,不等同于读取设备的定位权限。连接服务、中继服务及网络请求可能产生相应日志。
**远程会话内容。** 您发起或接受远程连接后,软件根据使用的功能在参与会话的设备之间传输画面、音频、键盘和鼠标操作、剪贴板文本及文件。会话内容可能包含个人或工作信息,请仅连接您拥有或已获授权使用的设备,并按需管理共享内容。
**版本检查。** 桌面客户端启动后会获取版本信息;iOS 与 Android 客户端在连接成功并收到远端版本信息后,会获取最新桌面版本信息,用于提示升级。该请求不携带设备 ID 或远端版本号,但网络服务会处理完成请求所必需的网络信息。
CrossDesk 未集成广告投放、广告追踪或用户行为分析功能。客户端不会主动上传诊断日志、崩溃报告或用户行为分析数据。您主动向我们提交问题或日志时,请先移除与问题无关的个人信息及连接凭据。
### 三、数据传输与相关服务
我们提供设备登记、连接协商、中继转发及版本检查服务。即使您使用自托管连接服务,客户端仍会按前述条件访问我们提供的版本服务。
远程会话内容优先在参与会话的设备间直接传输,必要时通过配置的中继服务器转发。中继服务用于实时转发,不提供会话录像或文件归档。客户端本地保存的画面预览和接收文件,按本政策相关说明处理。
自托管服务器由您选择的运营者管理。更换连接服务器后,设备登记、连接协商及中继数据将由相应运营者处理。
### 四、信息保存与安全措施
**客户端本地数据。** 软件会在本机保存连接设置、用户偏好、最近连接记录及必要的运行日志,以支持后续使用和故障排查。iOS 中的本机登录凭据及您选择记住的远程连接密码保存在系统钥匙串中,不通过 iCloud 钥匙串同步;旧版偏好中的本机登录凭据在成功迁入钥匙串后删除。
Android 中的设备身份及您选择保存的访问密码使用 Android Keystore 密钥加密后保存在本机,应用本地数据不纳入设备备份。
**远程画面预览。** iOS 与 Android 默认不保存远程画面预览。只有您在“设置 → 隐私”单独开启并确认后,才会从下一次连接起,每次连接保存一张远程画面,用于最近连接预览。预览仅保存在本机,不上传,并设置为不纳入设备备份。您可以单独清除预览;关闭保存或撤回隐私授权也会清除已有预览。旧版本未经此选择保存的预览会在升级后清理。
**接收的文件。** iOS 接收文件保存在本应用的文件目录中,您可通过系统“文件”应用管理或删除。清除画面预览不会删除接收文件或最近连接记录。
**服务端记录。** 为支持再次连接、服务运维和安全排查,设备身份、状态、关联记录及运行日志可能在连接结束后继续保存。保存范围和期限受服务运行需要、部署规则及适用的保留要求约束。您可以通过下述联系方式查询与您设备相关的信息及保存期限,或提出删除请求。撤回隐私授权、删除本地记录或卸载客户端,不会自动删除已产生的服务端记录;日志、备份和快照需分别核查和处理。
iOS 通过系统钥匙串和文件保护机制保护相应本地数据,默认信令连接进行 TLS 证书校验。请妥善保管设备和连接凭据,避免向无关人员共享访问密码。
Android 默认信令连接同样进行 TLS 证书校验。
### 五、移动端权限与授权选择
**隐私授权。** iOS 与 Android 首次使用,或从未提供此选择的旧版升级时,您需阅读本政策、主动勾选并点击同意后,客户端才会登记本机身份、连接信令服务和查询设备在线状态。拒绝后仍可查看设置、离线隐私政策和本地连接记录,远程连接功能暂不可用。未授权时,重新打开或从后台返回应用会再次提示。
**撤回同意。** 您可以在“设置 → 隐私 → 隐私与授权”中查看隐私政策、授权状态或撤回授权。客户端将停止远程会话、信令连接和版本检查,关闭并清除本地画面预览。再次使用连接功能前需重新同意;重新同意不会自动开启画面预览保存。撤回不影响撤回前已经发生的信息处理,也不等同于删除服务端数据。
**系统权限与会话功能。** iOS 客户端作为控制端接收远程电脑的画面与音频,不采集本机屏幕、摄像头或麦克风。局域网访问权限用于连接本地网络中的设备,您可在系统设置中管理。发送文件通过系统文件选择器选择,不要求开放整个文件库。当前 iOS 界面不读取或发送本机剪贴板文本;远端发送的剪贴板文本可在会话中写入本机剪贴板。
Android 客户端同样作为控制端接收远程画面与音频,不采集本机屏幕、摄像头或麦克风。发送及保存文件通过系统文件选择器完成,不要求开放整个文件库。剪贴板文本仅在您主动发送或复制远端文本时传输或写入本机,会话结束时清除应用内缓存的远端剪贴板文本。
Android 远程会话优先使用系统画中画在切换应用后继续显示画面。画中画不可用时,通过前台服务和连接通知保持您已建立的远程连接;后台暂停本地画面渲染和音频播放,不申请悬浮窗权限。通知权限用于提供返回及断开入口,CPU 唤醒锁用于会话后台期间维持连接,返回前台或会话结束时释放。您可以在应用或连接通知中断开,移除应用任务也会结束会话及保活服务。
应用及通信组件使用本地文件元数据、应用偏好和计时接口实现文件传输、设置保存及网络计时,不使用这些信息制作设备指纹或进行广告追踪。
### 六、查询与删除请求
您可以管理本地最近连接记录、保存的画面预览及接收文件。删除某条最近连接记录时,其预览及已保存的远程连接密码也会删除。
如需查询、获取数据摘要或删除默认服务中与您设备相关的记录,请通过下述邮箱联系我们,说明设备 ID 和请求范围。为避免未经授权的披露或删除,我们会核实请求权限;请勿通过邮件发送访问密码、私钥或其他敏感凭据。
删除服务端设备身份后,原身份及对应凭据将失效,再次连接可能登记为新设备。数据库记录的删除不表示日志、备份或其他设备上已接收的内容同时删除。使用自托管服务时,请向相应服务器运营者提出服务端数据请求。
### 七、政策更新与联系方式
本政策可能随功能及服务方式调整而更新,更新后的内容和日期将在隐私政策中公布。您可随时在应用设置中查阅当前随应用提供的政策文本。
如对本政策或个人信息处理有疑问,请联系:
邮箱:[junkun.di@hotmail.com](mailto:junkun.di@hotmail.com)
---
## English
Updated: October 2, 2026
CrossDesk respects your privacy. This policy explains how information is processed when we provide remote desktop services and how you can manage consent, locally saved content and data requests. Please read this policy before using the software.
### 1. Scope
This policy applies to the CrossDesk desktop, iOS and Android clients and the default network services provided by the CrossDesk project maintainers ("we" or "us").
If you deploy your own server or choose a server provided by another operator, that operator is responsible for its data processing, retention and security practices. Please review its privacy policy before use. The descriptions of local client data processing in this policy still apply.
### 2. Information processed and its purposes
**Device connections and authentication.** To register devices, verify connection permissions, query availability and establish remote connections, the clients and server process device IDs, authentication information and presence. The server also retains device identity and authentication verification records, online and offline times, client versions and platforms, and device associations. Necessary operational and security logs support service operation, troubleshooting and abuse prevention.
**Necessary network information.** Connections, network address translation traversal and relay forwarding require IP addresses, ports and other network information. This supports communication and network diagnostics and does not involve reading the device's location permission. Connection services, relay services and network requests may generate related logs.
**Remote-session content.** After you initiate or accept a remote connection, the software transfers content between participating devices according to the features used. This includes screens, audio, keyboard and mouse input, clipboard text and files. Such content may contain personal or work information. Connect only to devices you own or are authorized to access, and manage shared content accordingly.
**Version checks.** The desktop client retrieves release information after startup. After connecting and receiving the remote host's version, the iOS and Android clients retrieve the latest desktop release information to suggest updates. These requests do not contain device IDs or the remote host's version, but the service processes network information necessary to complete the request.
CrossDesk does not integrate advertising, advertising tracking or behavioral analytics. The clients do not proactively upload diagnostic logs, crash reports or behavioral analytics data. If you choose to submit an issue or logs, remove unrelated personal information and connection credentials first.
### 3. Data transmission and related services
We provide device registration, connection negotiation, relay forwarding and version checks. Even when you use a self-hosted connection service, the client still accesses our version service under the conditions described above.
Remote-session content is transmitted directly between participating devices where possible, or through the configured relay server when needed. The relay service forwards content in real time and does not provide session recording or file archiving. Locally saved previews and received files are handled as described in this policy.
Self-hosted servers are managed by the operator you choose. If you change the connection server, the corresponding operator will process device registration, connection negotiation and relay data.
### 4. Storage and security measures
**Local client data.** The software stores connection settings, preferences, recent connections and necessary operational logs on the device for subsequent use and troubleshooting. On iOS, local login credentials and remote connection passwords you choose to remember are stored in the system Keychain without iCloud Keychain synchronization. Legacy local login credentials in preferences are removed after successful migration to the Keychain.
On Android, device identities and access passwords you choose to save are encrypted with Android Keystore keys and stored locally. The app's local data is excluded from device backups.
**Remote desktop previews.** Saving previews is off by default on iOS and Android. Only after you separately enable and confirm it in Settings → Privacy will the app save one remote frame per connection, starting with the next connection, for recent-connection previews. Previews remain local, are not uploaded and are marked as excluded from device backups. You can clear them separately. Disabling saving or withdrawing network consent also clears them. Previews saved by older versions without this choice are cleared on upgrade.
**Received files.** Received files on iOS are stored in the app's file directory and can be managed or deleted through Files. Clearing previews does not delete received files or recent-connection records.
**Server records.** Device identities, presence, associations and operational logs may remain after a connection ends to support reconnection, service operation and security troubleshooting. Their scope and retention depend on operational needs, deployment rules and applicable retention requirements. You can contact us below to ask about records and retention periods related to your device or request deletion. Withdrawing network consent, deleting local records or uninstalling the client does not automatically delete existing server records. Logs, backups and snapshots require separate review and handling.
On iOS, the system Keychain and file protection mechanisms protect the relevant local data, and default signaling connections validate TLS certificates. Keep your devices and connection credentials secure and avoid sharing access passwords with unrelated people.
Default signaling connections on Android also validate TLS certificates.
### 5. Mobile permissions and consent choices
**Privacy authorization.** On first use of iOS or Android, or when upgrading from a version without this choice, you must read this policy, actively select the checkbox and agree before the client registers a local identity, connects to signaling or queries device presence. If you decline, settings, the offline policy and local connection history remain available, while remote connections are unavailable. Without consent, reopening the app or returning from the background presents the notice again.
**Withdrawal.** You can review the privacy policy and your authorization status or withdraw consent in Settings → Privacy → Privacy and Authorization. The client stops remote sessions, signaling and version checks, disables preview saving and clears local previews. Consent is required again before reconnecting. Agreeing again does not automatically enable preview saving. Withdrawal does not undo processing that already occurred or delete server data.
**System permissions and session features.** The iOS client receives remote computer screens and audio as a controller; it does not capture the local screen, camera or microphone. Local network access supports connections to devices on your network and can be managed in system settings. File sending uses the system document picker without requiring access to the entire file library. The current iOS interface does not read or send local clipboard text. Text sent by the remote device may be written to the local clipboard during a session.
The Android client also receives remote screens and audio as a controller and does not capture the local screen, camera or microphone. Sending and saving files uses the system document picker without requiring access to the entire file library. Clipboard text is transmitted or written locally only when you explicitly send text or copy remote text. The app clears cached remote clipboard text when the session ends.
Android remote sessions prefer system picture-in-picture to continue displaying video when you switch apps. If picture-in-picture is unavailable, a foreground service and connection notification maintain the remote connection you have established. Local video rendering and audio playback pause in the background; no overlay permission is requested. Notification permission provides return and disconnect actions. A CPU wake lock helps maintain the connection while the session is backgrounded and is released on foreground return or session end. You can disconnect in the app or its connection notification; removing the app task also ends the session and its foreground service.
The app and its communication components use local file metadata, preferences and timing APIs for file transfer, settings and network timing, not for device fingerprinting or advertising tracking.
### 6. Access and deletion requests
You can manage local recent connections, saved previews and received files. Removing a recent connection also removes its preview and remembered remote connection password.
To request access to information, a data summary or deletion of records associated with your device in the default service, contact the email address below with the device ID and scope of your request. We verify the requester's authority to avoid unauthorized disclosure or deletion. Do not send access passwords, private keys or other sensitive credentials by email.
Deleting a server-side device identity invalidates that identity and its credentials; reconnecting may register a new device. Deleting database records does not mean that logs, backups or content already received by other devices are also deleted. For a self-hosted service, direct server-side data requests to its operator.
### 7. Policy changes and contact
This policy may be updated as features and services change. Updated text and its date will be published in the privacy policy. You can review the policy bundled with your app in its settings at any time.
For questions about this policy or the processing of personal information, contact:
Email: [junkun.di@hotmail.com](mailto:junkun.di@hotmail.com)
+333
View File
@@ -0,0 +1,333 @@
<div align="center">
<img src="apps/desktop/resources/linux/crossdesk_128x128.png" width="80" alt="CrossDesk 标志" />
<h1>CrossDesk</h1>
<p>轻量、跨平台的远程桌面,支持电脑、浏览器和移动端连接,用桌面墙集中查看与操控多台设备。</p>
<p><a href="https://www.crossdesk.cn/">官方网站</a> · <a href="https://github.com/kunkundi/crossdesk/releases">下载客户端</a> · <a href="https://web.crossdesk.cn/">打开 Web 客户端</a> · <a href="README_EN.md">English</a></p>
</div>
<div align="center">
[![Platforms](https://img.shields.io/badge/platform-Windows%20%7C%20macOS%20%7C%20Linux%20%7C%20iOS%20%7C%20Android-blue)](#download)
[![Release](https://img.shields.io/github/v/release/kunkundi/crossdesk)](https://github.com/kunkundi/crossdesk/releases)
[![Build](https://github.com/kunkundi/crossdesk/actions/workflows/build.yml/badge.svg)](https://github.com/kunkundi/crossdesk/actions/workflows/build.yml)
[![License: GPL v3](https://img.shields.io/badge/license-GPL--3.0-blue)](LICENSE)
[![Stars](https://img.shields.io/github/stars/kunkundi/crossdesk?style=social)](https://github.com/kunkundi/crossdesk/stargazers)
</div>
CrossDesk 支持 Windows、macOS、Linux 之间的远程访问,也可从浏览器或原生 iOS / Android 客户端控制电脑。桌面端新增 **桌面墙(DeskHub)**,可在独立窗口中同时查看多台远程桌面,按分组管理设备,并进行批量操作与群控。项目基于 [MiniRTC](https://github.com/kunkundi/minirtc),提供实时音视频传输、键鼠控制、文件传输与自托管能力,仍在持续开发中。
> 本文按当前仓库代码整理。截图展示当前 Slint 桌面界面,使用演示 ID、密码、在线状态和连接记录;缩略图来自公开页面;下载包的功能与系统要求请同时核对对应 Release 说明。原生 iOS 客户端的构建、签名方式见下文。
[界面预览](#preview) · [下载与安装](#download) · [快速连接](#quick-start) · [桌面墙](#deskhub) · [会话操作](#session) · [设置](#settings) · [iOS](#ios) · [Android](#android) · [自托管](#self-hosting) · [源码构建](docs/BUILD.md) · [常见问题](docs/FAQ.md)
<a id="preview"></a>
## 界面预览
### 桌面客户端
主窗口以“本桌面”和“远程桌面”两张卡片展示本机凭据与连接入口,下方是可按分组筛选的近期连接。左上角打开桌面墙,右上角菜单进入设置、消息与关于。
<p align="center">
<img src="docs/images/desktop-main-zh.png" width="800" alt="新版主窗口:桌面墙入口、本机凭据、远程连接卡片和近期连接分组筛选;数据为演示" />
</p>
### 桌面墙(DeskHub)
在独立窗口中同时查看多台设备,支持分组、可调整大小的网格、精简模式、全屏与批量操作。点击画面可放大查看,再按需接管操控。
<p align="center">
<img src="docs/images/desktop-deskhub-zh.png" width="960" alt="桌面墙网格:六台演示设备、分组筛选、添加、选择、精简模式和网络状态入口" />
</p>
### Web 客户端
在浏览器中输入远程设备 ID 和密码,无需在控制端安装桌面客户端。
<p align="center">
<img src="docs/images/web-client.png" width="800" alt="CrossDesk Web 客户端连接首页(2026-09-25 截图)" />
</p>
图片来源与更新方式见 [截图说明](docs/images/README.md)。
## 主要功能
| 能力 | 当前支持 |
| --- | --- |
| 跨平台控制 | Windows / macOS / Linux 桌面互控;浏览器与原生 iOS / Android 作为控制端 |
| 实时画面与声音 | H.264 / AV1、硬件编解码、远端声音播放;会话中可调整画质、30 / 60 fps 与画面偏好 |
| 多设备与多显示器 | 近期连接、设备别名与分组筛选、会话标签与远端显示器切换 |
| 桌面墙(DeskHub) | 多桌面实时预览、分组与拖动排序、放大接管、群控、批量连接 / 断开 / 静音 / 文件分发;可配置分辨率、帧率与视频总带宽 |
| 输入与协作 | 键鼠输入、远端光标同步、组合键、文本剪贴板同步、文件传输 |
| 网络与部署 | P2P 直连、TURN 中继与强制中继、SRTP 媒体加密、自托管信令与中继服务 |
| 隐私屏 | 被连接时自动开启,或在会话工具栏切换;可用性取决于被控端系统与采集方式 |
| Windows 锁屏控制 | 通过 CrossDesk Service 支持锁屏、登录界面及安全桌面的输入转发 |
| Linux 无头运行 | 复用已有桌面和应用,或创建独立 Xvfb 虚拟桌面;终端控制台可查看状态、修改密码和设置,见 [运行说明](docs/HEADLESS.md) |
各客户端的入口和能力有所不同;桌面会话操作见下文,iOS 的具体功能见 [开发说明](apps/ios/README.md)。
<a id="download"></a>
## 下载与安装
前往 [GitHub Releases](https://github.com/kunkundi/crossdesk/releases) 或 [官方网站](https://www.crossdesk.cn/),按系统与 CPU 架构选择安装包。
| 平台 | 当前源码 / CI 基线 | 安装方式 |
| --- | --- | --- |
| Windows | Windows 10+,x64 | `.exe` 安装包;便携构建也受支持 |
| macOS | macOS 14.0+,Intel / Apple Silicon | 选择 x64 或 arm64 的 `.pkg` |
| Linux | Ubuntu 20.04+,amd64 / arm64,glibc 2.31 基线 | 普通版 / Xfce 虚拟桌面版 `.deb` |
| iOS / iPadOS | iOS 16.0+,arm64 真机 | 原生客户端;使用 Xcode 构建并签名,CI 产物为未签名应用 |
| Android | Android 8.0+,arm64 | 原生控制端;使用 Gradle 构建 APK,见 [开发说明](apps/android/README.md) |
| Web | 支持 WebRTC 的浏览器 | 访问 [web.crossdesk.cn](https://web.crossdesk.cn/) |
Linux 每个架构提供两个可独立安装的包,**选择其中一个**:
| 安装包 | 适用场景 |
| --- | --- |
| `crossdesk-linux-<arch>-<version>.deb`(推荐) | 已有桌面的电脑;不会额外安装 Xfce 或 Xvfb |
| `crossdesk-virtual-desktop-xfce-linux-<arch>-<version>.deb` | 需要创建独立桌面的服务器;APT 会额外安装 **Xfce、Xvfb 和 D-Bus 会话工具** |
普通版安装示例(将文件名替换为实际下载名称,arm64 选择对应架构):
```bash
sudo apt install "./crossdesk-linux-amd64-<version>.deb"
```
如需虚拟桌面版,改为安装:
```bash
sudo apt install "./crossdesk-virtual-desktop-xfce-linux-amd64-<version>.deb"
```
两个包包含相同的完整程序,互相替换并保留用户配置;普通版自行补齐依赖后也能创建虚拟桌面。安装虚拟桌面版不会自动启动会话或切换默认桌面,启动方法见 [Linux 无头运行](docs/HEADLESS.md)。应用更新的下载按钮会选择已安装的包类型。已有版本升级后不会自动删除先前安装的 Xfce。
**macOS 首次运行:** 按应用提示,在“系统设置 → 隐私与安全性”中授予 CrossDesk **屏幕录制**(新系统可能显示为“屏幕与系统音频录制”)及 **辅助功能**权限,再按系统提示重新打开应用。前者用于捕获桌面,后者用于远程键鼠输入。
<a id="quick-start"></a>
## 快速连接
### 从另一台电脑连接
1. **准备被控电脑。** 安装并运行 CrossDesk,等待底部显示“已连接服务器”。在左侧“本桌面”查看 **本机 ID** 和 **密码**,提供给控制端。
2. **输入对端 ID。** 在控制端右侧“远程桌面 → 对端 ID”输入被控电脑的 **9 位 ID**,点击 **连接**。
3. **完成密码验证。** 按弹窗输入被控电脑当前的连接密码,确认后等待远程画面出现。需要保存密码时勾选“记住密码”。
4. **再次连接。** 成功连接过的设备会出现在“近期连接”中,可通过卡片重连。悬停卡片可编辑别名、修改分组、删除记录或连接 / 断开;标题右侧可按分组筛选设备。
本机密码旁的眼睛按钮用于显示 / 隐藏密码,刷新按钮用于生成新的随机密码,铅笔按钮用于手动修改。密码统一为 **6 位数字或英文字母**。修改或刷新时需保持连接服务器;等待修改成功、客户端重新连接后,再复制当前密码。已保存旧密码的控制端需重新输入。
### 从浏览器连接
1. 保持被控电脑上的 CrossDesk 运行,并确认已连接服务器。
2. 打开 [Web 客户端](https://web.crossdesk.cn/),输入 **远程设备 ID** 和 **密码**,点击“连接”。
3. 连接后使用页面提供的显示器、鼠标模式和键盘控件操作远端;手机和平板也可通过浏览器访问。
如果使用自建服务器,需要让控制端与被控端接入同一服务;Web 部署配置见 [CrossDesk Web Client](https://github.com/kunkundi/crossdesk-web-client)。
<a id="deskhub"></a>
## 桌面墙:集中查看与操控多台设备
点击主窗口左上角 **桌面墙**,打开独立窗口;连接窗口仍可用于普通远程连接和全局设置。桌面墙会保存设备成员、分组、排序与窗口布局,重启后需要手动连接设备。
1. **添加设备。** 点击 **添加 → 通过设备 ID 添加**,填写 ID、密码及可选分组,点击“添加并连接”;只有勾选“记住密码”才保存凭据。也可选择 **从近期连接添加**,多选已有记录并导入;导入后用“选择 → 连接”发起连接。
2. **查看与整理。** 从“全部设备”切换到指定分组;拖动网格分隔线统一调整画面大小,拖动设备到另一台设备上交换位置。精简模式隐藏名称和管理工具栏,全屏用于扩大查看区域;翻页保留连接。
3. **放大与操控。** 点击设备画面进入只读放大视图,上方缩略图可切换设备,拖动中间分隔条可调整上下区域。点击 **接管操控** 后才发送键鼠;点击“释放操控”或按 **Ctrl / ⌘ + Shift + Esc** 释放。切换设备或窗口失焦也会释放操控。
4. **批量操作。** 点击 **选择**,勾选设备或“全选”,执行连接、断开,或从“更多”中静音 / 取消静音、分发文件。“全选”覆盖当前分组的全部分页;切换分组会清空选择。
<p align="center">
<img src="docs/images/desktop-deskhub-focus-zh.png" width="960" alt="桌面墙放大视图:上方设备缩略图、下方主画面,以及只读预览、开启群控和接管操控入口;画面为演示" />
</p>
**群控:** 在放大视图点击“开启群控”,将当前设备的键鼠操作同步到 **所有已连接设备**,包含其他分组、分页及未显示在墙内的连接;范围不受批量勾选限制。各设备接收相同坐标与按键,屏幕尺寸不同时不会另做比例适配。释放操控会同时结束群控。
桌面墙连接默认静音,需要声音时通过“选择 → 更多 → 取消静音”开启。底部 **网络状态** 可查看所有已连接设备的直连 / 中继、加密状态、收发速率、视频延时、丢包率、分辨率与帧率。需要显示器切换、隐私屏等完整单会话工具时,可在主窗口“近期连接”中点击已连接设备,打开独立会话窗口。
**关闭桌面墙会断开全部远程设备连接,并关闭共用连接的独立会话窗口;最小化不会断开。** 分组、分页和选择范围不会限制关闭时的断开范围。更多操作、预览策略与版本兼容性见 [桌面墙说明](docs/deskhub.md)。
<a id="session"></a>
## 会话中的常用操作
远程窗口通过会话标签切换设备,控制栏提供以下操作;控制栏收起时先点击展开按钮。将鼠标悬停在图标上可查看提示。
| 入口 | 用途 |
| --- | --- |
| 显示器 | 切换远端显示器 |
| 键盘 | 发送组合键;Windows 的 `Ctrl+Alt+Del` 依赖远端服务 |
| 鼠标 | 控制 / 释放远端鼠标 |
| 扬声器 | 播放声音 / 静音 |
| 文件夹 | 选择文件发送到远端,并查看传输进度 |
| 画面设置 | 在当前会话中调整画面质量、采集帧率与画面偏好 |
| 网络状态 | 查看流量、丢包率、帧率、分辨率、直连 / 中继及加密状态 |
| 隐私屏 | 开启或关闭被控电脑的隐私屏;悬停查看当前状态与可用操作 |
| 全屏 | 进入 / 退出全屏 |
| 断开连接 | 结束当前远程会话 |
桌面端可同步文本剪贴板。接收文件的位置可在“设置 → 常规 → 文件保存路径”调整。关闭主窗口会隐藏窗口并保持程序运行;需要完全退出时使用系统托盘或菜单栏中的退出入口。
### 在会话中调整画面
连接成功后,点击工具栏中的 **画面设置**(滑杆图标),直接选择低 / 中 / 高画质、**30 / 60 fps**,以及帧率优先 / 画质优先 / 平衡。选项会发送给当前被控端,无需断开重连;实际画面效果取决于网络、设备与编码器能力。旧版被控端不支持时,菜单会提示并禁用选项。
<p align="center">
<img src="docs/images/desktop-stream-video-settings-zh.png" width="800" alt="当前远程会话的画面设置菜单:画面质量、采集帧率与画面偏好;背景为公开页面演示图" />
</p>
<a id="settings"></a>
## 客户端设置与更新
点击主窗口右上角 **☰ → 设置**,顶部切换 **常规 / 桌面墙**,修改后点击 **保存**。切换选项卡会保留未保存的修改,点击“取消”放弃修改。“常规”按界面、视频、网络连接等类别组织选项,可向下滚动查看其余设置。编码与连接选项建议在建立连接前调整;会话进行中部分选项不可修改。普通会话的画质、帧率和画面偏好在远程会话工具栏中调整。
<p align="center">
<img src="docs/images/desktop-settings-zh.png" width="720" alt="新版常规设置:常规与桌面墙选项卡、语言、视频编码、硬件编解码及网络连接设置" />
</p>
| 设置 | 说明 |
| --- | --- |
| 语言 | 中文、English、Русский |
| 采集方式(Windows) | 自动 / DXGI / WGC / GDI;无显示器主机使用“自动”启用自动适配 |
| 视频编码格式 | H.264 / AV1;硬件编解码是否可用取决于平台、硬件与构建选项 |
| 启用中继服务 | 允许借助 TURN 中继建立连接;P2P 连接失败时先检查此项 |
| 强制中继连接 | 启用中继服务后可勾选,让连接通过中继建立;关闭中继服务会同时关闭此项 |
| 保存远程画面预览 | 默认开启,保存远程画面预览;关闭后缩略图区域显示被控端平台,并清除已有预览,保留连接记录和密码 |
| 被连接时开启隐私屏 | 设置本机被远程连接时是否自动启用隐私屏;会话中可从控制端工具栏切换 |
| 自托管配置 | 填写服务器地址和信令服务端口,并勾选启用 |
| 开机自启 / 启用守护进程 | 调整启动与进程守护行为,按界面提示重启后生效 |
| 文件保存路径 | 选择接收文件的目录 |
### 桌面墙画面传输
在 **设置 → 桌面墙** 中统一配置墙内设备,保存后立即应用到当前桌面墙会话,并用于后续连接;普通连接不受影响。
| 设置 | 说明 |
| --- | --- |
| 分辨率上限 | 自动、320 × 180、640 × 360、1280 × 720、1920 × 1080、2560 × 1440、3840 × 2160 或原始分辨率;自动模式按网格 / 放大视图调整,固定上限保持比例且不放大源画面 |
| 帧率 | 跟随设备设置,或指定 15 / 30 / 60 FPS |
| 视频总带宽 | 默认 20 Mbps,可选 2 / 5 / 10 / 20 / 50 / 100 Mbps;由支持该能力的桌面墙会话共享,放大画面优先分配,不包含音频、文件传输与普通连接,也不是瞬时流量的硬上限 |
<p align="center">
<img src="docs/images/desktop-settings-deskhub-zh.png" width="720" alt="桌面墙传输设置:自动分辨率、跟随设备帧率和 20 Mbps 视频总带宽" />
</p>
支持预览订阅的设备在不可见时可暂停视频传输,重新可见时恢复;旧版被控端按其能力回退,不保证所有分辨率、帧率或带宽选项都生效。
### 检查更新
客户端启动后会在后台检查版本,发现新版本时自动弹出更新提示,可查看更新说明并前往下载页面。关闭提示后,本次运行中的后台检查不会再次弹窗,主窗口菜单入口仍会显示更新提示;重新启动客户端后,如仍有新版本则再次提示。打开 **☰ → 关于** 可查看版本;有新版本时,点击版本信息下方的 **更新日志** 可再次打开更新提示,也可点击 **检查更新** 手动检查。
<p align="center">
<img src="docs/images/desktop-about-zh.png" width="720" alt="关于窗口与检查更新按钮,版本号和检查结果为演示数据" />
</p>
<a id="ios"></a>
## 原生 iOS / iPadOS 客户端
仓库的 [`apps/ios`](apps/ios/README.md) 提供原生控制端,与桌面端使用同一套 MiniRTC 协议。它可以控制远端电脑;当前不提供将 iPhone / iPad 作为被控桌面的功能。
1. 按 [iOS 开发说明](apps/ios/README.md) 使用 Xcode 构建并签名,安装到 iOS 16+ 的真机。
2. 在首页输入对端 ID,点击连接并填写密码;成功连接后可从“最近连接”中重连。
3. 在设置中选择鼠标模式:**相对位置**像触控板一样移动光标,**绝对位置**将触摸位置直接映射到远端画面。
4. 点击悬浮图标展开菜单,可切换显示器、显示键盘、控制声音或发送文件。收到的文件位于应用的 `Documents/Received`,可通过传输状态旁的分享按钮导出。
当前支持接收远端文本到 iOS 剪贴板;界面暂未提供主动发送本机剪贴板的按钮。
当前支持单指点击、双指右键、长按拖动与捏合缩放;缩放后的双指平移用于移动视图。原生端与浏览器端分别维护,使用入口和手势可能不同。
<a id="android"></a>
## 原生 Android 控制端
[`apps/android`](apps/android/README.md) 提供独立 Android Studio / Gradle 工程,复用 MiniRTC 和桌面键鼠协议。支持连接电脑、H.264 / AV1 画面、声音、触控/外接键鼠、多屏切换和文本剪贴板。当前面向 Android 8.0+ arm64 设备,使用软件解码;尚未提供手机被控、文件传输和 iOS 全部附加功能。
按 [Android 开发说明](apps/android/README.md) 构建并安装 APK,在首页填写电脑端的设备 ID 和密码即可连接。长按右键、双指滚动,横屏可扩大画面;切换到后台会结束会话。
<a id="windows-service"></a>
## Windows 锁屏与登录界面
**CrossDesk Service**(服务名 `CrossDeskService`)提供锁屏、登录、凭据输入及安全桌面的状态上报、`Ctrl+Alt+Del` 发送和键鼠输入转发。
安装版默认注册按需启动的服务,客户端启动时尝试启动它;未启用无人值守时,本机没有 CrossDesk 客户端进程后服务会自动退出。便携版可在提示窗口或“设置 → 锁屏控制服务”中安装服务,需要管理员权限。
Windows 的“开机自启”在当前用户登录后启动客户端。安装版使用以最高权限运行的登录计划任务,后续登录无需再次确认 UAC;便携版和 Debug 构建使用当前用户的普通启动项。升级安装版或手动启动新版时,会自动迁移指向该程序的旧启动项。关闭自启会删除相应注册。登录前远控需要另外启用下面的无人值守模式。
### 开机后尚未登录时远控
安装版支持独立的无人值守被控端。在完整安装目录中打开**管理员 PowerShell**,一次性启用:
```powershell
.\CrossDesk.exe --unattended-enable
# 等待联网注册后,查看独立设备 ID、密码和 online 状态
.\CrossDesk.exe --unattended-status
```
使用返回的 `device_id` 和 `password` 从另一台设备连接。首次启用时复制当前客户端的服务器和编码设置,单独生成无人值守凭据;它与普通客户端的设备 ID 不同,重启、注销和重新启用时保留。后续执行启用命令会复用机器配置,不会覆盖它。自建服务器的根证书需要安装到本地计算机的信任存储中。
启用后,`CrossDeskService` 改为系统启动时自动运行,无需 Windows 自动登录,也不需要保存 Windows 登录密码。服务以 SYSTEM 身份在当前控制台会话中启动无界面的被控进程,复用登录界面抓屏、键鼠及 `Ctrl+Alt+Del` 支持。用户登录、锁屏和关闭普通客户端不会停止它;注销、切换用户或进程崩溃后服务会重新拉起,期间连接可能中断,需要重新连接同一设备 ID。启动时网络尚未就绪会继续重试。
无人值守模式提供画面、键鼠、多屏切换和安全桌面控制;不提供声音、文件传输、剪贴板或隐私遮罩。便携版和 Debug 构建不能启用此模式。设置和凭据位于 `%ProgramData%\CrossDeskUnattended`,只允许 SYSTEM 和管理员访问;日志位于其 `logs` 子目录。
```powershell
# 停止无人值守被控端,并恢复服务按需启动
.\CrossDesk.exe --unattended-disable
```
关闭普通“开机自启”不会关闭无人值守模式。禁用或卸载服务会取消无人值守启动,但保留受保护的机器配置;若需彻底清除凭据,在服务停止后由管理员删除该目录。
<details>
<summary>手动部署与服务管理命令</summary>
保留完整安装目录;自行部署构建产物时,将 `CrossDesk.exe`、`crossdesk_service.exe`、`crossdesk_session_helper.exe` 及同次构建输出的全部 `.dll` 放在同一目录。在该目录打开管理员 PowerShell,按需执行:
```powershell
.\CrossDesk.exe --service-install
.\CrossDesk.exe --service-start
.\CrossDesk.exe --service-status
.\CrossDesk.exe --service-ping
# 停止或卸载服务
.\CrossDesk.exe --service-stop
.\CrossDesk.exe --service-uninstall
```
</details>
出现“远端 Windows 服务不可用”时,检查被控电脑的安装和服务状态;普通桌面连接仍可使用,受保护界面的控制能力会受限。
<a id="self-hosting"></a>
## 自托管服务器
可自行部署信令服务与 TURN 中继,并在桌面客户端 **☰ → 设置 → 常规 → 自托管配置** 中填写连接信息。控制端与被控端都需要启用同一套配置。
- [自托管指南](docs/SELF_HOSTING.md):当前 Compose 部署入口、客户端设置、证书信任与排查。
- [CrossDesk Server](https://github.com/kunkundi/crossdesk-server):服务端源码与发布配置。
- [CrossDesk Web Client](https://github.com/kunkundi/crossdesk-web-client):浏览器端源码与自托管说明。
## 开发与反馈
- [源码构建](docs/BUILD.md):Windows、macOS、Linux、可选编译参数与打包。
- [iOS 开发说明](apps/ios/README.md):原生端构建和真机验证。
- [Android 开发说明](apps/android/README.md):APK 构建、安装与模拟器验证。
- [GUI 架构](docs/gui-architecture.md):桌面 UI、平台实现与工程结构。
- [常见问题](docs/FAQ.md):连接失败、黑屏、文件位置与编译问题。
- [提交问题](https://github.com/kunkundi/crossdesk/issues):请附上两端系统、客户端版本、连接方式和可复现步骤。
## 致谢与许可
感谢 [HelloGitHub](https://hellogithub.com/)、[阮一峰的科技爱好者周刊](https://github.com/ruanyf/weekly) 与 [LinuxDo](https://linux.do) 社区的推荐、交流与支持。
CrossDesk 使用 [GPL-3.0](LICENSE) 许可。隐私说明见 [隐私政策](PRIVACY.md#中文)。
### Code signing policy
CrossDesk 使用 SignPath.io 为本仓库构建的官方 Windows 发布包提供代码签名。
**Free code signing provided by [SignPath.io](https://signpath.io/), certificate by [SignPath Foundation](https://signpath.org/).**
- **Committers and reviewers(代码提交与审核):** [kunkundi](https://github.com/kunkundi)
- **Approvers(签名审批):** [kunkundi](https://github.com/kunkundi)
+329
View File
@@ -0,0 +1,329 @@
<div align="center">
<img src="apps/desktop/resources/linux/crossdesk_128x128.png" width="80" alt="CrossDesk logo" />
<h1>CrossDesk</h1>
<p>A lightweight, cross-platform remote desktop for computers, browsers, and mobile devices, with DeskHub for viewing and controlling multiple desktops.</p>
<p><a href="https://www.crossdesk.cn/">Website</a> · <a href="https://github.com/kunkundi/crossdesk/releases">Download</a> · <a href="https://web.crossdesk.cn/">Open Web Client</a> · <a href="README.md">中文</a></p>
</div>
<div align="center">
[![Platforms](https://img.shields.io/badge/platform-Windows%20%7C%20macOS%20%7C%20Linux%20%7C%20iOS%20%7C%20Android-blue)](#download)
[![Release](https://img.shields.io/github/v/release/kunkundi/crossdesk)](https://github.com/kunkundi/crossdesk/releases)
[![Build](https://github.com/kunkundi/crossdesk/actions/workflows/build.yml/badge.svg)](https://github.com/kunkundi/crossdesk/actions/workflows/build.yml)
[![License: GPL v3](https://img.shields.io/badge/license-GPL--3.0-blue)](LICENSE)
[![Stars](https://img.shields.io/github/stars/kunkundi/crossdesk?style=social)](https://github.com/kunkundi/crossdesk/stargazers)
</div>
CrossDesk connects Windows, macOS, and Linux desktops, with browser and native iOS / Android clients for controlling computers. The desktop client now includes **DeskHub**, a separate window for viewing multiple remote desktops, organizing devices into groups, and performing batch actions or synchronized control. Built on [MiniRTC](https://github.com/kunkundi/minirtc), it supports real-time video and audio, keyboard and mouse control, file transfer, and self-hosting. The project is under active development.
> This guide follows the current repository source. Desktop screenshots render the current Slint UI with sample IDs, passwords, online statuses, and recent devices; thumbnails show public pages. Check each release's notes for the features and requirements of its binaries. Native iOS build and signing instructions are below.
[Preview](#preview) · [Download](#download) · [Quick start](#quick-start) · [DeskHub](#deskhub) · [Session controls](#session) · [Settings](#settings) · [iOS](#ios) · [Self-hosting](#self-hosting) · [Build](docs/BUILD_EN.md) · [FAQ](docs/FAQ.md#english)
<a id="preview"></a>
## Preview
### Desktop client
The main window presents your credentials and connection controls in Local Desktop and Remote Desktop cards, with recent devices and a group filter below. Open DeskHub at the top left, or use the top-right menu for settings, messages, and About.
<p align="center">
<img src="docs/images/desktop-main-en.png" width="800" alt="Updated main window with DeskHub access, local credentials, remote connection controls, and recent-device group filtering; data is illustrative" />
</p>
### DeskHub
View multiple devices in a separate window with groups, a resizable grid, compact and fullscreen views, and batch actions. Click a preview to enlarge it, then take control when needed.
<p align="center">
<img src="docs/images/desktop-deskhub-en.png" width="960" alt="DeskHub grid with six demonstration devices, group filtering, Add, Select, Compact, and Network controls" />
</p>
### Web client
Enter a remote device ID and password in your browser without installing the desktop app on the controlling device.
<p align="center">
<img src="docs/images/web-client.png" width="800" alt="CrossDesk Web Client connection page in Chinese, captured on 2026-09-25" />
</p>
See the [screenshot notes](docs/images/README.md) for image sources and refresh instructions.
## Features
| Capability | Current support |
| --- | --- |
| Cross-platform control | Windows / macOS / Linux desktop control; browser and native iOS / Android controllers |
| Live video and audio | H.264 / AV1, hardware codecs, and remote audio; adjust quality, 30 / 60 fps, and video preference during a session |
| Devices and displays | Recent connections, device aliases and group filtering, session tabs, and remote display switching |
| DeskHub | Live multi-desktop previews, groups and drag reordering, enlarged views with control, synchronized input, and batch connection / disconnection / audio / file actions; configurable resolution, frame rate, and shared video budget |
| Input and sharing | Keyboard/mouse input, remote cursor synchronization, shortcuts, text clipboard synchronization, and file transfer |
| Networking and deployment | Direct P2P connections, TURN relay and forced relay, SRTP media encryption, and self-hosted signaling/relay services |
| Privacy screen | Enable automatically when connected to, or toggle from the session toolbar; availability depends on the host OS and capture method |
| Windows protected desktops | CrossDesk Service forwards input on lock screens, sign-in screens, and secure desktops |
| Linux headless operation | Reuse existing desktops and applications or create separate Xvfb desktops; use the terminal console to check status and change passwords or settings; see [setup](docs/HEADLESS_EN.md) |
Controls and capabilities vary by client. Desktop controls are described below; see the [iOS guide](apps/ios/README.md) for native mobile features.
<a id="download"></a>
## Download and install
Choose a package matching your OS and CPU architecture from [GitHub Releases](https://github.com/kunkundi/crossdesk/releases) or the [website](https://www.crossdesk.cn/).
| Platform | Current source / CI baseline | Installation |
| --- | --- | --- |
| Windows | Windows 10+, x64 | `.exe` installer; portable builds are also supported |
| macOS | macOS 14.0+, Intel / Apple Silicon | x64 or arm64 `.pkg` |
| Linux | Ubuntu 20.04+, amd64 / arm64, glibc 2.31 baseline | Standard / Xfce virtual desktop `.deb` |
| iOS / iPadOS | iOS 16.0+, arm64 physical device | Native controller; build and sign with Xcode, or sign the unsigned CI app |
| Android | Android 8.0+, arm64 | Native controller; build an APK with Gradle ([guide](apps/android/README.md)) |
| Web | A WebRTC-capable browser | Open [web.crossdesk.cn](https://web.crossdesk.cn/) |
Linux provides two standalone packages per architecture. **Choose one**:
| Package | Intended use |
| --- | --- |
| `crossdesk-linux-<arch>-<version>.deb` (recommended) | Computers with an existing desktop; does not install Xfce or Xvfb |
| `crossdesk-virtual-desktop-xfce-linux-<arch>-<version>.deb` | Servers needing an independent desktop; APT additionally installs **Xfce, Xvfb and D-Bus session tools** |
To install the standard package, replace the example filename with your download (use arm64 for that architecture):
```bash
sudo apt install "./crossdesk-linux-amd64-<version>.deb"
```
For the virtual desktop package, install this file instead:
```bash
sudo apt install "./crossdesk-virtual-desktop-xfce-linux-amd64-<version>.deb"
```
Both contain the same complete application, replace each other and preserve user settings. The standard package can also create virtual desktops after you install the optional dependencies. Installing the virtual desktop package does not start a session or change the default desktop; see [Linux headless operation](docs/HEADLESS_EN.md) to start one. The app's update download button selects the installed package type. Upgrading an existing installation does not automatically remove previously installed Xfce components.
**First launch on macOS:** follow the app prompts to grant **Screen Recording** (called **Screen & System Audio Recording** on newer systems) and **Accessibility** under **System Settings → Privacy & Security**. Reopen the app if prompted. These permissions allow desktop capture and remote keyboard/mouse input respectively.
<a id="quick-start"></a>
## Quick start
### Connect from another computer
1. **Prepare the host.** Install and run CrossDesk on the computer to control. Wait for the bottom status bar to show that the server is connected. Share the **Local ID** and **Password** shown under **Local Desktop** with the controller.
2. **Enter the remote ID.** On the controlling computer, enter the host's **9-digit ID** in **Remote Desktop → Remote ID**, then click **Connect**.
3. **Verify the password.** Enter the host's current connection password when prompted and confirm. Select **Remember password** if you want to save it.
4. **Reconnect later.** Previously connected devices appear under **Recent Connections**. Reconnect from a card, or hover to rename it, edit its groups, remove its record, or connect / disconnect. Use the group filter beside the heading to narrow the list.
The eye button shows or hides the local password, the refresh button generates a new random password, and the pencil button lets you edit it. Passwords use **6 ASCII letters or digits**. Stay connected to the server when editing or refreshing a password. Wait for the change to succeed and the client to reconnect, then copy the current password. Controllers that saved the old password must enter it again.
### Connect from a browser
1. Keep CrossDesk running and connected to the server on the host computer.
2. Open the [Web Client](https://web.crossdesk.cn/), enter the **Remote Device ID** and **Password**, and click **Connect**.
3. Use the page's display, mouse-mode, and keyboard controls during the session. Phone and tablet browsers can also connect.
For self-hosting, connect both sides to the same service. Browser deployment is documented in [CrossDesk Web Client](https://github.com/kunkundi/crossdesk-web-client).
<a id="deskhub"></a>
## DeskHub: view and control multiple devices
Click **DeskHub** at the top left of the main window to open a separate window. The connection window remains available for ordinary remote sessions and global settings. DeskHub saves its device membership, groups, order, and window layout; connections must be started manually after relaunching.
1. **Add devices.** Choose **Add → Add by device ID**, enter an ID, password, and optional group, then click **Add and connect**. Credentials are saved only when you select **Remember password**. Alternatively, choose **Add from recent** and import multiple records; use **Select → Connect** to connect after importing.
2. **Arrange the view.** Switch from **All devices** to a group, drag grid dividers to resize all previews, or drag a device onto another to swap positions. **Compact** hides device names and management controls; fullscreen provides more viewing space. Changing pages keeps connections open.
3. **Enlarge and control.** Click a preview to open a read-only enlarged view. Switch devices with the thumbnails above it, and drag the divider to resize the two areas. Click **Control** to send keyboard and mouse input. Click **Release** or press **Ctrl / ⌘ + Shift + Esc** to release; switching devices or losing window focus also releases control.
4. **Apply batch actions.** Click **Select**, choose devices or **Select all**, and connect, disconnect with **Close**, or use **More** to mute / unmute or send a file. **Select all** includes every page in the current group; switching groups clears the selection.
<p align="center">
<img src="docs/images/desktop-deskhub-focus-en.png" width="960" alt="DeskHub enlarged view with thumbnails above the main preview and View only status, Group control, and Control buttons; screens are illustrative" />
</p>
**Group control:** click **Group control** in the enlarged view to mirror input from the current device to **all connected devices**, including other groups, pages, and connections not displayed in the wall. The scope is independent of the batch selection. Devices receive the same coordinates and keys without additional scaling for different screen sizes. Releasing control also ends group control.
DeskHub connections are muted by default. Enable sound with **Select → More → Unmute**. The bottom **Network** button shows direct / relay mode, encryption, receive/send rates, video latency, packet loss, resolution, and frame rate for all connected devices. For the full single-session toolbar, including display switching and privacy screens, click a connected device under **Recent Connections** in the main window to open its separate session window.
**Closing DeskHub disconnects all remote devices and closes session windows sharing those connections; minimizing it keeps connections open.** The disconnect scope includes all groups and pages, regardless of selection. See the [DeskHub guide](docs/deskhub.md) (Chinese) for further controls, preview behavior, and compatibility details.
<a id="session"></a>
## Session controls
Switch devices using session tabs. Expand the control bar if it is collapsed, and hover over icons to see their tooltips.
| Control | Action |
| --- | --- |
| Display | Switch the remote monitor |
| Keyboard | Send shortcuts; Windows `Ctrl+Alt+Del` requires the remote service |
| Mouse | Enable / release remote mouse control |
| Speaker | Play / mute remote audio |
| Folder | Select a file to send and view transfer progress |
| Video settings | Adjust video quality, capture frame rate, and video preference during the current session |
| Network statistics | Inspect traffic, packet loss, frame rate, resolution, direct / relay mode, and encryption status |
| Privacy screen | Enable or disable the host's privacy screen; hover to see its status and available actions |
| Fullscreen | Enter / exit fullscreen |
| Disconnect | End the current remote session |
Desktop clients synchronize text clipboard contents. Configure the receiving directory under **Settings → General → File Save Path**. Closing the main window hides it and keeps the app running; use the system tray or menu-bar exit command to quit completely.
### Adjust video during a session
After connecting, open **Video settings** (the sliders icon) in the toolbar. Choose low / medium / high quality, **30 / 60 fps**, and frame-rate priority / quality priority / balanced adaptation. Changes are sent to the current host without reconnecting; actual results depend on the network, device, and encoder. For older hosts that do not support live video settings, the menu explains the limitation and disables the options.
<p align="center">
<img src="docs/images/desktop-stream-video-settings-en.png" width="800" alt="Current session video menu with quality, capture frame rate, and video preference; the background is a public page used for demonstration" />
</p>
<a id="settings"></a>
## Client settings and updates
Open **☰ → Settings** in the top-right corner, choose **General / DeskHub**, and click **Save** to apply changes. Switching tabs preserves pending changes; **Cancel** discards them. General settings are grouped into interface, video, networking, and further sections available by scrolling. Configure codecs and connections before connecting; some settings are disabled during an active session. Adjust ordinary session quality, frame rate, and video preference from its toolbar.
<p align="center">
<img src="docs/images/desktop-settings-en.png" width="720" alt="Updated General settings with General and DeskHub tabs, language, video codec, hardware codecs, and networking options" />
</p>
| Setting | Purpose |
| --- | --- |
| Language | 中文, English, Русский |
| Capture Method (Windows) | Auto / DXGI / WGC / GDI; choose Auto for automatic headless adaptation |
| Video Encode Format | H.264 / AV1; hardware codec availability depends on the platform, device, and build options |
| Enable TURN Service | Allow relay-assisted connections; check this setting if P2P fails |
| Force Relay | Require relay connections when TURN is enabled; turning TURN off also disables this option |
| Save remote screen previews | On by default. When disabled, the thumbnail area shows the remote device’s platform and existing previews are cleared; connection records and passwords are preserved |
| Privacy screen on connect | Automatically enable privacy when this computer is controlled remotely; the controller can toggle it from the session toolbar |
| Self-Hosted Config | Set the server address and signaling port, then enable the checkbox |
| Auto Start / Enable Daemon | Configure startup and process supervision; restart as indicated by the UI |
| File Save Path | Choose where received files are saved |
### DeskHub video transmission
Use **Settings → DeskHub** to configure wall sessions together. Saving applies changes immediately to current DeskHub sessions and future connections; ordinary connections are unaffected.
| Setting | Purpose |
| --- | --- |
| Resolution limit | Auto, 320 × 180, 640 × 360, 1280 × 720, 1920 × 1080, 2560 × 1440, 3840 × 2160, or Original resolution; Auto adapts to grid / enlarged views, while fixed limits preserve aspect ratio without upscaling the source |
| Frame rate | Follow device settings, or choose 15 / 30 / 60 FPS |
| Video budget | Defaults to 20 Mbps; choose 2 / 5 / 10 / 20 / 50 / 100 Mbps, shared by compatible DeskHub sessions with priority for enlarged views. Audio, file transfers, and ordinary connections are excluded; this is not a hard limit on instantaneous traffic |
<p align="center">
<img src="docs/images/desktop-settings-deskhub-en.png" width="720" alt="DeskHub video settings with Auto resolution, Follow device settings frame rate, and a 20 Mbps video budget" />
</p>
Devices supporting preview subscriptions can pause video while their views are hidden and resume when visible. Older hosts fall back according to their capabilities, so not every resolution, frame-rate, or bandwidth setting will apply.
### Check for updates
The client checks for updates in the background after launch and automatically opens the update dialog when a new version is found, showing release notes and a link to the download page. After you dismiss the dialog, background checks will not reopen it during the current run, while the main window menu keeps its update indicator. Restarting the client shows the dialog again if an update is still available. Open **☰ → About** to view the version. When an update is available, click **Release notes** below the new version to reopen the update dialog, or click **Check for updates** to check manually.
<p align="center">
<img src="docs/images/desktop-about-en.png" width="720" alt="About dialog with the Check for updates button; version and check result are demonstration data" />
</p>
<a id="ios"></a>
## Native iOS / iPadOS client
[`apps/ios`](apps/ios/README.md) contains a native controller using the same MiniRTC protocol as the desktop client. It controls remote computers; it does not expose an iPhone or iPad as a remotely controlled desktop.
1. Follow the [iOS guide](apps/ios/README.md) to build and sign the app with Xcode, then install it on an iOS 16+ physical device.
2. Enter a remote ID on the home screen, connect, and enter its password. Successful connections become available in the recent devices list.
3. Choose a mouse mode in Settings: **Relative Position** works like a trackpad; **Absolute Position** maps touches directly to the remote screen.
4. Tap the floating icon to expand the menu, then switch displays, open the keyboard, toggle audio, or send files. Received files are stored in `Documents/Received` and can be exported using the share button beside the transfer status.
The app currently receives remote text into the iOS clipboard. Its UI does not yet expose a button to send the local clipboard.
Gestures include one-finger click, two-finger right-click, long-press drag, and pinch-to-zoom. When zoomed in, two-finger panning moves the viewport. The native and browser clients are maintained separately, so their controls and gestures may differ. The current native UI uses Chinese labels.
<a id="windows-service"></a>
## Windows lock screens and sign-in
**CrossDesk Service** (`CrossDeskService`) reports protected desktop states and forwards `Ctrl+Alt+Del`, keyboard, and mouse input on lock screens, sign-in screens, credential prompts, and secure desktops.
The installer registers an on-demand service by default. CrossDesk tries to start it on launch. Unless unattended mode is enabled, the service exits when no local CrossDesk client is running. Portable builds offer service installation in the prompt or **Settings → Lock Screen Service**, with administrator privileges.
On Windows, **Auto Start** launches the client after the current user signs in. Installed release builds use a logon scheduled task with highest privileges, so subsequent logons need no UAC confirmation; portable and Debug builds use a normal per-user startup entry. Upgrading the installed build or launching the new version manually migrates a legacy startup entry pointing to that executable. Turning Auto Start off removes its registration. Remote access before sign-in requires the separate unattended mode below.
### Remote access before Windows sign-in
The installed release supports a separate unattended host. Open an **administrator PowerShell** in the complete installation directory and enable it once:
```powershell
.\CrossDesk.exe --unattended-enable
# After network registration, show its separate device ID, password and online state
.\CrossDesk.exe --unattended-status
```
Connect from another device using the returned `device_id` and `password`. First-time setup copies the current client's server and codec preferences and creates separate credentials. This ID differs from the GUI client's ID and persists across reboots, logoffs and re-enabling. Subsequent enable commands retain the machine configuration. Self-hosted server root certificates must be trusted in the Local Computer certificate store.
Once enabled, `CrossDeskService` starts automatically at system boot. Windows automatic login and saved Windows login passwords are unnecessary. The service launches a windowless SYSTEM host in the active console session and reuses secure-desktop capture, keyboard/mouse input and `Ctrl+Alt+Del`. Signing in, locking Windows or closing the ordinary client does not stop it. Logoff, user switching or a host crash causes the service to restart the host; the connection may drop, and you can reconnect using the same ID. Network connections retry if networking is unavailable during boot.
Unattended mode supports screen viewing, keyboard/mouse input, monitor switching and secure desktops. Audio, file transfer, clipboard and privacy screens are unavailable. Portable and Debug builds cannot enable it. Configuration and credentials reside in `%ProgramData%\CrossDeskUnattended`, accessible only to SYSTEM and administrators; logs are in its `logs` subdirectory.
```powershell
# Stop the unattended host and restore on-demand service startup
.\CrossDesk.exe --unattended-disable
```
Turning off ordinary Auto Start does not disable unattended mode. Disabling or uninstalling the service disarms unattended startup but retains the protected machine profile. To erase its credentials, stop the service and delete that directory as an administrator.
<details>
<summary>Manual deployment and service commands</summary>
Keep the complete installation directory. For manual deployment, place `CrossDesk.exe`, `crossdesk_service.exe`, `crossdesk_session_helper.exe`, and all `.dll` files from the same build together. Open an administrator PowerShell in that directory and run the commands you need:
```powershell
.\CrossDesk.exe --service-install
.\CrossDesk.exe --service-start
.\CrossDesk.exe --service-status
.\CrossDesk.exe --service-ping
# Stop or uninstall the service
.\CrossDesk.exe --service-stop
.\CrossDesk.exe --service-uninstall
```
</details>
If **Remote Windows service unavailable** appears, check installation and service status on the host. Ordinary desktop connections remain available, while control of protected screens is limited.
<a id="self-hosting"></a>
## Self-hosting
Host your own signaling and TURN services, then enter their connection details under **☰ → Settings → General → Self-Hosted Config**. Enable the same server configuration on both the controller and host.
- [Self-hosting guide](docs/SELF_HOSTING_EN.md): current Compose deployment, client settings, certificate trust, and troubleshooting.
- [CrossDesk Server](https://github.com/kunkundi/crossdesk-server): server source and release configuration.
- [CrossDesk Web Client](https://github.com/kunkundi/crossdesk-web-client): browser source and deployment instructions.
## Development and feedback
- [Build from source](docs/BUILD_EN.md): Windows, macOS, Linux, optional flags, and packaging.
- [iOS development](apps/ios/README.md): native build and physical-device checks.
- [Android development](apps/android/README.md): APK builds, installation, and emulator checks.
- [GUI architecture](docs/gui-architecture.md): desktop UI and platform organization.
- [FAQ](docs/FAQ.md#english): connection failures, blank video, received files, and build issues.
- [Report an issue](https://github.com/kunkundi/crossdesk/issues): include both operating systems, client versions, connection mode, and reproduction steps.
## Acknowledgements and license
Thanks to [HelloGitHub](https://hellogithub.com/), [Ruanyf Weekly](https://github.com/ruanyf/weekly), and the [LinuxDo](https://linux.do) community for featuring CrossDesk and contributing feedback.
CrossDesk is licensed under [GPL-3.0](LICENSE). See the [Privacy Policy](PRIVACY.md#english).
### Code signing policy
CrossDesk uses SignPath.io to sign official Windows releases built from this repository.
**Free code signing provided by [SignPath.io](https://signpath.io/), certificate by [SignPath Foundation](https://signpath.org/).**
- **Committers and reviewers:** [kunkundi](https://github.com/kunkundi)
- **Approvers:** [kunkundi](https://github.com/kunkundi)
## Native Android controller
The independent [Android project](apps/android/README.md) builds an APK for Android 8.0+ arm64 devices. It reuses MiniRTC and the desktop input protocol for remote video/audio, touch and external keyboard/mouse input, display switching, and text clipboard transfer. H.264 and AV1 currently use software decoding. Phone-as-host, file transfer, and full iOS feature parity are not included. See the [Android build guide](apps/android/README.md) for setup and validation.
+2
View File
@@ -0,0 +1,2 @@
gradlew text eol=lf
gradlew.bat text eol=crlf
+7
View File
@@ -0,0 +1,7 @@
.gradle/
.native/
.idea/
**/build/
local.properties
*.iml
__pycache__/
+248
View File
@@ -0,0 +1,248 @@
# CrossDesk Android
原生 Android 控制端,使用 Java 界面、JNI 和 MiniRTC,与桌面端使用相同的信令、ICE、SRTP 和输入协议。没有 WebView。当前版本为 1.6.1,支持 Android 8.0(API 26)及以上的 arm64 手机和平板。
## 当前功能
- 官方或自托管 WSS 信令服务器;授权后进入前台即自动注册或登录本机身份,首页实时显示连接、重连及失败状态。发起桌面连接时复用该身份;切换服务器会重新登录,撤回授权会关闭连接。已有远程会话优先通过系统画中画保持连接,画中画不可用时由带连接通知的前台服务兜底;首页空闲信令在后台关闭。
- 优先使用 MediaCodec 硬件解码 H.264 / AV1,硬件缓冲区直接提交 Surface;设备无对应硬件、分辨率超限或运行失败时,按原编码格式回退到 OpenH264 / dav1d。软件输出由独立显示线程将 NV12 转 RGBA;只保留最新待显示帧。MiniRTC 原有的通用压缩帧解码队列保持不变。
- 48 kHz 单声道 PCM 播放,支持静音,音频队列有容量限制。
- 相对鼠标(触控板)和绝对位置模式;单指点击、绝对模式按住拖动、长按右键,以及外接键盘、鼠标。画面手势与 iOS 一致:双指捏合以触点为中心缩放(1–10 倍),放大后双指拖动画面,原始比例下双指上下滑动控制滚轮。
- 横竖屏等比例显示、远端多显示器切换。与 iOS 一致的画面质量(低/中/高)、采集帧率(30/60 fps)、画面偏好;支持能力检测、电脑端确认、失败/5 秒超时回退及连续操作的应答排序。
- 根据常见移动设备解码能力和屏幕尺寸设置起始参数:显示长边不超过 1280 像素时默认低画质(最高 720p)/30 fps,其余默认中画质(最高 1080p)/30 fps。用户保存的画面偏好不变,仍可手动选择高画质或 60 fps。
- 网络状态按视频、音频、数据、合计展示收发速率和丢包率,并显示实际提交帧率、分辨率、画面延时、平滑 RTT、P2P/TURN 和实际 SRTP 状态。每秒刷新,过期或无效测量显示“—”。
- 可拖动的悬浮控制球、三列控制菜单和浮动 ASCII / 电脑键盘、常用快捷键;通过剪贴板发送中文等文本,再手动执行远端粘贴。
- 悬浮菜单中的“虚拟鼠标”展开 140 × 48 dp 横向左键/滚轮/右键条,跟随悬浮球移动,可随时收起,不压缩远程画面。按住左键或右键后,同一根手指拖动即可拖拽,滑出按键范围仍继续,松开结束;也支持另一指在画面上移动光标。采用无文字的扁平分体按键,中间滚轮外观为 18 × 30 dp,三键均保留 44 × 44 dp 触控范围,通过留白分隔。无阴影、凹凸或按压位移,按压仅变色。等色横条随手指上下循环移动,松手停止;上下滑动可超出按键范围,在画面放大后仍控制远端滚动。切换模式、显示器、进入后台或取消触摸会释放按键。状态菜单按内容高度完整展开,只有安全区域空间不足时才滚动。
- 悬浮控制栏支持选择并发送文件、接收电脑端文件、查看确认进度及保存收到的文件;Ctrl+Alt+Del 使用远端 Windows 系统服务,未启用服务时显示提示。
- 设备身份与选择保存的连接密码使用 Android Keystore / AES-GCM 加密;首次联网需同意。远程会话在切换应用时自动使用系统画中画,不可用时自动使用通知保活。
- 与 iOS 一致的首页卡片、顶部状态/公告/设置入口、密码弹层及分组设置页;最近连接按服务器隔离,长按可删除记录及密码。
- 平板首页支持横竖屏和分屏,按当前可用宽度自动适配:900 dp 起连接与最近连接并排,较窄窗口纵向排列;最近连接随宽度显示 1–4 列,手机常规宽度仍为两列。首页最大宽度为 1200 dp,设置、公告及阅读页最大宽度为 720 dp,宽窗口中的密码和隐私弹窗居中限宽。旋转或调整分屏直接重排现有页面,保留输入、设置编辑和当前会话;手机全屏首页保持竖屏。
- 页面转场沿用 iOS 的交互方式:设置、隐私、关于及公告页面进入时从右滑入,返回时反向滑出,背景页面轻微跟随;进入和退出远程会话使用 0.2 秒淡入淡出。遵循 Android 系统动画开关及速度设置。
- 设置页的鼠标控制、画面偏好,以及悬浮控制栏的画质、帧率和画面偏好使用 0.2 秒的选中底块滑动动画;连续点击从当前位置转向,电脑端拒绝或超时后平滑回退,系统关闭动画时直接切换。
- 通知公告与 iOS 共用信令协议,支持未读角标、分页、下拉刷新、更新推送、详情和网页链接;已读及删除状态按服务器、本机身份和公告版本保存在本机。
- 连接建立并收到对端信息后,按 iOS 相同的版本号及补丁规则检查桌面端版本;旧版本弹出“升级提示”,点击“知道了”继续控制。每次连接最多检查、提醒一次;缺失或无效版本按旧版提醒,检查失败不打断连接。仅获取公共 HTTPS 版本元数据,不上传对端身份或版本;未授权不请求,断开及进入后台取消检查并忽略过期回复。
- 可选保存远程画面预览:默认关闭,经确认开启后,从下一次连接起保存一张 640×360 预览,用于最近连接卡片。支持清除预览,关闭选项或撤回授权会清除已有图片。
- “关于 CrossDesk”对齐 iOS 的版本、软件许可、开源组件及源码与构建说明页面,包含 OpenFEC 告知、组件详情和可离线选择复制的完整许可;版本号读取当前 APK,构建时记录应用与 MiniRTC 的基础版本。
当前不包含安卓被控端、隐私屏或 iOS 全部附加功能。硬件能力取决于设备和编码格式,软件回退时高分辨率或高帧率可能增加功耗;可通过悬浮菜单的画面设置降低画质或采集帧率。暂只构建 `arm64-v8a`,不支持 x86 模拟器或 32 位设备。
## 本机更新提示
完成联网授权后,每次启动或从后台返回时检查一次公共版本文件,前台远程连接结束后再检查一次;同时触发时复用正在进行的请求。不进行周期性检查或自动重试,失败时保留已发现的新版本提示,等待下一次触发或手动检查;进入后台或撤回授权时取消请求并忽略过期回复。
本机只读取 `downloads.android-arm64`,复用 PC 端的版本号及补丁比较规则;仅构建日期变化不提示升级,平台版本字段缺失按检查失败处理。发现新版本后,首页设置按钮右上角显示红底白色感叹号角标,大小和位置与通知角标一致,设置页“关于”显示“新版本”文字和红点;“关于”展示新版本号、官网更新入口,并提供“检查更新”。该功能独立于被控电脑的版本升级提示。
## 构建
在 macOS 或 Linux 安装:
- JDK 17 或更新版本(可使用 Android Studio 自带 JBR)。
- Android SDK Platform 36、Build Tools 36.0.0、NDK `28.2.13676358`。
- Xmake **3.1.1 或更新版本**、Python 3.9+、Git、CMake 和主机编译工具。
- Python 的 setuptools、wheel,用于构建依赖的宿主工具。
先在仓库根目录初始化子模块:
```sh
git submodule update --init --recursive
```
macOS 命令行示例:
```sh
export ANDROID_HOME="$HOME/Library/Android/sdk"
export JAVA_HOME="/Applications/Android Studio.app/Contents/jbr/Contents/Home"
# 使用 PATH 中的 Xmake(最低 3.1.1),或通过 XMAKE_BIN 指定其他可执行文件。
cd apps/android
./gradlew :app:assembleDebug
```
也可用 Android Studio 打开 `apps/android`。在 SDK Manager 安装上述版本;SDK 位置可由 IDE 写入被忽略的 `local.properties`。Xmake 不在 IDE 的 PATH 中时,启动 IDE 前设置 `XMAKE_BIN`。
输出为 `app/build/outputs/apk/debug/app-debug.apk`,已由本机 Android 调试密钥签名:
```sh
"$ANDROID_HOME/platform-tools/adb" install -r app/build/outputs/apk/debug/app-debug.apk
```
Release 构建使用 `./gradlew :app:assembleRelease`,默认输出未签名 APK;发行前需配置自己的签名。Debug APK 也使用优化后的 Release 原生库,以保证软件解码性能。
首次构建会下载并从源码编译依赖,耗时取决于网络。后续编译复用缓存。Android 直接编译 `deps/submodules/minirtc` 中的源码;构建产物和依赖缓存位于 `.native/`,Xmake 工程配置位于 `native/.xmake/`,与桌面和 iOS 分开保存:
- Gradle 9.3.1、AGP 9.1.0、NDK r28c 固定在工程中。
- Xmake 包仓库固定到 `eda39de3fb99b420c168f1ab9ab2d1791e11b662`。
- `scripts/build_native.py` 调用独立的 `native/xmake.lua`,直接包含 MiniRTC 子模块的构建定义。构建过程不复制 MiniRTC 源码,也不应用补丁。
- MiniRTC 源码内的 Android 分支启用 OpenH264、SVT-AV1 和 dav1d 软件编解码及依赖配方,兼容 OpenFEC 的 Android 头文件,并关闭 UPnP。SVT-AV1 使用内置 ARM CPU 能力检测;当前应用作为控制端只接收视频,库同时提供 AV1 编码能力。TLS 校验位于 MiniRTC 内部。STUN、TURN UDP/TCP 与直接连接仍由 MiniRTC 提供。
- MiniRTC 的 `thirdparty/openssl/xmake.lua` 统一维护 iOS 和 Android 配方;Android 显式使用 NDK 的归档索引工具,避免 macOS `ranlib` 损坏 ELF 静态库。
- SVT-AV1 编码及 dav1d 解码已在 Android 15 arm64 / 16 KB 模拟器上完成验证,覆盖软件编码、请求硬件加速时的软件回退、码率更新、强制关键帧及 320×192 → 256×144 → 320×192 分辨率切换;两组测试各成功编码并解码 24 帧。这是编解码正确性验证,不代表真机实时编码性能。
- 依赖静态链接到 `libcrossdesk_android.so`,保留 16 KB ELF / APK 对齐。
修改原生代码后重新运行 Gradle 即可;修改依赖版本或配方时同步检查许可证内容,必要时移除 `.native/packages` 重新构建。MiniRTC 的源码和依赖配方变更直接保存在子模块中;提交时先提交 MiniRTC,再更新主仓库的子模块引用。
## GitHub Actions
[`Build Android`](../../.github/workflows/build-android.yml) 可在 Actions 页面单独手动运行;修改 Android、MiniRTC、共享协议或许可证资料的 Pull Request 也会触发。仓库原有的 [`Build and Release`](../../.github/workflows/build.yml) 在分支推送、标签推送及手动运行时调用同一工作流,`v` 标签发布会等待安卓构建及签名成功,并将已签名 Release APK 加入 GitHub Release 和现有下载服务器的产物集合。推送主仓库前,先确保它引用的 MiniRTC 提交已推送到子模块远程仓库,否则 CI 无法完成检出。
单独发布使用 [`Release Mobile`](../../.github/workflows/release-mobile.yml)。先更新并提交 `gradle.properties` 中的 `crossdeskVersionName` 和递增的 `crossdeskVersionCode`,再为该提交创建 `android-v<versionName>-YYYYMMDD` 标签,例如:
```sh
git tag android-v1.6.1-20261010
git push origin android-v1.6.1-20261010
```
该标签只触发安卓构建,使用固定发布密钥签名并验证 Release APK 后,再发布到独立的 GitHub Release 和现有下载服务器。签名失败或缺少签名 Secrets 时停止发布,不回退到未签名 APK。标签版本必须与应用版本一致,日期必须有效。重试发布时,在 Actions 页面手动运行 `Release Mobile`,将已有标签填入 `source_tag`;即使从其他分支触发,也会检出该标签的源码。APK 的源码资料记录安卓标签及准确的应用、MiniRTC 提交。
移动端独立发布保留桌面 `latest` 标签和 GitHub 的最新 Release 选择。APK 上传完成后,将服务器下载地址合并到共享 `https://version.crossdesk.cn/version.json` 的 `downloads.android-arm64`,并在该下载项中记录安卓版本和发布日期;保留顶层桌面版本信息和其他平台的下载项。下载服务器上传保留其他平台文件,复用仓库已有的 `SERVER_HOST`、`SERVER_USER`、`SERVER_KEY` Secrets。普通桌面版本标签仍通过 `Build and Release` 发布全部平台并更新各平台下载项;所有发布任务更新版本文件时使用同一队列。单独运行 `Build Android` 仍只上传 Actions 构建产物。
已有 Release 需要补传服务器或刷新下载信息时,可手动运行 `Update version.json from Release` 并填写已有 `source_tag`,无需重新构建。
工作流使用 Ubuntu 24.04、JDK 17、Python 3.13、SDK 36、Build Tools 36.0.0、NDK r28c,并使用最低支持的 Xmake 3.1.1 验证构建;本地允许使用更新的 Xmake。Gradle 使用工程内的 Wrapper,原生构建器固定 Xmake 包仓库版本。SDK/NDK 使用独立目录缓存,按宿主系统、架构和工具链版本区分;命中缓存时跳过 SDK 安装,未命中时在安装完成后立即保存,即使后续 APK 构建失败,下次也可复用。Xmake 可执行环境、固定版本的包仓库和 pip 下载也有各自的缓存;Ubuntu 系统工具只安装缺失项。
Gradle 缓存与 Android 原生依赖缓存分别管理;原生缓存按宿主架构、构建脚本及 MiniRTC 配方区分,不复用桌面或 iOS 的配置和目标文件。GitHub 托管 runner 每次启动仍是新环境;第一次运行或缓存失效时需要安装。不同分支和标签可读取默认分支的缓存,因此建议先在默认分支运行一次 `Build Android` 预热,再创建发布标签。
CI 仅构建和打包 Debug、Release APK,并校验 APK 的包名、`versionName` / `versionCode`、arm64 ABI、16 KB ELF / ZIP 对齐、完整许可证及 Debug 签名。单元测试、本机 C++ 协议与画面队列测试、Lint 和设备测试改为按需在本地执行;设备测试使用下面的设备验证流程在 arm64 手机或模拟器上执行。
统一 `v*` 发布从标签提取数字版本,通过 Gradle 属性写入 APK 的 `versionName`;App 内版本展示读取同一包信息。产物版本、日期及可选热修复编号与桌面端保持一致,例如 `v1.6.1-20261010` 或 `v1.6.1-2-20261010`。分支构建和独立 `android-v*` 发布使用 `gradle.properties` 中的版本,独立发布会检查标签与配置一致。构建日期采用上海时区;带日期的版本标签沿用标签中的日期,与 iOS 一致。Actions 提供:
- `crossdesk-android-arm64-<版本>.apk`:已签名 Release APK,独立安卓发布和全平台标签发布收集此 APK,可直接安装。
- `crossdesk-android-arm64-unsigned-<版本>.apk`:构建工作流的中间产物,也可用于自行签名和验证修改后的构建。
- `crossdesk-android-arm64-debug-<版本>.apk`:可安装的调试应用,保留 14 天。
Debug APK 使用每次运行的临时调试证书,可能无法覆盖手机上已有的其他签名版本;卸载原应用会清除本机连接记录和密码。需要持续覆盖升级时,应使用同一私钥签名 Release APK,并在每次发布新版本(含统一发布及热修复)时递增 `gradle.properties` 中的 `crossdeskVersionCode`。该安装升级序号独立于显示版本,不从日期或 CI 运行编号推算。未签名 APK 已完成对齐,可通过 SDK 的 `apksigner sign --ks <自己的密钥库> --out <已签名.apk> <未签名.apk>` 签名,再用 `apksigner verify` 检查。
### Release 签名
[`Sign Android Release`](../../.github/workflows/sign-android.yml) 在独立 job 中签名,不检出或执行应用源码。构建 job 和 Pull Request 构建不接收发布密钥。签名 job 使用 Build Tools 36.0.0,先执行 `zipalign -P 16`,再通过环境变量向 `apksigner` 提供密码,验证签名和 16 KB 对齐后上传已签名 APK。临时密钥库在步骤结束时清理,产物中不包含密钥或密码。
首次发布前,在仓库 Settings → Secrets and variables → Actions 配置:
| Secret | 内容 |
| --- | --- |
| `ANDROID_KEYSTORE_BASE64` | 发布密钥库文件的 Base64 内容 |
| `ANDROID_KEYSTORE_PASSWORD` | 密钥库密码 |
| `ANDROID_KEY_ALIAS` | 发布私钥的 alias |
| `ANDROID_KEY_PASSWORD` | 发布私钥密码 |
APK 签名不需要 Google Play 开发者账号。若没有已有发布密钥,可使用 JDK 的 `keytool` 创建一次,密钥库保存在工程之外,并备份密钥和密码:
```sh
keytool -genkeypair -storetype PKCS12 -keystore /path/outside/repo/crossdesk-release.p12 \
-alias crossdesk-release -keyalg RSA -keysize 4096 -validity 10000
```
PKCS12 使用同一个密钥库和私钥密码,将它配置到两个密码 Secrets。可用 `gh secret set` 从标准输入写入 Secrets,避免把密码放进命令行参数。macOS 上传密钥库示例:
```sh
base64 -i /path/outside/repo/crossdesk-release.p12 | gh secret set ANDROID_KEYSTORE_BASE64 --repo kunkundi/crossdesk
gh secret set ANDROID_KEYSTORE_PASSWORD --repo kunkundi/crossdesk
gh secret set ANDROID_KEY_ALIAS --repo kunkundi/crossdesk
gh secret set ANDROID_KEY_PASSWORD --repo kunkundi/crossdesk
```
后续版本沿用这些 Secrets,不能在每次构建时生成新密钥,也不能将密钥或密码提交到 Git。已有未签名安卓 Release 可单独运行 `Sign Android Release` 并填写其 `source_tag`,无需重新构建;该手动任务只上传已签名 Actions 产物,不修改已发布 Release。普通发布流程会自动签名、上传下载服务器,并将 `downloads.android-arm64` 指向已签名 APK。旧 Release 同时保留已签名和未签名 APK 时,版本文件优先选择相同版本的已签名文件。
## 使用与连接安全
授权后首页会自动连接服务器,绿色“已连接服务器”表示信令登录完成;失败时可点击状态重试。设置页显示本机 ID。电脑端保持在线,在 Android 首页填写 9 位设备 ID,首次点击“连接”后在底部弹层输入密码,可选择加密保存密码。成功保存后,点击最近连接或再次输入相同 ID 会直接使用该服务器下保存的密码,重启应用后仍然有效;密码无法读取或被远端拒绝时会重新显示输入弹层,新密码仅在连接成功后替换,取消或连接失败不会覆盖原密码。自托管服务器从“设置 → 服务器”展开修改主机名与端口,不能填写 `https://`、路径或完整 URL。默认是 `api.crossdesk.cn:9099`。
最近连接卡片与 iOS 一样,在设备 ID 旁显示已保存密码的钥匙图标和在线/离线状态,在线设备优先,同一状态内保留原来的最近连接顺序。授权并登录服务器后,通过身份信令订阅 `recent_connections_presence`,接收完整快照与 `presence_update`;每 30 秒刷新,状态超过 60 秒未更新则显示离线。断线、切换服务器或进入后台会清除在线状态,重连后等待新的快照。自托管服务需要支持相同的设备在线状态协议。
证书信任来自 Android 默认 TrustManager 导出的根证书。JNI 设置证书文件路径后,MiniRTC 的 Android 分支通过 `SSL_CTX_load_verify_locations` 显式加载,并校验证书链及 DNS / IP 主机名;不会跳过 TLS 验证。Android 应用进程带有 `AT_SECURE` 标记,不能依赖 OpenSSL 的默认路径加载器读取 `SSL_CERT_FILE`,否则会出现所有服务器均无法建立信任链的问题。自托管服务器应使用受系统信任的证书。当前没有在应用内导入自签名证书的入口。
身份按主机名和端口分开保存,备份与设备迁移不包含应用数据。密码不写入连接记录,仅在明确开启“保存密码”后写入独立加密存储;未开启时仅用于当前会话。连接成功通知只处理一次,重复的传输就绪回调不会再次保存密码或重建会话页面;密码存储拒绝空值覆盖。旧版本已被空值覆盖的密码无法恢复,遇到此记录时会提示重新输入一次,并保留“保存密码”开启状态。由于 MiniRTC 的诊断日志包含登录身份,Android 桥接层关闭其会话日志。身份存储损坏会显示错误,不会静默重新注册。
会话中的“剪贴板”发送用户输入的文本;收到的远端文本先留在会话内,点击“复制远端文本”才写入手机剪贴板。退出会话后清除会话内容。每次发送最多 128 KB。浮动键盘切换“电脑”后的“复制 / 粘贴 / 全选”根据远端平台选择 Ctrl 或 macOS Command。
“发送文件”调用系统文件选择器,后台读取所选文件后使用桌面端相同的 `file` / `file_feedback` 协议传输,支持空文件和中文文件名。每次发送一个文件,以 64 KiB 分块、最多 1 MiB 未确认数据限制发送队列;进度来自接收端确认,30 秒没有有效进展则报告失败。接收时校验大小并追踪完整字节范围,允许跨线程回调乱序,未完成的文件不会提供保存入口。同名文件分开存储,不覆盖已有文件;可通过“保存收到的文件”导出最近收到的文件,连续接收多个文件时应逐个保存。
选取或保存文件期间保留会话并暂时禁用自动画中画,取消选择不会断开;停留超过 5 分钟且应用仍不在前台时结束会话。发送副本和收到的文件暂存于应用私有缓存,结束会话后清除,需要保留的接收文件应在断开前导出;不申请全盘存储权限。
## 后台连接与画中画
与 iOS 一样,通过系统画中画显示真实远程视频并维持会话。连接成功且已显示远程画面后,Android 12 及以上启用系统自动画中画;Android 8–11 在离开应用时尝试进入。设备需支持画中画,系统需允许 CrossDesk 使用该功能。未连接、尚无画面或正在打开系统文件选择器时不自动进入。
Android 版本满足要求不代表固件提供画中画,部分低内存模式设备会禁用该功能。以系统的 `FEATURE_PICTURE_IN_PICTURE` 检测为准,单独允许画中画权限不能补齐系统能力。无系统画中画或权限被禁止时,连接建立后自动启动前台服务兜底;画中画进入失败也尝试使用该兜底。控制菜单不提供“画中画”或“后台保活”按钮,两者均在切换应用时自动处理。
画中画仅显示完整远程画面,隐藏本地光标、悬浮球、鼠标条和键盘,并释放远程按键。使用原有视频 Surface 和 RTC 连接,进入小窗时不会关闭音视频;通过系统小窗返回全屏继续操作。画面比例根据远端尺寸更新,超宽或超长画面在系统允许的比例范围内完整显示并留黑边。
正常画中画不启动兜底服务,可见的小窗使 Activity 保持在 started 状态,进入时仅暂停交互。关闭小窗会结束会话,不自动转为隐藏的后台连接。
兜底模式通过前台服务保留原 RTC/信令连接,并显示带“返回”和“断开”操作的常驻通知。后台停止本地画面渲染及音频播放,不创建悬浮窗;视频传输和解码不做协议层暂停。返回应用后重新绑定 Surface 并请求关键帧,恢复原静音状态、显示器和画面设置,不重新登录或连接远端。会话状态独立于 Activity,页面被系统回收后可恢复,整个进程被系统终止则不能恢复原连接。
服务仅用于用户主动建立且已成功连接的远程会话,不用于首页待机。Android 14 及以上使用 `specialUse` 前台服务类型并声明远程控制连接用途;Android 13 及以上在兜底首次启用时请求通知权限,拒绝后系统仅在活动应用管理中显示服务。CPU 部分唤醒锁仅在兜底会话后台期间持有,返回前台、断开、移除任务或服务销毁时释放。通知断开、远端断开、移除任务、撤回授权和强制停止均结束会话及服务,不自动重连。系统文件选择器仍有上述五分钟限制;系统强杀或网络中断仍可能结束连接。
首页设置里的“画面偏好”保存在本机,作为下一次连接的默认偏好;会话内画面设置与 iOS 一样只影响当前连接。初始质量按屏幕长边选择低(不超过 1280 像素)或中,采集帧率为 30 fps,电脑端报告支持后自动下发;旧版电脑未报告支持时禁用控件。网络页的 FPS 统计实际提交给 Android Surface 的帧,画面延时使用 MiniRTC 校准后的采集时间至提交时刻的估计值,未完成校准时显示“—”;RTT 使用 0.25 权重平滑,3 秒未更新的数据会过期。切换屏幕清除旧画面的帧率、分辨率和画面延时,保留网络统计。
采集时间的有效性在接收时检查,本机解码和显示等待计入画面延时;真实延时超过 5 秒也会继续显示,不会当成无效时间戳过滤。显示线程复用解码器的 CPU NV12 缓冲区,只保留一帧待显示画面,切换显示器或 Surface 时清除旧帧,会话结束时先停止显示线程再销毁原生连接。
## 隐私授权
未完成隐私授权时,首次打开或从后台返回应用会自动显示离线隐私政策;需要主动勾选阅读并同意后才能联网,与 iOS 一致。暂不同意后,本次停留不会反复弹窗,仍可浏览设置和本地连接记录。设置 → 隐私 → 隐私与授权可离线查看政策或撤回授权;撤回后下次进入应用会再次提示。
## 远程画面预览
设置 → 隐私中的“保存远程画面预览”默认关闭,完成联网授权后可开启。与 iOS 一致,开启前说明预览可能包含个人或工作信息;每次连接只在实际显示画面后保存一张预览,居中裁剪为 640×360、JPEG 质量 78。截图来自远程视频的 Surface,不包含悬浮菜单、键盘、本地光标或画面外的黑边;压缩、读写和解码在串行后台线程执行,不复制完整 4K 位图,也不连续截图。
图片保存在应用私有、不参与备份的 `RecentConnectionThumbnails` 目录,不上传、不写入系统相册。文件按服务器与远端 ID 隔离,最近连接卡片异步加载;未开启、没有预览或图片损坏时继续显示平台封面。删除或淘汰连接记录会删除对应预览。
“清除预览图”保留连接记录、密码和开关状态,下一次连接仍可保存新的预览。关闭保存选项或撤回联网授权会关闭保存并清除全部预览。清除时立即使未完成的截图和读取请求失效,删除与保存共用串行队列,防止已清除的图片被旧截图重新写回;清除失败会显示提示,可再次重试。
## 通知公告
首页铃铛展示全部未读公告的数量(超过 99 条显示 99+)。授权并连接服务器后,通过已有身份信令请求 `announcements_list`,摘要每页 200 条、正文每页 20 条;不依赖远程桌面连接。列表支持刷新、滚动加载更多、长按或左滑删除,删除前需确认,且仅隐藏本机的当前版本。打开详情即标记已读;服务器更新公告版本后会重新显示并计为未读。详情正文保留纯文本和换行,支持 HTTP(S) 地址及 `[文字](https://...)` 链接,不执行 HTML 或其他协议。
阅读和删除标记以原子文件保存在不参与备份的 `AnnouncementReads` 目录,按主机名、端口和本机设备 ID 隔离;写入失败会提示并保留原状态。内容只缓存于内存。收到 `announcements_changed` 时刷新,分页期间目录版本改变时重新获取;过期请求、断线前的回复不会覆盖新状态。请求失败或 12 秒超时可重试;未授权不联网,进入后台停止请求。自托管服务需要支持与桌面及 iOS 相同的公告协议。
## 验证
连接 arm64 设备或启动 arm64 模拟器后,在 `apps/android` 执行:
```sh
./gradlew :app:assembleDebug :app:assembleDebugAndroidTest :app:lintDebug
"$ANDROID_HOME/platform-tools/adb" install -r app/build/outputs/apk/debug/app-debug.apk
"$ANDROID_HOME/platform-tools/adb" install -r app/build/outputs/apk/androidTest/debug/app-debug-androidTest.apk
"$ANDROID_HOME/platform-tools/adb" shell am instrument -w -r cn.crossdesk.mobile.test/androidx.test.runner.AndroidJUnitRunner
"$ANDROID_HOME/platform-tools/adb" uninstall cn.crossdesk.mobile.test
python3 test/verify_apk.py app/build/outputs/apk/debug/app-debug.apk
python3 test/run_native.py
```
以上流程覆盖安装应用并只卸载测试包,保留已有应用数据;多台设备同时连接时,在每个 `adb` 命令中加上 `-s <设备序列号>`。`connectedDebugAndroidTest` 可能卸载被测应用及其数据,不用于已有连接记录或密码的设备。
测试源码、资源和检查入口统一位于 `test/`:
- `test/native/`:本机 C++ 协议、帧队列与画面延时回归,由 `test/run_native.py` 编译运行。
- `test/android/java/`:非 UI 的 Android 功能回归,覆盖需要 Android API 或 JNI 的逻辑,包括设备在线状态刷新、过期与信令重连。Gradle 的 `androidTest` 源集显式引用此目录。
- `test/android/assets/tls/`:本机环回 TLS 测试证书,仅进入测试 APK。
- `test/verify_apk.py`:发布 APK 的 arm64 ABI、16 KB ELF / ZIP 对齐、许可证完整性和源码资料检查。
设备回归仅保留 TLS 证书校验、凭据加密及服务器隔离、原生连接生命周期、键盘映射、画面设置状态、缩放及输入坐标计算、网络采样、公告与预览数据持久化、版本兼容判断。预览存储测试使用生成的纯色位图,不采集屏幕或视频画面。
画面手势需在远程会话中人工验证:两种鼠标模式均检查捏合放大至 10 倍、缩回 1 倍、放大后的双指平移和边界限制;原始比例下双指滑动仍控制滚轮,捏合及平移不应产生远端点击或拖动。放大后检查点击与光标位置一致、横竖屏切换后位置正确,切换显示器或重新连接恢复 1 倍。自动化回归只验证几何计算,不注入 UI 手势。
UI 验证统一由人工完成,不维护页面导航、布局、动画、悬浮窗和截图采集的自动化用例。许可证和构建资料的完整性由 `test/verify_apk.py` 检查。
控制栏联调需在真实远程会话中验证文件选择及取消、收发文件内容一致性、接收后导出、传输中断线;Windows 远端分别检查系统服务开启与关闭时的 Ctrl+Alt+Del 行为。
画中画需在真实会话中检查切换应用自动进入、其他应用前台时画面持续更新、返回全屏、关闭小窗、静音、超宽及竖屏画面、文件选择器取消、系统禁用画中画和锁屏。
前台服务兜底需在无原生画中画的实机上验证后台往返、Activity 重建时复用会话、通知断开、旧通知隔离、远端断开时释放唤醒锁,以及实际网络和画面恢复。设备测试前后应备份、核对并恢复服务器等应用设置,避免中断的测试留下本地测试地址。
## MediaCodec 编解码
实现参照 MiniRTC 的 NVCodec 分层:`src/media/mediacodec/` 负责硬件后端、能力查询和 JNI/Surface 资源;`src/media/video/encode/mediacodec/` 与 `src/media/video/decode/mediacodec/` 分别接入编码器、解码器接口,并负责同编码格式的软件回退。Android 工程直接编译这些源码。通用 API 仅需启用 `hardware_acceleration` 和 `native_video_output`。JavaVM 由 Android JNI 适配层在 `JNI_OnLoad` 中设置到后端私有实现;该桥接不安装为 SDK 头文件,也不导出为动态库符号。当前能力查询和 SurfaceTexture 创建依赖 JNI,缺少 JavaVM 时仍可使用软件编解码。独立输出线程在画面停止更新后仍会取出最后一帧,空闲时休眠。
- H.264 / AV1 由系统能力查询选择硬件组件,支持编码码率调整、请求关键帧和分辨率变化。编码输入为 8 位 NV12,硬件需支持 NV12 / I420 ByteBuffer 输入;不满足时回退 OpenH264 / SVT-AV1。当前应用仍是控制端,库的编码能力不代表已实现安卓被控端。
- 解码原生输出为可保留/释放的 MediaCodec 缓冲区,显示线程直接提交 Surface。切换显示器、销毁 Surface 和切回软件输出时解除旧 Surface 绑定。缓冲区在解码器重建或销毁后不可再次显示;未显示的缓冲区自动归还。
- 关闭原生输出时,支持将硬件 NV12 / I420 输出按行距、填充高度和裁剪范围转换为紧凑 NV12;未知布局回退软件。
- Retroid Pocket 2S 的 `OMX.sprd.av1.decoder` 实际加载软件 dav1d,虽被系统标成硬件组件,仍明确排除;AV1 使用软件回退。H.264 可使用 `OMX.sprd.h264.encoder` / `OMX.sprd.h264.decoder`。
AV1 硬件路径尚无对应实机验证;Retroid 上使用 dav1d 软件解码。
## 开源资料
应用为 GPL-3.0-only,MiniRTC 为 LGPL-3.0-only,其余组件保留各自许可证。`scripts/generate_notices.py` 复用仓库已有的依赖通知,选取 Android 实际使用的组件;`licenses/additional-notices.json` 补充 OpenH264、GNU libiconv 和 NDK / LLVM 运行时通知。APK 的开源信息页提供完整内容。可以修改库源码、重新链接,并使用自己的 Android 密钥签名安装。
设置 → 关于使用与 iOS 相同的分组及入口:版本、软件许可、开源组件、源码与构建说明。软件许可中可分别阅读 GNU GPL 第 3 版及开源软件权利说明;开源组件页单独展示 OpenFEC 告知,其余组件列出名称和许可证,详情包含版本、源码、适用的构建配方和每一份许可文档。内容按 Android 构建生成,不显示未使用的 iOS 依赖,Android 签名说明替换 Apple 签名说明。
APK 保留完整 `THIRD_PARTY_NOTICES.txt`,并生成轻量的 `ThirdPartyLicenses.json` 索引、72 份独立许可文档及 `SourceMetadata.json`。打开文档时才读取正文,长文按有限长度分块显示,支持文本选择、复制与网页链接;打包验证核对每份正文的 SHA-256。源码页面显示标签或提交版本及未发布修改提示,源码链接指向基础提交。当前 Android 构建说明、构建脚本、MiniRTC、OpenSSL 及 SVT-AV1 配方随 APK 离线提供,避免开发版链接指向基础提交中尚不存在的 Android 文件。
+43
View File
@@ -0,0 +1,43 @@
plugins { id 'com.android.application' }
android {
namespace 'cn.crossdesk.mobile'
compileSdk 36
ndkVersion '28.2.13676358'
defaultConfig {
applicationId 'cn.crossdesk.mobile'
minSdk 26
targetSdk 36
versionCode providers.gradleProperty('crossdeskVersionCode').get().toInteger()
versionName providers.gradleProperty('crossdeskVersionName').get()
ndk { abiFilters 'arm64-v8a' }
testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_17
targetCompatibility JavaVersion.VERSION_17
}
sourceSets.main.jniLibs.srcDirs = [layout.buildDirectory.dir('native')]
sourceSets.main.assets.srcDirs += [layout.buildDirectory.dir('generated/notices')]
sourceSets.androidTest.java.srcDirs = ['../test/android/java']
sourceSets.androidTest.assets.srcDirs = ['../test/android/assets']
buildTypes.release { minifyEnabled false }
packaging.jniLibs.useLegacyPackaging = false
}
dependencies {
androidTestImplementation 'androidx.test:runner:1.7.0'
androidTestImplementation 'androidx.test.ext:junit:1.3.0'
}
tasks.register('buildMiniRtc', Exec) {
workingDir rootProject.projectDir
commandLine 'python3', 'scripts/build_native.py'
environment 'ANDROID_HOME', androidComponents.sdkComponents.sdkDirectory.get().asFile.absolutePath
}
tasks.named('preBuild').configure { dependsOn 'buildMiniRtc' }
tasks.register('generateNotices', Exec) {
workingDir rootProject.projectDir
commandLine 'python3', 'scripts/generate_notices.py'
}
tasks.named('preBuild').configure { dependsOn 'generateNotices' }
@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application android:theme="@style/AppTheme" android:label="CrossDesk"
android:icon="@mipmap/ic_launcher" android:allowBackup="false"
android:fullBackupContent="false"
android:dataExtractionRules="@xml/data_extraction_rules"
android:supportsRtl="true" android:usesCleartextTraffic="false">
<service android:name=".RemoteSessionService" android:exported="false"
android:foregroundServiceType="specialUse">
<property android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
android:value="Maintain a user-started remote desktop RTC/control session when picture-in-picture is unavailable. Background rendering and audio are suspended; the user can return or disconnect from the notification." />
</service>
<activity android:name=".MainActivity" android:exported="true"
android:launchMode="singleTop"
android:supportsPictureInPicture="true"
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|keyboard|keyboardHidden"
android:resizeableActivity="true"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
@@ -0,0 +1,138 @@
package cn.crossdesk.mobile;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import static cn.crossdesk.mobile.MobileUi.*;
/** Mirrors the iOS About / component / source / document navigation. */
final class AboutPages {
private final MainActivity activity;
private final MobileUi ui;
private final Runnable settings;
private final LicenseCatalog catalog;
private final AppUpdateChecker updates;
private TextView updateStatus, updateLink, checkButton;
private LinearLayout updateRow;
AboutPages(MainActivity activity,MobileUi ui,Runnable settings,AppUpdateChecker updates){
this.activity=activity;this.ui=ui;this.settings=settings;this.updates=updates;
LicenseCatalog loaded;try{loaded=new LicenseCatalog(activity);}catch(Exception error){loaded=null;}catalog=loaded;
}
void show(){
LinearLayout content=activity.formPage("about","关于 CrossDesk",settings);
LinearLayout version=activity.section(content,"");value(version,"版本",applicationVersion());
updateRow=ui.row();updateRow.setPadding(ui.dp(16),0,ui.dp(16),0);updateRow.addView(activity.updateDot(),ui.size(8,8));
updateLink=ui.action("",BLUE,()->open("https://crossdesk.cn"));updateLink.setGravity(Gravity.START|Gravity.CENTER_VERTICAL);updateLink.setPadding(ui.dp(8),ui.dp(12),0,ui.dp(12));updateRow.addView(updateLink,new LinearLayout.LayoutParams(0,-2,1));version.addView(updateRow);
updateStatus=ui.text("",13,false);updateStatus.setPadding(ui.dp(16),ui.dp(8),ui.dp(16),ui.dp(8));version.addView(updateStatus);
checkButton=ui.action("检查更新",BLUE,activity::checkAppUpdates);version.addView(checkButton);renderUpdates();ui.gap(content,28);
if(catalog==null){unavailable(content);return;}
LinearLayout links=activity.section(content,"");
activity.link(links,"软件许可","",()->component(catalog.find("crossdesk"),this::show));ui.divider(links);
activity.link(links,"开源组件","",this::components);ui.divider(links);
activity.link(links,"源码与构建说明","",this::source);
activity.footer(content,"许可与版权声明可离线查阅。");
}
private String applicationVersion(){
return activity.applicationVersion();
}
void renderUpdates(){
if(updateStatus==null)return;
updateRow.setVisibility(updates.updateAvailable()?View.VISIBLE:View.GONE);
updateLink.setText("新版本可用:v"+updates.availableVersion);
String status=!activity.hasNetworkConsent()?"完成隐私授权后可检查更新":switch(updates.status){
case CHECKING -> "正在检查更新…";
case UP_TO_DATE -> "当前已是最新版本";
case FAILED -> "检查失败,请稍后重试";
default -> "";
};
updateStatus.setText(status);updateStatus.setVisibility(status.isEmpty()?View.GONE:View.VISIBLE);
updateStatus.setTextColor(updates.status==AppUpdateChecker.Status.FAILED?RED:SECONDARY);
checkButton.setEnabled(updates.status!=AppUpdateChecker.Status.CHECKING);
checkButton.setAlpha(checkButton.isEnabled()?1f:.5f);
}
private void components(){
LinearLayout content=activity.formPage("open-source","开源组件",this::show);
LinearLayout notice=activity.section(content,"OpenFEC 告知");
paragraph(notice,"本应用使用 OpenFEC 提供前向纠错功能,遵循 CeCILL-C 1.0 许可。该许可规定了有限保证及责任限制,详情见许可全文。",SECONDARY);
ui.divider(notice);paragraph(notice,"(c) Copyright 2009 - 2012 INRIA - All rights reserved",INK);ui.divider(notice);
activity.link(notice,"OpenFEC 许可与源码","",()->component(catalog.find("openfec"),this::components));ui.gap(content,28);
LinearLayout list=activity.section(content,"");boolean first=true;
for(LicenseCatalog.Component item:catalog.components){
if(item.id.equals("crossdesk")||item.id.equals("openfec"))continue;
if(!first)ui.divider(list);first=false;
LinearLayout row=ui.row();row.setPadding(ui.dp(16),ui.dp(12),ui.dp(12),ui.dp(12));
LinearLayout labels=ui.column();labels.addView(ui.text(item.name,16,false));ui.gap(labels,4);
TextView license=ui.text(item.license,12,false);license.setTextColor(SECONDARY);labels.addView(license);
row.addView(labels,new LinearLayout.LayoutParams(0,-2,1));TextView chevron=ui.text(" ›",23,false);chevron.setTextColor(0xFFB7B7BD);row.addView(chevron);
row.setContentDescription(item.name+","+item.license);row.setClickable(true);row.setFocusable(true);row.setOnClickListener(v->component(item,this::components));list.addView(row);
}
activity.footer(content,"各组件遵循所列开源许可证,其授予的权利不受本应用普通使用条款限制。查看源码需要网络连接。");
}
private void component(LicenseCatalog.Component item,Runnable back){
LinearLayout content=activity.formPage("license:"+item.id,item.name,back);LinearLayout info=activity.section(content,"");
String version=item.id.equals("crossdesk")?applicationVersion():item.version.length()==40?item.version.substring(0,12):item.version;
value(info,"版本",version);ui.divider(info);value(info,"许可",item.license);ui.divider(info);
external(info,"查看源码",item.sourceURL);
if(!item.buildDocuments.isEmpty()||!item.buildSourceURL.isEmpty()){
ui.divider(info);
if(!item.buildDocuments.isEmpty())activity.link(info,"构建配方与项目补丁","",()->buildSources(item,back));
else external(info,"构建配方与项目补丁",item.buildSourceURL);
}
ui.gap(content,16);LinearLayout docs=activity.section(content,"许可与版权声明");
for(int i=0;i<item.documents.size();i++){
if(i>0)ui.divider(docs);LicenseCatalog.Document document=item.documents.get(i);
activity.link(docs,item.documentTitle(document),"",()->document(item.documentTitle(document),document,()->component(item,back)));
}
}
private void source(){
LinearLayout content=activity.formPage("source","源码与构建说明",this::show);
LinearLayout info=activity.section(content,"本版本源码与构建说明");
if(catalog.source==null){paragraph(info,"本版本源码信息暂不可用。",SECONDARY);ui.divider(info);external(info,"项目主页","https://github.com/kunkundi/crossdesk");return;}
String revision=catalog.source.optString("revision","");String tag=catalog.source.isNull("tag")?"":catalog.source.optString("tag","");
value(info,"源码版本",tag.isEmpty()?revision.substring(0,Math.min(12,revision.length())):tag);ui.divider(info);
if(catalog.source.optBoolean("isModified")){paragraph(info,"开发版本包含尚未发布的修改,以下链接为基础版本源码。",SECONDARY);ui.divider(info);}
external(info,"查看源码",catalog.source.optString("sourceURL",catalog.find("crossdesk").sourceURL));ui.divider(info);
try{
List<LicenseCatalog.Document> documents=LicenseCatalog.documents(catalog.source.optJSONArray("buildDocuments"));
if(!documents.isEmpty())actionLink(info,"构建说明",()->document("构建说明",documents.get(0),this::source));
else external(info,"构建说明",catalog.source.optString("buildInstructionsURL","https://github.com/kunkundi/crossdesk"));
}catch(org.json.JSONException error){paragraph(info,"本版本源码信息暂不可用。",SECONDARY);}
}
private void buildSources(LicenseCatalog.Component item,Runnable back){
LinearLayout content=activity.formPage("build:"+item.id,"构建配方与项目补丁",()->component(item,back));
if(!item.buildSourceURL.isEmpty()){LinearLayout upstream=activity.section(content,"");external(upstream,"查看源码",item.buildSourceURL);ui.gap(content,28);}
LinearLayout docs=activity.section(content,"");
for(int i=0;i<item.buildDocuments.size();i++){
if(i>0)ui.divider(docs);LicenseCatalog.Document document=item.buildDocuments.get(i);
activity.link(docs,document.title,"",()->document(document.title,document,()->buildSources(item,back)));
}
}
private void document(String title,LicenseCatalog.Document document,Runnable back){
try{activity.licenseDocument(title,LicenseCatalog.read(activity,document.asset),back);}catch(java.io.IOException error){unavailable(activity.formPage("license-error",title,back));}
}
private void value(LinearLayout parent,String label,String value){
LinearLayout row=ui.row();row.setPadding(ui.dp(16),ui.dp(14),ui.dp(16),ui.dp(14));
TextView key=ui.text(label,16,false);key.setPadding(0,0,ui.dp(16),0);row.addView(key);
TextView content=ui.text(value,16,false);content.setTextColor(SECONDARY);content.setGravity(Gravity.END);content.setTextIsSelectable(true);row.addView(content,new LinearLayout.LayoutParams(0,-2,1));parent.addView(row);
}
private void paragraph(LinearLayout parent,String text,int color){TextView view=ui.text(text,13,false);view.setTextColor(color);view.setPadding(ui.dp(16),ui.dp(12),ui.dp(16),ui.dp(12));view.setLineSpacing(ui.dp(3),1);parent.addView(view);}
private void external(LinearLayout parent,String title,String url){
actionLink(parent,title,()->open(url));
}
private void actionLink(LinearLayout parent,String title,Runnable action){TextView link=ui.action(title,BLUE,action);link.setTypeface(android.graphics.Typeface.DEFAULT);link.setGravity(Gravity.START|Gravity.CENTER_VERTICAL);link.setPadding(ui.dp(16),ui.dp(12),ui.dp(16),ui.dp(12));parent.addView(link);}
private void open(String url){
Uri uri=Uri.parse(url);if(!"https".equals(uri.getScheme())&&!"http".equals(uri.getScheme()))return;
try{activity.startActivity(new Intent(Intent.ACTION_VIEW,uri).addCategory(Intent.CATEGORY_BROWSABLE));}catch(ActivityNotFoundException error){Toast.makeText(activity,"未找到可打开链接的浏览器",Toast.LENGTH_SHORT).show();}
}
private void unavailable(LinearLayout content){
content.setGravity(Gravity.CENTER);ui.gap(content,32);TextView icon=ui.text("▤",36,false);icon.setTextColor(SECONDARY);content.addView(icon);ui.gap(content,12);
content.addView(ui.text("无法读取开源许可",17,true));TextView message=ui.text("应用中的许可文件缺失或损坏,请重新安装应用。",14,false);message.setGravity(Gravity.CENTER);message.setTextColor(SECONDARY);content.addView(message);
}
}
@@ -0,0 +1,235 @@
package cn.crossdesk.mobile;
import android.os.Handler;
import android.os.Looper;
import android.util.AtomicFile;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.*;
/** Main-thread inbox. The server owns content; this device owns read/dismissed revisions. */
final class AnnouncementInbox implements AutoCloseable {
interface Sender { void send(JSONObject request, String requestId); }
static final class Item {
final long id, revision, updatedAt;
final String title, body;
boolean read;
Item(JSONObject json) throws Exception {
id=integer(json,"id");revision=integer(json,"revision");updatedAt=integer(json,"updated_at");
title=string(json,"title");body=string(json,"body");
if(id<=0||revision<=0||updatedAt<=0||updatedAt>32_503_680_000L||
title.getBytes(StandardCharsets.UTF_8).length>240||body.getBytes(StandardCharsets.UTF_8).length>8000)
throw new IllegalArgumentException("Invalid announcement");
}
}
final List<Item> items=new ArrayList<>();
int total, unread;
boolean loaded, loading, failed, readSaveFailed, deleteFailed;
Sender sender;
Runnable changed=()->{};
private final File directory;
private final Handler handler=new Handler(Looper.getMainLooper());
private final Map<Long,Long> reads=new HashMap<>(), dismissed=new HashMap<>();
private Map<Long,Long> catalog=new LinkedHashMap<>(), pendingCatalog=new LinkedHashMap<>();
private final Map<Integer,List<Long>> pageIds=new HashMap<>();
private final Map<Integer,List<Item>> pageBodies=new HashMap<>();
private long catalogRevision=-1, pendingRevision=-1;
private int pendingTotal, pageOffset, visibleLimit=20;
private boolean summary=true, connected;
private String scope="", requestId;
private AtomicFile file;
private Runnable timeout;
AnnouncementInbox(File directory){this.directory=directory;}
boolean isConnected(){return connected;}
void configure(String host,int port,String deviceId){
if(host.isEmpty()||port<=0||deviceId.isEmpty())return;
String canonical=host.toLowerCase(Locale.ROOT);
if(canonical.endsWith("."))canonical=canonical.substring(0,canonical.length()-1);
String next=new JSONArray().put(canonical).put(port).put(deviceId).toString();
if(scope.equals(next))return;
boolean wasConnected=connected;reset();connected=wasConnected;scope=next;
try{
byte[] hash=MessageDigest.getInstance("SHA-256").digest(scope.getBytes(StandardCharsets.UTF_8));
StringBuilder name=new StringBuilder();for(byte b:hash)name.append(String.format(Locale.ROOT,"%02x",b&255));
file=new AtomicFile(new File(directory,name+".json"));loadLocalState();
}catch(Exception error){file=null;}
refresh();
}
void reset(){
cancelRequest();scope="";file=null;connected=false;items.clear();reads.clear();dismissed.clear();
catalog.clear();pendingCatalog.clear();pageIds.clear();pageBodies.clear();
catalogRevision=pendingRevision=-1;pendingTotal=pageOffset=total=unread=0;visibleLimit=20;
loaded=failed=readSaveFailed=deleteFailed=false;changed.run();
}
void setConnected(boolean value){
if(connected==value)return;connected=value;
if(value)refresh();else{cancelRequest();changed.run();}
}
void refresh(){
cancelRequest();pendingCatalog=new LinkedHashMap<>();pendingRevision=-1;pendingTotal=0;summary=true;
request(0);changed.run();
}
void loadMore(){
if(!connected||loading||failed||catalogRevision<0||visibleLimit>=total)return;
visibleLimit+=Math.min(20,total-visibleLimit);rebuild();changed.run();
}
Item find(long id,long revision){
for(Item item:items)if(item.id==id&&item.revision==revision)return item;return null;
}
void markRead(Item item){
if(find(item.id,item.revision)==null||Objects.equals(reads.get(item.id),item.revision))return;
Map<Long,Long> updated=new HashMap<>(reads);updated.put(item.id,item.revision);
if(!saveLocalState(updated,dismissed)){readSaveFailed=true;changed.run();return;}
reads.clear();reads.putAll(updated);readSaveFailed=deleteFailed=false;updateReadingState();changed.run();
}
void dismiss(Item item){
if(find(item.id,item.revision)==null){deleteFailed=true;changed.run();return;}
Map<Long,Long> updated=new HashMap<>(dismissed);updated.put(item.id,item.revision);
if(!saveLocalState(reads,updated)){deleteFailed=true;changed.run();return;}
dismissed.clear();dismissed.putAll(updated);deleteFailed=readSaveFailed=false;
if(summary&&loading){items.removeIf(this::isDismissed);updateReadingState();}
else{cancelRequest();rebuild();}
changed.run();
}
void failed(String id){
if(!Objects.equals(requestId,id)||id==null)return;
cancelRequest();failed=true;changed.run();
}
void receive(JSONObject message){
Object identifier=message.opt("request_id");
if(!(identifier instanceof String)||!identifier.equals(requestId))return;
String id=(String)identifier;
try{
if(!"announcements".equals(string(message,"type"))||message.has("error"))throw new IllegalArgumentException();
Object summaryFlag=message.get("summary_only");
long offsetValue=integer(message,"offset"), totalValue=integer(message,"total");
long revision=integer(message,"catalog_revision");JSONArray entries=message.getJSONArray("items");
if(!(summaryFlag instanceof Boolean)||((Boolean)summaryFlag)!=summary||offsetValue<0||
totalValue<offsetValue||totalValue>Integer.MAX_VALUE||revision<0||
entries.length()!=Math.min(summary?200:20,totalValue-offsetValue))throw new IllegalArgumentException();
int offset=(int)offsetValue, count=(int)totalValue;
LinkedHashMap<Long,Long> entriesById=new LinkedHashMap<>();
for(int i=0;i<entries.length();i++){
JSONObject entry=entries.getJSONObject(i);long key=integer(entry,"id"), version=integer(entry,"revision");
if(key<=0||version<=0||entriesById.put(key,version)!=null)throw new IllegalArgumentException();
}
long expected=summary?pendingRevision:catalogRevision;
if(expected>=0&&expected!=revision){refresh();return;}
if(summary){
if(offset!=pendingCatalog.size()||(pendingRevision>=0&&pendingTotal!=count))throw new IllegalArgumentException();
for(Map.Entry<Long,Long> entry:entriesById.entrySet())
if(pendingCatalog.put(entry.getKey(),entry.getValue())!=null)throw new IllegalArgumentException();
pendingRevision=revision;pendingTotal=count;cancelRequest();
if(pendingCatalog.size()<pendingTotal){request(pendingCatalog.size());changed.run();return;}
if(catalogRevision!=pendingRevision){pageIds.clear();pageBodies.clear();}
catalog=new LinkedHashMap<>(pendingCatalog);catalogRevision=pendingRevision;
reads.keySet().retainAll(catalog.keySet());dismissed.keySet().retainAll(catalog.keySet());
}else{
if(offset!=pageOffset||count!=catalog.size())throw new IllegalArgumentException();
List<Item> bodies=new ArrayList<>();
for(int i=0;i<entries.length();i++){
Item item=new Item(entries.getJSONObject(i));
if(!Objects.equals(catalog.get(item.id),item.revision))throw new IllegalArgumentException();
// A repeated ID on another body page must not create duplicate rows.
for(Map.Entry<Integer,List<Long>> page:pageIds.entrySet())
if(page.getKey()!=offset&&page.getValue().contains(item.id))throw new IllegalArgumentException();
bodies.add(item);
}
cancelRequest();pageIds.put(offset,new ArrayList<>(entriesById.keySet()));pageBodies.put(offset,bodies);
}
failed=false;rebuild();changed.run();
}catch(Exception error){failed(id);}
}
private void request(int offset){
if(!connected||scope.isEmpty())return;
String id=UUID.randomUUID().toString();
try{
JSONObject payload=new JSONObject().put("type","announcements_list").put("request_id",id)
.put("summary_only",summary).put("offset",offset);
requestId=id;loading=true;failed=false;timeout=()->failed(id);handler.postDelayed(timeout,12_000);
if(sender!=null)sender.send(payload,id);else failed(id);
}catch(Exception error){failed(id);}
}
private void cancelRequest(){
if(timeout!=null)handler.removeCallbacks(timeout);timeout=null;requestId=null;loading=false;
}
private boolean isDismissed(Item item){return Objects.equals(dismissed.get(item.id),item.revision);}
private void updateReadingState(){
total=unread=0;
for(Map.Entry<Long,Long> entry:catalog.entrySet()){
if(Objects.equals(dismissed.get(entry.getKey()),entry.getValue()))continue;
total++;if(!Objects.equals(reads.get(entry.getKey()),entry.getValue()))unread++;
}
for(Item item:items)item.read=Objects.equals(reads.get(item.id),item.revision);
}
private void rebuild(){
updateReadingState();int wanted=Math.min(visibleLimit,total), position=0;Integer nextOffset=null;
List<Item> visible=new ArrayList<>();Set<Integer> retainedPages=new HashSet<>();summary=false;
if(wanted>0)for(int offset=0;offset<catalog.size();offset+=20){
List<Long> ids=pageIds.get(offset);if(ids==null){nextOffset=offset;break;}
Set<Long> selection=new HashSet<>();
for(long id:ids){
Long revision=catalog.get(id);if(revision==null||Objects.equals(dismissed.get(id),revision))continue;
if(position<wanted)selection.add(id);position++;
}
if(selection.isEmpty()){pageBodies.remove(offset);continue;}
retainedPages.add(offset);List<Item> bodies=pageBodies.get(offset);
if(bodies==null){nextOffset=offset;break;}
for(Item item:bodies)if(selection.contains(item.id))visible.add(item);
if(visible.size()==wanted)break;
}
if(visible.size()==wanted)pageBodies.keySet().retainAll(retainedPages);
else{
Set<Long> retained=new HashSet<>();for(Item item:visible)retained.add(item.id);
for(Item item:items)if(Objects.equals(catalog.get(item.id),item.revision)&&!isDismissed(item)&&retained.add(item.id)){
visible.add(item);if(visible.size()==wanted)break;
}
}
items.clear();items.addAll(visible);loaded=true;updateReadingState();
if(nextOffset!=null){pageOffset=nextOffset;request(nextOffset);}
}
private void loadLocalState(){
if(file==null||file.getBaseFile().length()>16*1024*1024)return;
try{
JSONObject saved=new JSONObject(new String(file.readFully(),StandardCharsets.UTF_8));
long version=integer(saved,"version");
if(!scope.equals(string(saved,"scope"))||(version!=1&&version!=2))return;
loadRevisions(saved.optJSONObject("reads"),reads);loadRevisions(saved.optJSONObject("dismissed"),dismissed);
}catch(Exception ignored){}
}
private static void loadRevisions(JSONObject json,Map<Long,Long> target){
if(json==null)return;
for(Iterator<String> keys=json.keys();keys.hasNext();){
String key=keys.next();
try{long id=Long.parseLong(key), revision=integer(json,key);if(id>0&&revision>0)target.put(id,revision);}catch(Exception ignored){}
}
}
private boolean saveLocalState(Map<Long,Long> readValues,Map<Long,Long> dismissedValues){
if(file==null)return false;FileOutputStream output=null;
try{
if(!directory.isDirectory()&&!directory.mkdirs())return false;
JSONObject saved=new JSONObject().put("version",2).put("scope",scope)
.put("reads",revisions(readValues)).put("dismissed",revisions(dismissedValues));
byte[] bytes=saved.toString().getBytes(StandardCharsets.UTF_8);
output=file.startWrite();output.write(bytes);output.getFD().sync();file.finishWrite(output);output=null;
// AtomicFile logs some rename failures instead of throwing; verify the committed file.
return Arrays.equals(bytes,file.readFully());
}catch(Exception error){if(output!=null)file.failWrite(output);return false;}
}
private static JSONObject revisions(Map<Long,Long> values)throws Exception{
JSONObject json=new JSONObject();for(Map.Entry<Long,Long> entry:values.entrySet())json.put(entry.getKey().toString(),entry.getValue());return json;
}
private static long integer(JSONObject json,String key)throws Exception{
Object value=json.get(key);if(!(value instanceof Integer)&&!(value instanceof Long))throw new IllegalArgumentException(key);
return ((Number)value).longValue();
}
private static String string(JSONObject json,String key)throws Exception{
Object value=json.get(key);if(!(value instanceof String))throw new IllegalArgumentException(key);return (String)value;
}
@Override public void close(){cancelRequest();connected=false;sender=null;changed=()->{};}
}
@@ -0,0 +1,72 @@
package cn.crossdesk.mobile;
import android.content.Intent;
import android.net.Uri;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.URLSpan;
import android.view.View;
import android.widget.Toast;
import java.util.Locale;
/** Plain text plus HTTP(S) links, matching iOS; never interpret HTML or arbitrary Markdown. */
final class AnnouncementText {
static CharSequence format(String body){
String text=body.replace("\r\n","\n");SpannableStringBuilder result=new SpannableStringBuilder();
for(int position=0;position<text.length();){
if(text.charAt(position)=='['){
int labelEnd=text.indexOf(']',position+1), start=labelEnd+2;
if(labelEnd>position+1&&start<text.length()&&text.charAt(labelEnd+1)=='('&&
!text.substring(position+1,labelEnd).matches("(?s).*[\\[\\]\\r\\n].*")&&hasScheme(text,start)){
int end=urlEnd(text,start);
if(end<text.length()&&text.charAt(end)==')'&&
appendLink(result,text.substring(position+1,labelEnd),text.substring(start,end))){
position=end+1;continue;
}
}
}
if(hasScheme(text,position)){
int end=urlEnd(text,position);
while(end>position&&".,;:!?".indexOf(text.charAt(end-1))>=0)end--;
String address=text.substring(position,end);
if(appendLink(result,address,address)){position=end;continue;}
}
result.append(text.charAt(position++));
}
return result;
}
static boolean isWebURL(String address){
if(address==null)return false;
for(int i=0;i<address.length();i++){char c=address.charAt(i);if(c<=0x20||c==0x7f||"\\<>\"".indexOf(c)>=0)return false;}
Uri uri=Uri.parse(address);String scheme=uri.getScheme(),host=uri.getHost();
return scheme!=null&&(scheme.equalsIgnoreCase("http")||scheme.equalsIgnoreCase("https"))&&host!=null&&!host.isEmpty();
}
private static boolean hasScheme(String text,int start){
String prefix=text.substring(start,Math.min(text.length(),start+8)).toLowerCase(Locale.ROOT);
return prefix.startsWith("https://")||prefix.startsWith("http://");
}
private static int urlEnd(String text,int start){
int parentheses=0,brackets=0,end=start;
for(;end<text.length();end++){
char c=text.charAt(end);
if(c<=0x20||c==0x7f||c=='\\'||c==96||"<>\"'{},。;:!?、()【】《》「」『』“”‘’".indexOf(c)>=0)break;
if(c=='(')parentheses++;
if(c==')'){if(parentheses==0)break;parentheses--;}
if(c=='[')brackets++;
if(c==']'){if(brackets==0)break;brackets--;}
}
return end;
}
private static boolean appendLink(SpannableStringBuilder result,String label,String destination){
if(!isWebURL(destination))return false;
int start=result.length();result.append(label);
result.setSpan(new URLSpan(destination){
@Override public void onClick(View widget){
if(!isWebURL(getURL()))return;
try{widget.getContext().startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(getURL())).addCategory(Intent.CATEGORY_BROWSABLE));}
catch(android.content.ActivityNotFoundException error){Toast.makeText(widget.getContext(),"没有可打开网页的浏览器",Toast.LENGTH_SHORT).show();}
}
},start,result.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
return true;
}
}
@@ -0,0 +1,170 @@
package cn.crossdesk.mobile;
import android.app.AlertDialog;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.view.*;
import android.widget.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.function.Consumer;
import static cn.crossdesk.mobile.MobileUi.*;
/** Grouped announcement list and plain-text detail, sharing the iOS presentation. */
@android.annotation.SuppressLint("ViewConstructor")
final class AnnouncementView extends ScrollView {
private final MobileUi ui;
private final AnnouncementInbox inbox;
private final LinearLayout content;
private final Consumer<AnnouncementInbox.Item> open;
private final Runnable authorize;
private final boolean detail;
private final long id,revision;
private final SimpleDateFormat dates=new SimpleDateFormat("yyyy-MM-dd HH:mm",Locale.getDefault());
private TextView countLabel;
private AlertDialog deleteDialog;
private float downX,downY;
private boolean pulling,canPull;
private final int slop;
AnnouncementView(MobileUi ui,AnnouncementInbox inbox,AnnouncementInbox.Item selected,
Consumer<AnnouncementInbox.Item> open,Runnable authorize){
super(ui.context);this.ui=ui;this.inbox=inbox;this.open=open;this.authorize=authorize;
detail=selected!=null;id=detail?selected.id:0;revision=detail?selected.revision:0;
slop=ViewConfiguration.get(getContext()).getScaledTouchSlop();
setFillViewport(true);setScrollBarStyle(SCROLLBARS_OUTSIDE_OVERLAY);
content=ui.column();content.setPadding(ui.dp(20),ui.dp(detail?20:16),ui.dp(20),ui.dp(28));
addView(content,new ScrollView.LayoutParams(-1,-2));
setOnScrollChangeListener((v,x,y,oldX,oldY)->{if(y>oldY)loadVisiblePage();});
render();
}
void render(){
int y=getScrollY();content.removeAllViews();countLabel=null;
if(detail)renderDetail();else renderList();
post(()->{if(isAttachedToWindow()){scrollTo(0,y);loadVisiblePage();}});
}
private String date(AnnouncementInbox.Item item){return dates.format(new Date(item.updatedAt*1000));}
private TextView message(String value,int color){
TextView text=ui.text(value,14,false);text.setTextColor(color);text.setLineSpacing(ui.dp(3),1);return text;
}
private void renderList(){
if(inbox.deleteFailed){content.addView(message("无法删除这条公告,请重试。",RED));ui.gap(content,12);}
if(!inbox.isConnected()){
content.addView(message("连接服务器后可获取最新公告。",SECONDARY));
content.addView(ui.action("连接服务器",BLUE,authorize));ui.gap(content,8);
}else if(inbox.failed){
LinearLayout error=ui.row();error.addView(message("公告加载失败,请重试。",SECONDARY),new LinearLayout.LayoutParams(0,-2,1));
error.addView(ui.action("重试",BLUE,inbox::refresh),ui.size(64,48));content.addView(error);ui.gap(content,8);
}
countLabel=ui.text("共 "+inbox.total+" 条 · "+inbox.unread+" 条未读",13,false);
countLabel.setTextColor(SECONDARY);countLabel.setPadding(ui.dp(16),ui.dp(8),0,ui.dp(8));content.addView(countLabel);
LinearLayout card=ui.column();ui.card(card,12);content.addView(card);
for(AnnouncementInbox.Item item:inbox.items){
if(card.getChildCount()>0)ui.divider(card);
card.addView(itemRow(item),ui.size(-1,-2));
}
if(inbox.loading){
LinearLayout loading=ui.row();loading.setGravity(Gravity.CENTER);loading.setPadding(0,ui.dp(18),0,ui.dp(18));
ProgressBar spinner=new ProgressBar(getContext());spinner.setIndeterminateTintList(ColorStateList.valueOf(BLUE));loading.addView(spinner,ui.size(20,20));
TextView label=message("加载中…",SECONDARY);label.setPadding(ui.dp(10),0,0,0);loading.addView(label);card.addView(loading);
}else if(inbox.items.size()<inbox.total&&!inbox.failed){
TextView more=ui.action("加载更多",BLUE,inbox::loadMore);more.setEnabled(inbox.isConnected());card.addView(more,ui.size(-1,48));
}else if(inbox.loaded&&inbox.total==0&&!inbox.failed&&inbox.isConnected()){
TextView empty=message("暂无公告",SECONDARY);empty.setGravity(Gravity.CENTER);card.addView(empty,ui.size(-1,120));
}
}
private View itemRow(AnnouncementInbox.Item item){
LinearLayout row=ui.row();row.setBackgroundColor(Color.WHITE);row.setPadding(ui.dp(16),ui.dp(16),ui.dp(12),ui.dp(16));
LinearLayout words=ui.column();
LinearLayout top=ui.row();top.setGravity(Gravity.TOP);
View dot=new View(getContext());dot.setBackground(ui.background(item.read?Color.TRANSPARENT:BLUE,4));
LinearLayout.LayoutParams dotLayout=ui.size(7,7);dotLayout.topMargin=ui.dp(7);dotLayout.rightMargin=ui.dp(10);top.addView(dot,dotLayout);
TextView title=ui.text(item.title,16,!item.read);title.setMaxLines(2);title.setEllipsize(TextUtils.TruncateAt.END);
words.addView(title,ui.size(-1,-2));ui.gap(words,7);TextView date=ui.text(date(item),12,false);date.setTextColor(SECONDARY);words.addView(date);
top.addView(words,new LinearLayout.LayoutParams(0,-2,1));row.addView(top,new LinearLayout.LayoutParams(0,-2,1));
TextView chevron=ui.text("›",23,false);chevron.setTextColor(0xFFB7B7BD);chevron.setPadding(ui.dp(10),0,0,0);row.addView(chevron);
row.setContentDescription(item.title+","+date(item)+","+(item.read?"已读":"未读"));row.setFocusable(true);
row.setOnClickListener(v->open.accept(item));row.setOnLongClickListener(v->{confirmDelete(item);return true;});
return new SwipeRow(row,()->confirmDelete(item));
}
private void confirmDelete(AnnouncementInbox.Item item){
if(deleteDialog!=null)deleteDialog.dismiss();
deleteDialog=new AlertDialog.Builder(getContext()).setTitle("删除公告").setMessage("删除这条公告?")
.setNegativeButton("取消",null).setPositiveButton("删除",(dialog,which)->inbox.dismiss(item)).show();
}
private void renderDetail(){
AnnouncementInbox.Item item=inbox.find(id,revision);
if(item==null){content.addView(message("这条公告已更新或删除,请返回公告列表查看。",SECONDARY));return;}
content.addView(ui.text(item.title,22,true));ui.gap(content,16);
TextView date=ui.text(date(item)+" · "+(item.read?"已读":"未读"),12,false);date.setTextColor(SECONDARY);content.addView(date);ui.gap(content,16);
if(inbox.readSaveFailed){
content.addView(message("无法保存本地阅读状态,请重试。",RED));
content.addView(ui.action("重试保存阅读状态",BLUE,()->inbox.markRead(item)));ui.gap(content,16);
}
TextView body=ui.text("",17,false);body.setText(AnnouncementText.format(item.body));body.setTextIsSelectable(true);
body.setMovementMethod(LinkMovementMethod.getInstance());body.setLinksClickable(true);body.setLinkTextColor(BLUE);body.setLineSpacing(ui.dp(4),1);
content.addView(body,ui.size(-1,-2));
}
private void loadVisiblePage(){
if(!detail&&isAttachedToWindow()&&inbox.isConnected()&&!inbox.loading&&!inbox.failed&&inbox.items.size()<inbox.total&&
content.getHeight()>0&&getHeight()>0&&getScrollY()+getHeight()>=content.getHeight()-ui.dp(48))inbox.loadMore();
}
private void trackPull(MotionEvent event){
if(!detail&&inbox.isConnected()&&!inbox.loading){
if(event.getActionMasked()==MotionEvent.ACTION_DOWN){downX=event.getX();downY=event.getY();pulling=false;canPull=getScrollY()==0;}
else if(event.getActionMasked()==MotionEvent.ACTION_MOVE&&canPull&&getScrollY()==0&&
event.getY()-downY>slop&&event.getY()-downY>Math.abs(event.getX()-downX))pulling=true;
}
}
@Override public boolean onInterceptTouchEvent(MotionEvent event){
trackPull(event);return pulling||super.onInterceptTouchEvent(event);
}
@android.annotation.SuppressLint("ClickableViewAccessibility") // Pull gesture only; toolbar refresh is the accessible action.
@Override public boolean onTouchEvent(MotionEvent event){
trackPull(event);
if(!pulling)return super.onTouchEvent(event);
boolean reached=event.getY()-downY>=ui.dp(72);
if(event.getActionMasked()==MotionEvent.ACTION_MOVE&&countLabel!=null)countLabel.setText(reached?"松开刷新":"下拉刷新");
if(event.getActionMasked()==MotionEvent.ACTION_UP||event.getActionMasked()==MotionEvent.ACTION_CANCEL){
pulling=false;if(reached&&event.getActionMasked()==MotionEvent.ACTION_UP)inbox.refresh();else render();
}
return true;
}
@Override protected void onDetachedFromWindow(){if(deleteDialog!=null)deleteDialog.dismiss();super.onDetachedFromWindow();}
/** Reveal a delete action without interfering with vertical scrolling or row taps. */
private final class SwipeRow extends FrameLayout {
private final View front,remove;
private float x,y,origin;
private boolean dragging;
SwipeRow(View front,Runnable delete){
super(ui.context);this.front=front;setClipChildren(true);
remove=ui.action("删除",Color.WHITE,delete);remove.setBackgroundColor(RED);
remove.setVisibility(INVISIBLE);
remove.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);remove.setFocusable(false);
addView(remove,new FrameLayout.LayoutParams(ui.dp(76),-1,Gravity.END));addView(front,new FrameLayout.LayoutParams(-1,-2));
}
@Override public boolean onInterceptTouchEvent(MotionEvent event){
if(event.getActionMasked()==MotionEvent.ACTION_DOWN){front.animate().cancel();x=event.getX();y=event.getY();origin=front.getTranslationX();dragging=false;}
if(event.getActionMasked()==MotionEvent.ACTION_MOVE&&Math.abs(event.getX()-x)>slop&&Math.abs(event.getX()-x)>Math.abs(event.getY()-y)){
dragging=true;remove.setVisibility(VISIBLE);getParent().requestDisallowInterceptTouchEvent(true);return true;
}
return super.onInterceptTouchEvent(event);
}
@android.annotation.SuppressLint("ClickableViewAccessibility") // Taps/long presses belong to the accessible row and delete button.
@Override public boolean onTouchEvent(MotionEvent event){
if(!dragging)return super.onTouchEvent(event);
int direction=getLayoutDirection()==LAYOUT_DIRECTION_RTL?1:-1;
if(event.getActionMasked()==MotionEvent.ACTION_MOVE)front.setTranslationX(direction*Math.max(0,Math.min(ui.dp(76),direction*(origin+event.getX()-x))));
if(event.getActionMasked()==MotionEvent.ACTION_UP||event.getActionMasked()==MotionEvent.ACTION_CANCEL){
boolean expanded=Math.abs(front.getTranslationX())>ui.dp(38);dragging=false;
front.animate().translationX(expanded?direction*ui.dp(76):0).setDuration(150).withEndAction(()->{if(!expanded)remove.setVisibility(INVISIBLE);}).start();
remove.setFocusable(expanded);remove.setImportantForAccessibility(expanded?IMPORTANT_FOR_ACCESSIBILITY_YES:IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);
}
return true;
}
}
}
@@ -0,0 +1,63 @@
package cn.crossdesk.mobile;
import java.util.function.BiFunction;
/** Main-thread local-app checks triggered by visits, session endings and manual requests. */
final class AppUpdateChecker {
enum Status { IDLE, CHECKING, UP_TO_DATE, AVAILABLE, FAILED }
private final String currentVersion;
private final RemoteVersionCheck.Fetcher fetcher;
private final BiFunction<String, byte[], String> compare;
private final Runnable changed;
private RemoteVersionCheck.Cancellation request;
private boolean enabled;
private long generation;
Status status = Status.IDLE;
String availableVersion = "";
AppUpdateChecker(String currentVersion, Runnable changed) {
this(currentVersion, RemoteVersionCheck.ReleaseRequest::start,
NativeSession::nCheckMobileUpdate, changed);
}
AppUpdateChecker(String currentVersion, RemoteVersionCheck.Fetcher fetcher,
BiFunction<String, byte[], String> compare, Runnable changed) {
this.currentVersion = currentVersion; this.fetcher = fetcher;
this.compare = compare;
this.changed = changed;
}
boolean updateAvailable() { return !availableVersion.isEmpty(); }
void setEnabled(boolean value) {
if (enabled == value) return;
enabled = value;
if (enabled) { checkNow(); return; }
++generation;
if (request != null) request.cancel();
request = null;
if (status == Status.CHECKING) {
status = updateAvailable() ? Status.AVAILABLE : Status.IDLE;
}
changed.run();
}
void checkNow() {
if (!enabled || status == Status.CHECKING) return;
status = Status.CHECKING;
changed.run();
long token = ++generation;
request = fetcher.fetch(data -> {
if (!enabled || token != generation) return;
request = null;
String result = data == null ? null : compare.apply(currentVersion, data);
if (result == null) {
status = Status.FAILED;
} else {
availableVersion = result;
status = updateAvailable() ? Status.AVAILABLE : Status.UP_TO_DATE;
}
changed.run();
});
}
}
@@ -0,0 +1,49 @@
package cn.crossdesk.mobile;
import android.media.AudioAttributes;
import android.media.AudioFormat;
import android.media.AudioTrack;
import java.util.concurrent.ArrayBlockingQueue;
/** Bounded audio queue: network callbacks never block on the speaker. */
final class AudioPlayer implements AutoCloseable {
private final ArrayBlockingQueue<byte[]> queue = new ArrayBlockingQueue<>(20);
private volatile boolean closed;
private volatile boolean enabled = true;
private final Thread thread = new Thread(this::play, "CrossDesk audio");
AudioPlayer() { thread.start(); }
void offer(byte[] pcm) {
if (!closed && enabled && !queue.offer(pcm)) { queue.poll(); queue.offer(pcm); }
}
void setEnabled(boolean value) { enabled = value; queue.clear(); }
private void play() {
AudioTrack track = null;
try {
int minimum = AudioTrack.getMinBufferSize(48000, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
track = new AudioTrack.Builder()
.setAudioAttributes(new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MOVIE).build())
.setAudioFormat(new AudioFormat.Builder().setSampleRate(48000)
.setChannelMask(AudioFormat.CHANNEL_OUT_MONO).setEncoding(AudioFormat.ENCODING_PCM_16BIT).build())
.setBufferSizeInBytes(Math.max(minimum, 9600)).setTransferMode(AudioTrack.MODE_STREAM).build();
track.play();
while (!closed) {
byte[] data = queue.take();
if (!enabled) continue;
int offset = 0;
while (!closed && enabled && offset < data.length) {
int written = track.write(data, offset, data.length - offset, AudioTrack.WRITE_BLOCKING);
if (written <= 0) break;
offset += written;
}
}
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
} catch (IllegalArgumentException | IllegalStateException ignored) {
// Devices with unavailable output can still operate as a silent controller.
} finally {
if (track != null) { track.release(); }
}
}
@Override public void close() { closed = true; queue.clear(); thread.interrupt(); }
}
@@ -0,0 +1,85 @@
package cn.crossdesk.mobile;
import android.content.Context;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.File;
import java.util.UUID;
/** Main-thread session state; never retains a stopped Activity or its Views. */
final class BackgroundSession implements NativeSession.Listener {
final Context context;
final NativeSession session;
final String token = UUID.randomUUID().toString();
final String host, remote;
final int port;
NativeSession.Listener view;
String identity = "", platform = "", clipboard = "", fileStatus = "", endReason = "";
JSONArray displays = new JSONArray();
RemoteVideoSettings videoSettings;
int signalState, selectedDisplay, width, height;
boolean muted, remoteServiceAvailable, background, ended;
File receivedFile;
BackgroundSession(Context context, NativeSession session, String host, int port, String remote) {
this.context = context.getApplicationContext();
this.session = session; this.host = host; this.port = port; this.remote = remote;
}
void attach(NativeSession.Listener listener) { view = listener; }
void detach(NativeSession.Listener listener) { if (view == listener) view = null; }
void setBackground(boolean value) {
if (background == value || ended) return;
background = value;
// With no visible window, release rendering buffers and stop remote
// audio. The RTC/control connection and file transfers remain alive.
if (value) session.surface(null);
session.control(2, value || muted ? 0 : 1);
RemoteSessionService.refresh(this);
}
void finish(String reason) {
if (ended) return;
ended = true; endReason = reason; clipboard = "";
session.close();
RemoteSessionService.release(context, this);
NativeSession.Listener listener = view; view = null;
if (listener != null) listener.ended(reason);
}
@Override public void ended(String reason) { finish(reason); }
@Override public void passwordRejected() { finish("远端访问密码已失效,请重新连接"); }
@Override public void connected() { /* Already connected before the service takes ownership. */ }
@Override public void status(String message) { if (view != null) view.status(message); }
@Override public void signaling(int state, String id) {
signalState = state; identity = id;
if (view != null) view.signaling(state, id);
}
@Override public void data(JSONObject message) {
if (view != null) { view.data(message); return; }
if (message.optInt("type", -1) == 12 && videoSettings != null) videoSettings.receive(message);
if (message.optInt("type", -1) == 5) {
JSONObject service = message.optJSONObject("service_status");
remoteServiceAvailable = service != null && service.optBoolean("available", false);
}
JSONObject info = message.optJSONObject("host_info");
if (info != null) {
platform = info.optString("platform", "");
JSONArray values = info.optJSONArray("displays"); if (values != null) displays = values;
if (videoSettings != null) videoSettings.setSupported(info.optBoolean("supports_video_settings", false));
}
}
@Override public void videoSize(int w, int h) {
width = w; height = h;
if (view != null) view.videoSize(w, h);
}
@Override public void clipboard(String text) { clipboard = text; if (view != null) view.clipboard(text); }
@Override public void statistics(RemoteNetworkStatistics.Snapshot value) { if (view != null) view.statistics(value); }
@Override public void fileTransfer(String name, double progress, boolean sending, File received) {
if (received != null) receivedFile = received;
fileStatus = progress < 0 ? name + " 传输失败" : (sending ? "发送 " : "接收 ") + name
+ (progress >= 1 ? " · 已完成" : " · " + (int)(progress * 100) + "%");
if (view != null) view.fileTransfer(name, progress, sending, received);
}
@Override public void controlFeedback(String text) { if (view != null) view.controlFeedback(text); }
@Override public void presence(JSONObject message) { if (view != null) view.presence(message); }
@Override public void announcement(JSONObject message) { if (view != null) view.announcement(message); }
@Override public void announcementFailed(String id) { if (view != null) view.announcementFailed(id); }
}
@@ -0,0 +1,46 @@
package cn.crossdesk.mobile;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ScrollView;
/** Reflows the existing panels, keeping text, focus and scroll state during window resizing. */
@android.annotation.SuppressLint("ViewConstructor")
final class HomeLayout extends ScrollView {
final LinearLayout panels;
private final MobileUi ui;
private int panelHeight;
HomeLayout(MobileUi ui){
super(ui.context);this.ui=ui;
setFillViewport(true);setClipChildren(false);setClipToPadding(false);
panels=new LinearLayout(ui.context){
@Override protected void onMeasure(int widthSpec,int heightSpec){
// ScrollView offers unbounded height even with an explicit LayoutParams height.
super.onMeasure(widthSpec,MeasureSpec.makeMeasureSpec(panelHeight,MeasureSpec.EXACTLY));
}
};panels.setGravity(Gravity.TOP);
panels.setPadding(ui.dp(20),ui.dp(24),ui.dp(20),ui.dp(12));
panels.setClipChildren(false);panels.setClipToPadding(false);
addView(panels,new LayoutParams(-1,-1));
}
@Override protected void onMeasure(int widthSpec,int heightSpec){
boolean wide=MeasureSpec.getSize(widthSpec)>=ui.dp(900);
panels.setOrientation(wide?LinearLayout.HORIZONTAL:LinearLayout.VERTICAL);
// A short split window or the IME can leave less room than the two panels need.
// Keep the recent list usable and let the outer viewport scroll in that case.
panelHeight=Math.max(ui.dp(wide?360:440),MeasureSpec.getSize(heightSpec));
if(panels.getChildCount()==2){
View connection=panels.getChildAt(0),recent=panels.getChildAt(1);
LinearLayout.LayoutParams first=(LinearLayout.LayoutParams)connection.getLayoutParams();
first.width=wide?ui.dp(360):-1;first.height=-2;first.weight=0;first.gravity=Gravity.TOP;
LinearLayout.LayoutParams second=(LinearLayout.LayoutParams)recent.getLayoutParams();
second.width=wide?0:-1;second.height=wide?-1:0;second.weight=1;
second.topMargin=wide?0:ui.dp(20);second.setMarginStart(wide?ui.dp(24):0);
second.resolveLayoutDirection(panels.getLayoutDirection());
}
super.onMeasure(widthSpec,heightSpec);
}
}
@@ -0,0 +1,61 @@
package cn.crossdesk.mobile;
import android.view.KeyEvent;
final class KeyMap {
static int windowsCode(int code) {
if (code >= KeyEvent.KEYCODE_A && code <= KeyEvent.KEYCODE_Z) return 0x41 + code - KeyEvent.KEYCODE_A;
if (code >= KeyEvent.KEYCODE_0 && code <= KeyEvent.KEYCODE_9) return 0x30 + code - KeyEvent.KEYCODE_0;
if (code >= KeyEvent.KEYCODE_F1 && code <= KeyEvent.KEYCODE_F12) return 0x70 + code - KeyEvent.KEYCODE_F1;
return switch (code) {
case KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_NUMPAD_ENTER -> 0x0D;
case KeyEvent.KEYCODE_DEL -> 0x08;
case KeyEvent.KEYCODE_FORWARD_DEL -> 0x2E;
case KeyEvent.KEYCODE_TAB -> 0x09;
case KeyEvent.KEYCODE_ESCAPE -> 0x1B;
case KeyEvent.KEYCODE_SPACE -> 0x20;
case KeyEvent.KEYCODE_SHIFT_LEFT, KeyEvent.KEYCODE_SHIFT_RIGHT -> 0x10;
case KeyEvent.KEYCODE_CTRL_LEFT, KeyEvent.KEYCODE_CTRL_RIGHT -> 0x11;
case KeyEvent.KEYCODE_ALT_LEFT, KeyEvent.KEYCODE_ALT_RIGHT -> 0x12;
case KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_META_RIGHT -> 0x5B;
case KeyEvent.KEYCODE_DPAD_LEFT -> 0x25;
case KeyEvent.KEYCODE_DPAD_UP -> 0x26;
case KeyEvent.KEYCODE_DPAD_RIGHT -> 0x27;
case KeyEvent.KEYCODE_DPAD_DOWN -> 0x28;
case KeyEvent.KEYCODE_MOVE_HOME -> 0x24;
case KeyEvent.KEYCODE_MOVE_END -> 0x23;
case KeyEvent.KEYCODE_PAGE_UP -> 0x21;
case KeyEvent.KEYCODE_PAGE_DOWN -> 0x22;
case KeyEvent.KEYCODE_MINUS -> 0xBD;
case KeyEvent.KEYCODE_EQUALS -> 0xBB;
case KeyEvent.KEYCODE_LEFT_BRACKET -> 0xDB;
case KeyEvent.KEYCODE_RIGHT_BRACKET -> 0xDD;
case KeyEvent.KEYCODE_BACKSLASH -> 0xDC;
case KeyEvent.KEYCODE_SEMICOLON -> 0xBA;
case KeyEvent.KEYCODE_APOSTROPHE -> 0xDE;
case KeyEvent.KEYCODE_COMMA -> 0xBC;
case KeyEvent.KEYCODE_PERIOD -> 0xBE;
case KeyEvent.KEYCODE_SLASH -> 0xBF;
case KeyEvent.KEYCODE_GRAVE -> 0xC0;
default -> 0;
};
}
// High bit is the Shift modifier; zero means use the clipboard for this text.
static int ascii(char ch) {
if (ch >= 'a' && ch <= 'z') return ch - 'a' + 0x41;
if (ch >= 'A' && ch <= 'Z') return ch | 0x100;
if (ch >= '0' && ch <= '9') return ch;
if (ch == '\n') return 0x0D;
if (ch == '\t') return 0x09;
if (ch == ' ') return 0x20;
String plain = "-=[]\\;',./`";
String shifted = "_+{}|:\"<>?~";
int[] codes = {0xBD,0xBB,0xDB,0xDD,0xDC,0xBA,0xDE,0xBC,0xBE,0xBF,0xC0};
int i = plain.indexOf(ch);
if (i >= 0) return codes[i];
i = shifted.indexOf(ch);
if (i >= 0) return codes[i] | 0x100;
i = ")!@#$%^&*(".indexOf(ch);
return i < 0 ? 0 : (0x30 + i) | 0x100;
}
}
@@ -0,0 +1,58 @@
package cn.crossdesk.mobile;
import android.content.Context;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/** Offline catalog; document bodies are loaded only when opened. */
final class LicenseCatalog {
static final class Document {
final String title,asset;
Document(JSONObject value)throws JSONException{
title=value.getString("title");asset=value.getString("asset");
if(!asset.startsWith("about/")||asset.contains(".."))throw new JSONException("Invalid asset");
}
}
static final class Component {
final String id,name,version,license,sourceURL,buildSourceURL;
final List<Document> documents,buildDocuments;
Component(JSONObject value)throws JSONException{
id=value.getString("id");name=value.getString("name");version=value.getString("version");license=value.getString("license");
sourceURL=value.getString("sourceURL");buildSourceURL=value.optString("buildSourceURL","");
documents=documents(value.getJSONArray("documents"));buildDocuments=documents(value.optJSONArray("buildDocuments"));
if(documents.isEmpty())throw new JSONException("Missing documents");
}
String documentTitle(Document document){
if(document.title.equals("Source copyright and license notices"))return "版权与许可声明";
if(document.title.equals("apps/android/licenses/OPEN_SOURCE_NOTICE.txt"))return "开源软件权利说明";
if(id.equals("crossdesk")&&document.title.equals("LICENSE"))return "GNU GPL 第 3 版";
return document.title;
}
}
final List<Component> components=new ArrayList<>();
final JSONObject source;
LicenseCatalog(Context context)throws IOException,JSONException{
JSONObject data=new JSONObject(read(context,"ThirdPartyLicenses.json"));
if(data.getInt("schemaVersion")!=1)throw new JSONException("Unknown catalog");
JSONArray entries=data.getJSONArray("components");
for(int i=0;i<entries.length();i++)components.add(new Component(entries.getJSONObject(i)));
if(find("crossdesk")==null||find("openfec")==null)throw new JSONException("Incomplete catalog");
JSONObject metadata;
try{metadata=new JSONObject(read(context,"SourceMetadata.json"));if(metadata.getInt("schemaVersion")!=1)metadata=null;}catch(IOException|JSONException error){metadata=null;}
source=metadata;
}
Component find(String id){for(Component component:components)if(component.id.equals(id))return component;return null;}
static List<Document> documents(JSONArray values)throws JSONException{
List<Document> result=new ArrayList<>();if(values!=null)for(int i=0;i<values.length();i++)result.add(new Document(values.getJSONObject(i)));return result;
}
static String read(Context context,String asset)throws IOException{
try(var input=context.getAssets().open(asset);var output=new ByteArrayOutputStream()){
byte[] buffer=new byte[8192];int count;while((count=input.read(buffer))!=-1)output.write(buffer,0,count);return output.toString("UTF-8");
}
}
}
@@ -0,0 +1,771 @@
package cn.crossdesk.mobile;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ClipData;
import android.content.Intent;
import android.content.ClipboardManager;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.ColorStateList;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.text.*;
import android.text.method.PasswordTransformationMethod;
import android.view.*;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.HashSet;
import java.util.Set;
import static cn.crossdesk.mobile.MobileUi.*;
public final class MainActivity extends Activity implements NativeSession.Listener {
private MobileUi ui;
private PageHost pageHost;
private AboutPages aboutPages;
private AppUpdateChecker appUpdates;
private View settingsUpdateDot, aboutUpdateDot, settingsUpdateButton, aboutUpdateRow;
private TextView aboutUpdateLabel;
private boolean navigatingBack;
private FrameLayout canvas;
private LinearLayout root;
private EditText remote;
private TextView status, signalBadge, identitySummary;
private AnnouncementInbox announcementInbox;
private AnnouncementView announcementView;
private TextView announcementBadge;
private View announcementRefresh;
private String announcementServer="";
private SharedPreferences preferences;
private RecentConnections history;
private final RecentConnectionPresence recentPresence=new RecentConnectionPresence();
private LinearLayout recentGrid;
private int recentColumns=2;
private final Runnable presenceTick=new Runnable(){public void run(){
if(!recentPresence.isConnected())return;
recentPresence.maintain(android.os.SystemClock.elapsedRealtime());
mainHandler.postDelayed(this,1000);
}};
private RemotePreviewStore previews;
private RemotePreviewStore.Capture previewCapture;
private boolean previewCopying,updatingPreviewSwitch;
private int previewAttempts;
private Switch previewSwitch;
private TextView clearPreviewsButton,previewCleanupError;
private AlertDialog previewDialog;
private final java.util.List<Runnable> previewCards=new java.util.ArrayList<>();
private final Runnable previewChanged=this::renderPreviews;
private NativeSession session, signaling;
private String signalingServer="", localIdentity="", signalError="";
private int signalState=-1;
private boolean foreground;
private boolean pictureInPictureUi;
private boolean enteredPictureInPicture;
private BackgroundSession backgroundSession;
private int videoWidth,videoHeight;
private final RemotePictureInPicture pictureInPicture=new RemotePictureInPicture();
private RemoteVideoView video;
private SessionControls controls;
private Dialog passwordDialog, progressDialog, privacyDialog;
private AlertDialog disconnectDialog;
private AlertDialog connectionDialog;
private String pendingConnectionMessage="";
private AlertDialog remoteUpdateDialog;
private RemoteVersionCheck remoteVersionCheck;
private String host, connectedRemote="", hostPlatform="", remoteClipboard="", pendingPassword="", page="home";
private int port,selectedDisplay;
private JSONArray displays=new JSONArray();
private boolean muted,ready,rememberPassword;
private boolean remoteServiceAvailable;
private static final int PICK_FILE=41,SAVE_FILE=42;
private NativeSession documentSession;
private java.io.File receivedFile,documentToSave;
private final Runnable documentTimeout=()->{if(documentSession!=null&&!foreground)end("文件选择已超时,会话已结束");};
private RemoteVideoSettings videoSettings=new RemoteVideoSettings(1);
private final android.os.Handler mainHandler=new android.os.Handler(android.os.Looper.getMainLooper());
private Runnable videoSettingsTimeout;
private final Set<Integer> pressed=new HashSet<>();
private Runnable backAction;
@Override public void onCreate(Bundle state){
super.onCreate(state);ui=new MobileUi(this);history=new RecentConnections(this);
pageHost=new PageHost(this);setContentView(pageHost);
preferences=getSharedPreferences("settings",MODE_PRIVATE);host=preferences.getString("host","api.crossdesk.cn");port=preferences.getInt("port",9099);
recentPresence.sender=ids->{if(signaling!=null&&!signaling.isClosed())signaling.presenceRequest(ids);};
recentPresence.changed=this::renderRecentConnections;
remoteVersionCheck=new RemoteVersionCheck(this::showRemoteUpdate);
appUpdates=new AppUpdateChecker(applicationVersion(),this::renderAppUpdates);
previews=RemotePreviewStore.get(this);previews.addListener(previewChanged);previews.enforceConsent();
announcementInbox=new AnnouncementInbox(new java.io.File(getNoBackupFilesDir(),"AnnouncementReads"));
announcementInbox.sender=(request,id)->{if(signaling!=null&&!signaling.isClosed())signaling.announcementRequest(request,id);else announcementInbox.failed(id);};
announcementInbox.changed=this::renderAnnouncements;
if(android.os.Build.VERSION.SDK_INT>=33)getOnBackInvokedDispatcher().registerOnBackInvokedCallback(android.window.OnBackInvokedDispatcher.PRIORITY_DEFAULT,this::back);
home("");
}
private int dp(float value){return ui.dp(value);}
private LinearLayout column(){return ui.column();}
private LinearLayout row(){return ui.row();}
private TextView text(String title,int size,boolean bold){return ui.text(title,size,bold);}
private String serverKey(){return host+":"+port;}
private void toast(String value){Toast.makeText(this,value,Toast.LENGTH_SHORT).show();}
private void hideKeyboard(){((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(root.getWindowToken(),0);root.clearFocus();}
private void installRoot(String nextPage,boolean dark){
PageHost.Motion motion=PageHost.Motion.NONE;
if(canvas!=null&&foreground&&!page.equals(nextPage)){
if(nextPage.equals("session"))motion=PageHost.Motion.SESSION_IN;
else if(page.equals("session"))motion=PageHost.Motion.SESSION_OUT;
else motion=navigatingBack||nextPage.equals("home")?PageHost.Motion.POP:PageHost.Motion.PUSH;
}
if(root!=null)hideKeyboard();page=nextPage;
signalBadge=null;identitySummary=null;announcementBadge=null;announcementView=null;announcementRefresh=null;
settingsUpdateDot=null;aboutUpdateDot=null;settingsUpdateButton=null;aboutUpdateRow=null;aboutUpdateLabel=null;
previewSwitch=null;clearPreviewsButton=null;previewCleanupError=null;previewCards.clear();recentGrid=null;
canvas=new FrameLayout(this);canvas.setBackgroundColor(dark?Color.BLACK:BACKGROUND);
FrameLayout safeArea=new FrameLayout(this);canvas.addView(safeArea,new FrameLayout.LayoutParams(-1,-1));
root=ui.pageColumn(dark?0:nextPage.equals("home")?1200:720);
safeArea.addView(root,new FrameLayout.LayoutParams(-1,-1,Gravity.TOP|Gravity.CENTER_HORIZONTAL));
safeArea.setOnApplyWindowInsetsListener((view,insets)->{
view.setPadding(insets.getSystemWindowInsetLeft(),insets.getSystemWindowInsetTop(),insets.getSystemWindowInsetRight(),insets.getSystemWindowInsetBottom());return insets;
});
root.setFocusableInTouchMode(true);pageHost.show(canvas,motion);
applySystemBars(dark);
}
private void applySystemBars(boolean dark){
if(android.os.Build.VERSION.SDK_INT>=30){
android.view.WindowInsetsController controller=getWindow().getInsetsController();
if(controller!=null){int light=android.view.WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS|android.view.WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS;controller.setSystemBarsAppearance(dark?0:light,light);}
}else getWindow().getDecorView().setSystemUiVisibility(dark?0:View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR|View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
private EditText field(String hint,int type){
EditText v=new EditText(this);v.setHint(hint);v.setContentDescription(hint);v.setInputType(type);v.setSingleLine(true);v.setTextSize(17);v.setTextColor(INK);v.setHintTextColor(SECONDARY);
v.setPadding(dp(14),0,dp(14),0);v.setBackground(ui.background(BACKGROUND,12));v.setImportantForAutofill(View.IMPORTANT_FOR_AUTOFILL_NO);return v;
}
private LinearLayout navigation(String title,Runnable back){
LinearLayout bar=row();bar.setPadding(dp(12),0,dp(12),0);root.addView(bar,ui.size(-1,56));
bar.addView(ui.iconButton("back","返回",this::navigateBack),ui.size(44,44));
TextView label=text(title,17,true);label.setGravity(Gravity.CENTER);label.setSingleLine();label.setEllipsize(TextUtils.TruncateAt.END);bar.addView(label,new LinearLayout.LayoutParams(0,-1,1));
bar.addView(new View(this),ui.size(44,44));backAction=back;return bar;
}
LinearLayout formPage(String name,String title,Runnable back){
installRoot(name,false);navigation(title,back);ScrollView scroll=new ScrollView(this);scroll.setFillViewport(true);root.addView(scroll,new LinearLayout.LayoutParams(-1,0,1));
LinearLayout content=column();content.setPadding(dp(20),dp(16),dp(20),dp(28));scroll.addView(content);return content;
}
LinearLayout section(LinearLayout content,String title){
return section(content,title,12);
}
private LinearLayout section(LinearLayout content,String title,int radius){
if(!title.isEmpty()){TextView label=text(title,13,false);label.setTextColor(SECONDARY);label.setPadding(dp(16),dp(12),0,dp(8));content.addView(label);}
LinearLayout card=column();ui.card(card,radius);content.addView(card);return card;
}
void footer(LinearLayout content,String title){TextView v=text(title,12,false);v.setTextColor(SECONDARY);v.setLineSpacing(dp(3),1);v.setPadding(dp(16),dp(8),dp(16),dp(16));content.addView(v);}
LinearLayout link(LinearLayout parent,String title,String detail,Runnable action){
LinearLayout item=row();item.setPadding(dp(16),dp(14),dp(12),dp(14));item.setMinimumHeight(dp(48));
item.addView(text(title,16,false),new LinearLayout.LayoutParams(0,-2,1));TextView value=text(detail,15,false);value.setTextColor(SECONDARY);item.addView(value);
TextView chevron=text(" ›",23,false);chevron.setTextColor(0xFFB7B7BD);item.addView(chevron);item.setContentDescription(title+(detail.isEmpty()?"":","+detail));item.setClickable(true);item.setFocusable(true);item.setOnClickListener(v->action.run());parent.addView(item);
return item;
}
@android.annotation.SuppressLint("SourceLockedOrientationActivity") // Phones keep the portrait home; tablets and multi-window follow user rotation settings.
private void updateHomeOrientation(){
boolean tablet=getResources().getConfiguration().smallestScreenWidthDp>=600;
if(android.os.Build.VERSION.SDK_INT>=30){
android.graphics.Rect bounds=getWindowManager().getMaximumWindowMetrics().getBounds();
tablet|=Math.min(bounds.width(),bounds.height())>=dp(600);
}
int orientation=tablet||isInMultiWindowMode()?ActivityInfo.SCREEN_ORIENTATION_FULL_USER:ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
if(getRequestedOrientation()!=orientation)setRequestedOrientation(orientation);
}
private void home(String message){
backAction=null;updateHomeOrientation();installRoot("home",false);
LinearLayout toolbar=row();toolbar.setPadding(dp(20),0,dp(20),0);root.addView(toolbar,ui.size(-1,56));
signalBadge=text("",12,true);signalBadge.setGravity(Gravity.CENTER);signalBadge.setPadding(dp(11),0,dp(11),0);signalBadge.setSingleLine(true);
signalBadge.setOnClickListener(v->{
if(!preferences.getBoolean("networkConsent",false))consent(this::renderSignaling);
else if(signalState==1)toast("已连接 "+serverKey());
else {stopSignaling();ensureSignaling();}
});renderSignaling();toolbar.addView(signalBadge,ui.size(-2,34));toolbar.addView(new View(this),new LinearLayout.LayoutParams(0,1,1));
FrameLayout announcementButton=(FrameLayout)ui.iconButton("envelope","通知公告",this::announcements);announcementButton.setClipChildren(false);toolbar.setClipChildren(false);toolbar.setClipToPadding(false);
announcementBadge=text("",10,true);announcementBadge.setTextColor(Color.WHITE);announcementBadge.setGravity(Gravity.CENTER);announcementBadge.setMinWidth(dp(16));announcementBadge.setPadding(dp(4),0,dp(4),0);announcementBadge.setBackground(ui.background(RED,12));announcementBadge.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
FrameLayout.LayoutParams badgePosition=new FrameLayout.LayoutParams(-2,dp(16),Gravity.TOP|Gravity.END);badgePosition.topMargin=-dp(3);badgePosition.setMarginEnd(-dp(5));announcementButton.addView(announcementBadge,badgePosition);renderAnnouncements();
toolbar.addView(announcementButton,ui.size(40,40));View spacer=new View(this);toolbar.addView(spacer,ui.size(12,1));
FrameLayout settingsButton=(FrameLayout)ui.iconButton("settings","设置",this::settings);settingsButton.setClipChildren(false);settingsUpdateButton=settingsButton;
TextView updateBadge=text("!",10,true);updateBadge.setTextColor(Color.WHITE);updateBadge.setGravity(Gravity.CENTER);updateBadge.setIncludeFontPadding(false);updateBadge.setBackground(ui.background(RED,8));updateBadge.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);settingsUpdateDot=updateBadge;
FrameLayout.LayoutParams updatePosition=new FrameLayout.LayoutParams(dp(16),dp(16),Gravity.TOP|Gravity.END);updatePosition.topMargin=-dp(3);updatePosition.setMarginEnd(-dp(5));settingsButton.addView(settingsUpdateDot,updatePosition);
toolbar.addView(settingsButton,ui.size(40,40));renderAppUpdates();
HomeLayout layout=new HomeLayout(ui);root.addView(layout,new LinearLayout.LayoutParams(-1,0,1));LinearLayout content=layout.panels;
LinearLayout connection=column();connection.setPadding(dp(18),dp(18),dp(18),dp(18));content.addView(ui.shadowCard(connection,20));
connection.addView(text("远程桌面",20,true));ui.gap(connection,16);
LinearLayout entry=row();connection.addView(entry,ui.size(-1,54));
remote=field("对端 ID",InputType.TYPE_CLASS_NUMBER);remote.setTextSize(20);remote.setTypeface(Typeface.create("sans-serif-medium",Typeface.NORMAL));
remote.setOnFocusChangeListener((view,focused)->{GradientDrawable shape=ui.background(BACKGROUND,12);shape.setStroke(dp(focused?2:1),focused?BLUE:LINE);remote.setBackground(shape);});
remote.setFilters(new InputFilter[]{new InputFilter.LengthFilter(11)});remote.setText(formatId(preferences.getString("lastRemote","")));
entry.addView(remote,new LinearLayout.LayoutParams(0,-1,1));
TextView connect=ui.primary("连接 →",()->promptConnection(id()));connect.setContentDescription("连接");LinearLayout.LayoutParams buttonParams=ui.size(96,54);buttonParams.leftMargin=dp(10);entry.addView(connect,buttonParams);
Runnable update=()->{connect.setEnabled(!id().isEmpty());connect.setAlpha(id().isEmpty()?.45f:1);};update.run();
remote.addTextChangedListener(new TextWatcher(){boolean editing;public void beforeTextChanged(CharSequence s,int start,int count,int after){}public void onTextChanged(CharSequence s,int start,int before,int count){update.run();}public void afterTextChanged(Editable value){if(editing)return;String formatted=formatId(value.toString());if(!formatted.equals(value.toString())){editing=true;int cursor=remote.getSelectionStart(),digits=value.subSequence(0,Math.max(0,cursor)).toString().replaceAll("[^0-9]","").length();remote.setText(formatted);remote.setSelection(Math.min(formatted.length(),digits+Math.max(0,digits-1)/3));editing=false;}}});
LinearLayout recent=column();recent.setPadding(dp(16),dp(16),dp(16),dp(16));ui.card(recent,18);LinearLayout.LayoutParams p=new LinearLayout.LayoutParams(-1,0,1);p.topMargin=dp(20);content.addView(recent,p);
JSONArray records=history.list(serverKey());recentPresence.watch(records,android.os.SystemClock.elapsedRealtime());LinearLayout heading=row();heading.addView(text("最近连接",20,true),new LinearLayout.LayoutParams(0,-2,1));
if(records.length()>0){TextView count=text(records.length()+" 台设备",12,false);count.setTextColor(SECONDARY);heading.addView(count);}recent.addView(heading);
if(records.length()==0){
LinearLayout empty=column();empty.setGravity(Gravity.CENTER);recent.addView(empty,new LinearLayout.LayoutParams(-1,0,1));empty.addView(ui.icon("history",0xFFB6B6BB),ui.size(34,34));ui.gap(empty,12);
TextView emptyTitle=text("还没有连接记录",17,true);emptyTitle.setGravity(Gravity.CENTER);empty.addView(emptyTitle);ui.gap(empty,8);TextView hint=text("成功连接后,这里会显示最近的远程设备。",13,false);hint.setTextColor(SECONDARY);hint.setGravity(Gravity.CENTER);empty.addView(hint);
}else{
ui.gap(recent,14);ScrollView scroll=new ScrollView(this);recent.addView(scroll,new LinearLayout.LayoutParams(-1,0,1));recentGrid=column();scroll.addView(recentGrid);
recentGrid.addOnLayoutChangeListener((view,left,top,right,bottom,oldLeft,oldTop,oldRight,oldBottom)->{
int width=right-left;if(width<=0)return;
int columns=width<dp(300)?1:Math.max(2,Math.min(4,(width+dp(12))/dp(192)));
if(columns!=recentColumns){recentColumns=columns;view.post(()->{if(view==recentGrid)renderRecentConnections();});}
});renderRecentConnections();
}
ensureSignaling();
if(!message.isEmpty())pendingConnectionMessage=message;
showConnectionMessage();
}
private void showConnectionMessage(){
if(pendingConnectionMessage.isEmpty()||!foreground||isFinishing()||isDestroyed())return;
if(connectionDialog!=null)connectionDialog.dismiss();
connectionDialog=new AlertDialog.Builder(this).setTitle("连接提示").setMessage(pendingConnectionMessage).setPositiveButton("确定",null).create();
connectionDialog.setOnDismissListener(dialog->connectionDialog=null);
pendingConnectionMessage="";connectionDialog.show();
}
private String id(){return remote.getText().toString().replace(" ","");}
static String formatId(String value){String digits=value.replaceAll("[^0-9]","");if(digits.length()>9)digits=digits.substring(0,9);return digits.replaceAll("(.{3})(?=.)","$1 ");}
private void renderRecentConnections(){
if(recentGrid==null)return;
JSONArray records=recentPresence.ordered(history.list(serverKey()),android.os.SystemClock.elapsedRealtime());
recentGrid.removeAllViews();previewCards.clear();
for(int i=0;i<records.length();i+=recentColumns){LinearLayout line=row();line.setGravity(Gravity.TOP);recentGrid.addView(line);for(int j=i;j<i+recentColumns;j++){View card=j<records.length()?recentCard(records.optJSONObject(j)):new View(this);LinearLayout.LayoutParams cell=new LinearLayout.LayoutParams(0,-2,1);if(j>i)cell.setMarginStart(dp(12));line.addView(card,cell);}ui.gap(recentGrid,12);}
}
private View recentCard(JSONObject item){
if(item==null)return new View(this);String id=item.optString("id"),platform=item.optString("platform");
LinearLayout card=column();ui.card(card,14);FrameLayout preview=new FrameLayout(this){@Override protected void onMeasure(int w,int h){super.onMeasure(w,MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(w)*9/16,MeasureSpec.EXACTLY));}};
int color=platform.equals("windows")?0xFF316AB7:platform.equals("macos")?0xFF8057B9:platform.equals("linux")?0xFFAE642B:0xFF677587;preview.setBackgroundColor(color);
TextView label=text(platform.equals("windows")?"Windows":platform.equals("macos")?"macOS":platform.equals("linux")?"Linux":"远程电脑",19,true);label.setGravity(Gravity.CENTER);label.setTextColor(Color.WHITE);preview.addView(label,new FrameLayout.LayoutParams(-1,-1));card.addView(preview,ui.size(-1,80));
ImageView image=new ImageView(this);image.setScaleType(ImageView.ScaleType.CENTER_CROP);image.setVisibility(View.GONE);image.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);preview.addView(image,new FrameLayout.LayoutParams(-1,-1));
String server=serverKey();Runnable load=()->{if(!image.isAttachedToWindow())return;Object binding=new Object();image.setTag(binding);image.setImageDrawable(null);image.setVisibility(View.GONE);label.setVisibility(View.VISIBLE);
previews.load(server,id,bitmap->{if(image.getTag()!=binding||!image.isAttachedToWindow()){if(bitmap!=null)bitmap.recycle();return;}if(bitmap!=null){image.setImageBitmap(bitmap);image.setVisibility(View.VISIBLE);label.setVisibility(View.GONE);}});};previewCards.add(load);image.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener(){public void onViewAttachedToWindow(View view){load.run();}public void onViewDetachedFromWindow(View view){image.setTag(null);}});if(image.isAttachedToWindow())load.run();
LinearLayout caption=column();caption.setPadding(dp(9),dp(9),dp(9),dp(9));TextView name=text(item.optString("name",id),12,true);name.setSingleLine();name.setEllipsize(TextUtils.TruncateAt.END);caption.addView(name);ui.gap(caption,4);
LinearLayout details=row();TextView detail=text("ID "+id,10,false);detail.setTypeface(Typeface.create("sans-serif",Typeface.NORMAL));detail.setTextColor(SECONDARY);detail.setSingleLine();detail.setEllipsize(TextUtils.TruncateAt.END);details.addView(detail,new LinearLayout.LayoutParams(0,-2,1));
if(item.optBoolean("remember")){View key=ui.icon("key",SECONDARY);key.setContentDescription("已保存密码");LinearLayout.LayoutParams keySize=ui.size(10,10);keySize.leftMargin=dp(4);details.addView(key,keySize);}
boolean online=recentPresence.isOnline(id,android.os.SystemClock.elapsedRealtime());String availability=online?"在线":"离线";TextView presence=text(availability,10,true);presence.setSingleLine();presence.setTextColor(online?GREEN:SECONDARY);LinearLayout.LayoutParams presenceSize=ui.size(-2,-2);presenceSize.leftMargin=dp(5);details.addView(presence,presenceSize);caption.addView(details);card.addView(caption);
card.setContentDescription("连接 "+item.optString("name",id)+",ID "+id+(item.optBoolean("remember")?",已保存密码":"")+","+availability);card.setClickable(true);card.setFocusable(true);card.setOnClickListener(v->{remote.setText(formatId(id));promptConnection(id);});
card.setOnLongClickListener(v->{new AlertDialog.Builder(this).setTitle(item.optString("name",id)).setItems(new String[]{"连接","删除记录"},(d,w)->{if(w==0)promptConnection(id);else{history.delete(serverKey(),id);home("");}}).show();return true;});return card;
}
private void promptConnection(String id){
hideKeyboard();if(!id.matches("[0-9]{9}")){remote.setError("请输入 9 位设备 ID");remote.requestFocus();return;}
if(!preferences.getBoolean("networkConsent",false)){consent(()->connectOrPrompt(id));return;}connectOrPrompt(id);
}
private void connectOrPrompt(String id){
String stored;
try{stored=history.password(serverKey(),id);}catch(Exception error){passwordSheet(id,"已保存密码无法读取,请重新输入",true);return;}
if(!stored.isEmpty()){rememberPassword=true;begin(id,stored);return;}
boolean remember=history.remembersPassword(serverKey(),id);
passwordSheet(id,remember?"已保存的密码未能保留,请重新输入一次":"",remember);
}
private void consent(Runnable accepted){
if(privacyDialog!=null&&privacyDialog.isShowing())return;
Dialog dialog=new PrivacyConsentDialog(this,ui,()->{
preferences.edit().putBoolean("networkConsent",true).apply();appUpdates.setEnabled(foreground);renderSignaling();ensureSignaling();accepted.run();
});
privacyDialog=dialog;dialog.setOnDismissListener(d->{if(privacyDialog==dialog)privacyDialog=null;});dialog.show();
}
private void passwordSheet(String id,String error,boolean rememberDefault){
Dialog dialog=new Dialog(this);passwordDialog=dialog;LinearLayout sheet=column();sheet.setPadding(dp(22),dp(10),dp(22),dp(22));sheet.setBackground(ui.background(BACKGROUND,24));
View handle=new View(this);handle.setBackground(ui.background(0xFFC6C6CB,3));LinearLayout.LayoutParams hp=ui.size(36,5);hp.gravity=Gravity.CENTER;sheet.addView(handle,hp);ui.gap(sheet,20);
LinearLayout header=row(),titles=column();titles.addView(text("连接远程桌面",22,true));ui.gap(titles,5);TextView subtitle=text("对端 ID "+id,15,false);subtitle.setTextColor(SECONDARY);titles.addView(subtitle);header.addView(titles,new LinearLayout.LayoutParams(0,-2,1));header.addView(ui.iconButton("close","关闭",dialog::dismiss),ui.size(36,36));sheet.addView(header);ui.gap(sheet,18);
LinearLayout passwordRow=row();ui.card(passwordRow,10);EditText password=field("访问密码",InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_PASSWORD);password.setBackgroundColor(Color.TRANSPARENT);passwordRow.addView(password,new LinearLayout.LayoutParams(0,dp(50),1));
View eye=ui.iconButton("eye","显示密码",()->{boolean hidden=password.getTransformationMethod()!=null;password.setTransformationMethod(hidden?null:PasswordTransformationMethod.getInstance());password.setSelection(password.length());});passwordRow.addView(eye,ui.size(44,44));sheet.addView(passwordRow);ui.gap(sheet,18);
LinearLayout save=row(),saveText=column();saveText.addView(text("保存密码",15,true));ui.gap(saveText,3);TextView security=text("密码将加密保存在本机 Android Keystore 中",11,false);security.setTextColor(SECONDARY);saveText.addView(security);save.addView(saveText,new LinearLayout.LayoutParams(0,-2,1));Switch remember=new Switch(this);remember.setContentDescription("保存密码");save.addView(remember);sheet.addView(save);
remember.setChecked(rememberDefault);
ui.gap(sheet,18);TextView connect=ui.primary("连接 →",()->{
String secret=password.getText().toString();if(secret.isEmpty()||secret.length()>128||secret.contains("@")){password.setError("请输入有效访问密码");return;}
rememberPassword=remember.isChecked();password.setText("");dialog.dismiss();begin(id,secret);
});connect.setContentDescription("确认连接");sheet.addView(connect,ui.size(-1,48));
ScrollView scroll=new ScrollView(this);scroll.addView(sheet);
dialog.setContentView(scroll);Window window=dialog.getWindow();if(window!=null){window.setBackgroundDrawableResource(android.R.color.transparent);window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);window.setDimAmount(.22f);}dialog.show();sizePasswordDialog();password.requestFocus();if(!error.isEmpty())password.setError(error);
dialog.setOnDismissListener(d->{password.setText("");passwordDialog=null;});
}
private void sizePasswordDialog(){
if(passwordDialog==null||passwordDialog.getWindow()==null)return;
int width=getResources().getConfiguration().screenWidthDp;
Window window=passwordDialog.getWindow();window.setLayout(width>=600?dp(Math.min(520,width-48)):-1,-2);
window.setGravity(width>=600?Gravity.CENTER:Gravity.BOTTOM);
}
private void begin(String id,String secret){
videoWidth=videoHeight=0;enteredPictureInPicture=false;
pictureInPicture.disconnect();updatePictureInPicture();
remoteServiceAvailable=false;receivedFile=null;
resetRemoteVersionCheck();
resetVideoSettings();
previewCapture=previews.begin(serverKey(),id);previewCopying=false;previewAttempts=0;
connectedRemote=id;pendingPassword=rememberPassword?secret:"";ready=false;muted=false;selectedDisplay=0;hostPlatform="";remoteClipboard="";displays=new JSONArray();preferences.edit().putString("lastRemote",id).apply();
ensureSignaling();
if(signaling==null){pendingPassword="";toast("请先完成联网授权");return;}
session=signaling;showProgress();session.connect(id,secret);
}
private void showProgress(){
Dialog dialog=new Dialog(this);progressDialog=dialog;LinearLayout card=column();ui.card(card,24);card.setGravity(Gravity.CENTER_HORIZONTAL);LinearLayout body=column();body.setGravity(Gravity.CENTER);body.setPadding(dp(26),dp(24),dp(26),dp(20));
ProgressBar spinner=new ProgressBar(this);spinner.setIndeterminateTintList(ColorStateList.valueOf(BLUE));body.addView(spinner,ui.size(34,34));ui.gap(body,14);TextView title=text("正在连接",20,true);title.setGravity(Gravity.CENTER);body.addView(title);ui.gap(body,6);status=text("正在连接信令服务器…",14,false);status.setGravity(Gravity.CENTER);status.setTextColor(SECONDARY);status.setMinHeight(dp(36));body.addView(status);card.addView(body,ui.size(-1,-2));ui.divider(card);card.addView(ui.action("取消连接",RED,()->end("")),ui.size(-1,46));
dialog.setContentView(card);dialog.setCanceledOnTouchOutside(false);dialog.setOnCancelListener(d->end(""));Window w=dialog.getWindow();if(w!=null){w.setBackgroundDrawableResource(android.R.color.transparent);w.setDimAmount(.08f);}dialog.show();if(w!=null)w.setLayout(dp(292),-2);
}
private void sessionScreen(){
installRoot("session",true);setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);video=new RemoteVideoView(this,session);video.setRelative(preferences.getBoolean("relativeMouse",true));canvas.addView(video,0,new FrameLayout.LayoutParams(-1,-1));
controls=new SessionControls(this,ui,new SessionControls.Actions(){
public void disconnect(){confirmDisconnect();}public void display(){selectDisplay();}public void clipboard(){MainActivity.this.clipboard();}
public void sendFile(){chooseFile();}public void saveFile(){saveReceivedFile();}public void secureAttention(){MainActivity.this.secureAttention();}
public void key(int code){tapKey(code);}
public void chord(int code,int[] modifiers){if(session==null)return;for(int modifier:modifiers)session.key(modifier,true);tapKey(code);for(int i=modifiers.length-1;i>=0;i--)session.key(modifiers[i],false);}public void shortcut(int code){MainActivity.this.shortcut(code);}public void text(String value){sendText(value);}
public void mute(){muted=!muted;if(session!=null)session.control(2,muted?0:1);controls.setMuted(muted);}
public void mouse(){boolean relative=!preferences.getBoolean("relativeMouse",true);preferences.edit().putBoolean("relativeMouse",relative).apply();video.setRelative(relative);controls.setRelative(relative);}
public void videoSettings(int field,int value){RemoteVideoSettings.Values old=MainActivity.this.videoSettings.selection;updateVideoSettings(new RemoteVideoSettings.Values(field==0?value:old.quality,field==1?value:old.frameRate,field==2?value:old.preference));}
});controls.setRelative(preferences.getBoolean("relativeMouse",true));controls.setMuted(muted);controls.videoSettings(videoSettings);root.addView(controls,new LinearLayout.LayoutParams(-1,-1));getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
controls.attachMouseBar(canvas,new VirtualMouseBar(ui,video.mouseInput));
video.addOnLayoutChangeListener((view,left,top,right,bottom,oldLeft,oldTop,oldRight,oldBottom)->{
if(!pictureInPictureUi&&!isInPictureInPictureMode())updatePictureInPicture();
});
pictureInPicture.connected();updatePictureInPicture();
}
private void confirmDisconnect(){disconnectDialog=new AlertDialog.Builder(this).setTitle("断开远程连接?").setMessage("断开后将返回首页").setNegativeButton("取消",null).setPositiveButton("断开连接",(d,w)->end("")).show();}
private void end(String reason){
if(backgroundSession!=null){BackgroundSession retained=backgroundSession;backgroundSession=null;retained.detach(this);retained.finish(reason);}
boolean closeWindow=isInPictureInPictureMode();
pictureInPicture.disconnect();updatePictureInPicture();
if(controls!=null)controls.cancelMouseInput();if(video!=null)video.releaseMouse();
mainHandler.removeCallbacks(documentTimeout);documentSession=null;documentToSave=null;receivedFile=null;remoteServiceAvailable=false;
resetRemoteVersionCheck();
resetVideoSettings();
previewCapture=null;previewCopying=false;
if(progressDialog!=null){progressDialog.dismiss();progressDialog=null;}if(session!=null){releaseKeys();session.close();session=null;}stopSignaling();pendingPassword="";remoteClipboard="";hostPlatform="";displays=new JSONArray();ready=false;video=null;controls=null;getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
if(closeWindow){finish();return;}
home(reason);
appUpdates.checkNow();
}
private void settings(){
LinearLayout content=formPage("settings","设置",()->home(""));
LinearLayout mouse=section(content,"鼠标控制",MobileUi.SETTINGS_CARD_RADIUS);mouse.setPadding(dp(12),dp(12),dp(12),dp(12));boolean relative=preferences.getBoolean("relativeMouse",true);
mouse.addView(segments(new String[]{"相对位置","绝对位置"},relative?0:1,true,index->preferences.edit().putBoolean("relativeMouse",index==0).apply()));
LinearLayout picture=section(content,"画面偏好",MobileUi.SETTINGS_CARD_RADIUS);picture.setPadding(dp(12),dp(12),dp(12),dp(12));int preference=Math.max(0,Math.min(2,preferences.getInt("videoPreference",1)));
picture.addView(segments(RemoteVideoSettings.PREFERENCES,preference,true,index->preferences.edit().putInt("videoPreference",index).apply()));ui.gap(content,28);
LinearLayout server=section(content,"",MobileUi.SETTINGS_CARD_RADIUS);LinearLayout fields=column();fields.setVisibility(View.GONE);boolean custom=!host.equals("api.crossdesk.cn")||port!=9099;
link(server,"服务器",custom?"自定义":"默认",()->fields.setVisibility(fields.getVisibility()==View.VISIBLE?View.GONE:View.VISIBLE));server.addView(fields);
LinearLayout toggleRow=row();toggleRow.setPadding(dp(16),dp(8),dp(16),dp(8));toggleRow.addView(text("使用自定义服务器",16,false),new LinearLayout.LayoutParams(0,-2,1));Switch toggle=new Switch(this);toggle.setContentDescription("使用自定义服务器");toggle.setChecked(custom);toggleRow.addView(toggle);fields.addView(toggleRow);
LinearLayout inputs=column();inputs.setPadding(dp(12),0,dp(12),dp(12));EditText address=field("服务器地址",InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_URI),number=field("服务器端口",InputType.TYPE_CLASS_NUMBER);address.setText(custom?host:"");number.setText(custom?String.valueOf(port):"");inputs.addView(address,ui.size(-1,48));ui.gap(inputs,8);inputs.addView(number,ui.size(-1,48));ui.gap(inputs,8);
inputs.addView(ui.action("完成",BLUE,()->{if(saveServer(address,number)){hideKeyboard();settings();}}));fields.addView(inputs);inputs.setVisibility(custom?View.VISIBLE:View.GONE);
toggle.setOnCheckedChangeListener((button,checked)->{inputs.setVisibility(checked?View.VISIBLE:View.GONE);if(!checked){host="api.crossdesk.cn";port=9099;preferences.edit().putString("host",host).putInt("port",port).apply();ensureSignaling();} });
backAction=()->{if(toggle.isChecked()&&!saveServer(address,number))return;hideKeyboard();home("");};
identitySummary=text("",12,false);identitySummary.setTextColor(SECONDARY);identitySummary.setGravity(Gravity.CENTER);identitySummary.setPadding(dp(16),dp(12),dp(16),dp(16));identitySummary.setTextIsSelectable(true);content.addView(identitySummary);renderSignaling();
LinearLayout privacy=section(content,"隐私",MobileUi.SETTINGS_CARD_RADIUS);link(privacy,"隐私与授权",preferences.getBoolean("networkConsent",false)?"已授权":"未授权",this::privacyPage);ui.divider(privacy);
LinearLayout preview=row();preview.setPadding(dp(16),dp(10),dp(16),dp(10));preview.addView(text("保存远程画面预览",16,false),new LinearLayout.LayoutParams(0,-2,1));previewSwitch=new Switch(this);previewSwitch.setContentDescription("保存远程画面预览");preview.addView(previewSwitch);privacy.addView(preview);
previewSwitch.setOnCheckedChangeListener((button,checked)->{if(updatingPreviewSwitch)return;if(checked){renderPreviews();confirmPreviewSaving();}else previews.setEnabled(false);});
ui.divider(privacy);clearPreviewsButton=ui.action("清除预览图",RED,this::confirmClearPreviews);clearPreviewsButton.setGravity(Gravity.START|Gravity.CENTER_VERTICAL);clearPreviewsButton.setTypeface(Typeface.DEFAULT);clearPreviewsButton.setPadding(dp(16),0,dp(16),0);privacy.addView(clearPreviewsButton,ui.size(-1,48));
previewCleanupError=text("",12,false);previewCleanupError.setTextColor(RED);previewCleanupError.setPadding(dp(16),dp(8),dp(16),dp(12));privacy.addView(previewCleanupError);renderPreviews();
ui.gap(content,28);LinearLayout about=section(content,"",MobileUi.SETTINGS_CARD_RADIUS);LinearLayout aboutLink=link(about,"关于","新版本",this::about);aboutUpdateRow=aboutLink;
aboutUpdateLabel=(TextView)aboutLink.getChildAt(1);aboutUpdateLabel.setPadding(0,0,dp(8),0);
aboutUpdateDot=updateDot();LinearLayout.LayoutParams dotPosition=new LinearLayout.LayoutParams(dp(8),dp(8));dotPosition.setMarginEnd(dp(8));aboutLink.addView(aboutUpdateDot,2,dotPosition);renderAppUpdates();
}
private void confirmPreviewSaving(){
previewDialog=new AlertDialog.Builder(this).setTitle("保存远程画面预览?")
.setMessage("预览可能包含远程电脑上的个人或工作信息。开启后,每次连接会自动将一张画面保存在本机并显示在最近连接中。你可以随时关闭并清除。")
.setNegativeButton("取消",null).setPositiveButton("开启保存",(d,w)->previews.setEnabled(true)).show();
previewDialog.setOnDismissListener(d->{previewDialog=null;renderPreviews();});
}
private void confirmClearPreviews(){
previewDialog=new AlertDialog.Builder(this).setTitle("清除预览图?")
.setMessage("将删除本机保存的所有远程预览图,保留连接记录和密码。"+(previews.enabled()?"后续连接仍会保存新的预览图。":""))
.setNegativeButton("取消",null).setPositiveButton("清除",(d,w)->previews.clear()).show();
previewDialog.setOnDismissListener(d->previewDialog=null);
}
private void renderPreviews(){
if(previews==null)return;
if(!previews.enabled()||previews.cleaning)previewCapture=null;
if(previewSwitch!=null){updatingPreviewSwitch=true;previewSwitch.setChecked(previews.enabled());previewSwitch.setEnabled(preferences.getBoolean("networkConsent",false)&&!previews.cleaning);updatingPreviewSwitch=false;}
if(clearPreviewsButton!=null){clearPreviewsButton.setText(previews.cleaning?"正在清除…":"清除预览图");clearPreviewsButton.setEnabled(!previews.cleaning);}
if(previewCleanupError!=null){previewCleanupError.setText(previews.cleanupError);previewCleanupError.setVisibility(previews.cleanupError.isEmpty()?View.GONE:View.VISIBLE);}
for(Runnable card:previewCards)card.run();
}
private void capturePreviewIfNeeded(){
if(!ready||video==null||previewCapture==null||previewCopying||!previews.current(previewCapture))return;
if(!history.contains(serverKey(),connectedRemote)){previewCapture=null;return;}
RemotePreviewStore.Capture capture=previewCapture;NativeSession source=session;previewCopying=true;
video.capturePreview(bitmap->{
if(session!=source||previewCapture!=capture||!previews.current(capture)){if(bitmap!=null)bitmap.recycle();return;}
previewCopying=false;
if(bitmap!=null){previewCapture=null;previews.save(capture,bitmap);}
else if(++previewAttempts>=3)previewCapture=null;
});
}
private View segments(String[] titles,int selected,boolean enabled,java.util.function.IntConsumer changed){
return new SegmentedControl(ui,titles,selected,enabled,changed);
}
private boolean saveServer(EditText address,EditText number){
String name=address.getText().toString().trim();int value;try{value=Integer.parseInt(number.getText().toString());}catch(NumberFormatException e){number.setError("请输入 1–65535 范围内的端口");return false;}
if(name.length()>253||!name.matches("[A-Za-z0-9.-]+")||name.startsWith(".")||name.endsWith(".")){address.setError("填写主机名或 IPv4 地址,不含协议和路径");return false;}if(value<1||value>65535){number.setError("端口范围为 1–65535");return false;}host=name;port=value;preferences.edit().putString("host",host).putInt("port",port).apply();ensureSignaling();return true;
}
private void announcements(){
installRoot("announcements",false);LinearLayout bar=navigation("通知公告",()->home(""));
bar.removeViewAt(bar.getChildCount()-1);announcementRefresh=ui.iconButton("refresh","刷新公告",announcementInbox::refresh);bar.addView(announcementRefresh,ui.size(44,44));
announcementView=new AnnouncementView(ui,announcementInbox,null,this::announcementDetail,this::connectAnnouncements);
root.addView(announcementView,new LinearLayout.LayoutParams(-1,0,1));announcementInbox.refresh();renderAnnouncements();
}
private void announcementDetail(AnnouncementInbox.Item item){
installRoot("announcement-detail",false);navigation("公告详情",this::announcements);
announcementView=new AnnouncementView(ui,announcementInbox,item,this::announcementDetail,this::connectAnnouncements);
root.addView(announcementView,new LinearLayout.LayoutParams(-1,0,1));announcementInbox.markRead(item);
}
private void connectAnnouncements(){
if(!preferences.getBoolean("networkConsent",false))consent(()->{ensureSignaling();renderAnnouncements();});
else{stopSignaling();ensureSignaling();}
}
private void renderAnnouncements(){
if(announcementBadge!=null){int unread=announcementInbox.unread;announcementBadge.setText(unread>99?"99+":String.valueOf(unread));announcementBadge.setVisibility(unread>0?View.VISIBLE:View.GONE);
if(android.os.Build.VERSION.SDK_INT>=30)((View)announcementBadge.getParent()).setStateDescription(unread>0?unread+" 条未读":"无未读公告");}
if(announcementRefresh!=null){boolean enabled=announcementInbox.isConnected()&&!announcementInbox.loading;announcementRefresh.setEnabled(enabled);announcementRefresh.setAlpha(enabled?1:.4f);}
if(announcementView!=null)announcementView.render();
}
@Override public void announcement(JSONObject message){
if(!preferences.getBoolean("networkConsent",false)||signalState!=1)return;
if("announcements_changed".equals(message.optString("type")))announcementInbox.refresh();else announcementInbox.receive(message);
}
@Override public void announcementFailed(String requestId){announcementInbox.failed(requestId);}
private void privacyPage(){
LinearLayout content=formPage("privacy","隐私与授权",this::settings);LinearLayout card=section(content,"");boolean consent=preferences.getBoolean("networkConsent",false);link(card,"授权状态",consent?"已授权":"未授权",()->{});ui.divider(card);link(card,"隐私政策","",this::privacyPolicyPage);
footer(content,"设备身份及选择保存的访问密码使用 Android Keystore 加密。连接记录仅保存在本机,不纳入设备备份。剪贴板内容在结束会话时清除。离开应用后通过画中画或连接通知保持会话,可在应用或通知中断开。");
if(consent)content.addView(ui.action("撤回联网授权",RED,()->new AlertDialog.Builder(this).setTitle("撤回联网授权?").setMessage("撤回后将停止远程连接、关闭画面预览保存并清除已有预览。连接记录和密码会保留,重新连接前需再次授权。").setNegativeButton("取消",null).setPositiveButton("撤回",(d,w)->{preferences.edit().putBoolean("networkConsent",false).apply();appUpdates.setEnabled(false);previews.setEnabled(false);stopSignaling();announcementInbox.reset();privacyPage();}).show()));else content.addView(ui.primary("阅读并授权",()->consent(this::privacyPage)));
}
private void privacyPolicyPage(){
installRoot("privacy-policy",false);navigation("隐私政策",this::privacyPage);
root.addView(new PrivacyPolicyDocument(this).view(ui),new LinearLayout.LayoutParams(-1,0,1));
}
String applicationVersion(){
try{return getPackageManager().getPackageInfo(getPackageName(),0).versionName;}catch(android.content.pm.PackageManager.NameNotFoundException error){return "";}
}
View updateDot(){View dot=new View(this);dot.setBackground(ui.background(RED,4));dot.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);return dot;}
boolean hasNetworkConsent(){return preferences.getBoolean("networkConsent",false);}
void checkAppUpdates(){
if(hasNetworkConsent())appUpdates.checkNow();
else consent(appUpdates::checkNow);
}
private void renderAppUpdates(){
boolean available=appUpdates.updateAvailable();
if(settingsUpdateDot!=null)settingsUpdateDot.setVisibility(available?View.VISIBLE:View.GONE);
if(aboutUpdateDot!=null)aboutUpdateDot.setVisibility(available?View.VISIBLE:View.GONE);
if(aboutUpdateLabel!=null)aboutUpdateLabel.setVisibility(available?View.VISIBLE:View.GONE);
if(settingsUpdateButton!=null)settingsUpdateButton.setContentDescription(available?"设置,有新版本":"设置");
if(aboutUpdateRow!=null)aboutUpdateRow.setContentDescription(available?"关于,有新版本":"关于");
if(aboutPages!=null&&page.equals("about"))aboutPages.renderUpdates();
}
private void about(){
if(aboutPages==null)aboutPages=new AboutPages(this,ui,this::settings,appUpdates);aboutPages.show();
}
private void sendText(String value){if(session==null)return;if(value.length()>2048){toast("单次最多 2048 个字符");return;}for(char ch:value.toCharArray())if(KeyMap.ascii(ch)==0){toast("中文等文本请通过剪贴板发送,再点击粘贴");return;}for(char ch:value.toCharArray()){int code=KeyMap.ascii(ch);boolean shift=(code&0x100)!=0;if(shift)session.key(0x10,true);tapKey(code&0xFF);if(shift)session.key(0x10,false);}}
private void tapKey(int code){if(session!=null){session.key(code,true);session.key(code,false);}}
private void shortcut(int code){if(session!=null){int modifier=hostPlatform.equals("macos")?0x5B:0x11;session.key(modifier,true);tapKey(code);session.key(modifier,false);}}
private void selectDisplay(){
if(!ready)return;int count=Math.min(displays.length(),8);if(count==0){toast("等待远端屏幕信息");return;}String[] labels=new String[count];for(int i=0;i<count;i++){JSONObject display=displays.optJSONObject(i);labels[i]=(i+1)+" · "+(display==null?"显示器":display.optString("name","显示器"));}new AlertDialog.Builder(this).setTitle("显示器").setItems(labels,(d,w)->{if(session!=null){if(w!=selectedDisplay&&video!=null)video.resetViewport();selectedDisplay=w;session.control(4,w);if(controls!=null)controls.resetVideoStatistics();}}).show();
}
private void secureAttention(){
if(!ready||session==null)return;
if(!remoteServiceAvailable){controlFeedback(hostPlatform.equals("windows")?"请在远端启用 CrossDesk 系统服务后重试":"Ctrl+Alt+Del 需要远端 Windows 系统服务支持");return;}
session.secureAttention();
}
private void chooseFile(){
if(!ready||session==null)return;
openDocument(new Intent(Intent.ACTION_OPEN_DOCUMENT).addCategory(Intent.CATEGORY_OPENABLE).setType("*/*"),PICK_FILE);
}
private void saveReceivedFile(){
if(!ready||session==null||receivedFile==null)return;
documentToSave=receivedFile;
openDocument(new Intent(Intent.ACTION_CREATE_DOCUMENT).addCategory(Intent.CATEGORY_OPENABLE).setType("application/octet-stream").putExtra(Intent.EXTRA_TITLE,receivedFile.getName()),SAVE_FILE);
}
private void openDocument(Intent intent,int request){
if(documentSession!=null)return;
documentSession=session;releaseKeys();
pictureInPicture.choosingDocument(true);updatePictureInPicture();
try{startActivityForResult(intent,request);mainHandler.postDelayed(documentTimeout,5*60*1000);}
catch(android.content.ActivityNotFoundException error){documentSession=null;documentToSave=null;pictureInPicture.choosingDocument(false);updatePictureInPicture();controlFeedback("此设备没有可用的文件选择器");}
}
@Override protected void onActivityResult(int request,int result,Intent data){
super.onActivityResult(request,result,data);
if(request!=PICK_FILE&&request!=SAVE_FILE)return;
NativeSession source=documentSession;java.io.File saved=documentToSave;
documentSession=null;documentToSave=null;mainHandler.removeCallbacks(documentTimeout);
pictureInPicture.choosingDocument(false);updatePictureInPicture();
if(source==null||source!=session||!ready||result!=RESULT_OK||data==null||data.getData()==null)return;
if(request==PICK_FILE)source.sendFile(data.getData());else if(saved!=null)source.saveFile(saved,data.getData());
}
@Override public void fileTransfer(String name,double progress,boolean sending,java.io.File received){
if(!ready)return;
if(received!=null)receivedFile=received;
String fileStatus=progress<0?name+" 传输失败":(sending?"发送 ":"接收 ")+name+(progress>=1?" · 已完成":" · "+(int)(progress*100)+"%");
if(controls!=null)controls.fileStatus(fileStatus,receivedFile!=null);
if(progress<0||progress>=1)toast(fileStatus);
}
@Override public void controlFeedback(String message){
toast(message);
}
private void clipboard(){
if(!ready)return;
EditText input=field("要发送到远端的文本",InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_FLAG_MULTI_LINE);input.setSingleLine(false);input.setMinLines(3);
new AlertDialog.Builder(this).setTitle("剪贴板").setView(input)
.setMessage("发送后,在远程键盘中点击“粘贴”。接收的远端文本可手动复制到本机。")
.setNegativeButton("关闭",null).setNeutralButton("复制远端文本",(d,w)->{
if(!remoteClipboard.isEmpty())((ClipboardManager)getSystemService(CLIPBOARD_SERVICE)).setPrimaryClip(ClipData.newPlainText("CrossDesk",remoteClipboard));
}).setPositiveButton("发送文本",(d,w)->{
String value=input.getText().toString();
if(value.getBytes(java.nio.charset.StandardCharsets.UTF_8).length>128*1024){Toast.makeText(this,"文本超过 128 KB",Toast.LENGTH_SHORT).show();return;}
if(session!=null)session.clipboard(value);
}).show();
}
void licenseDocument(String title,String value,Runnable back){
installRoot("document:"+title,false);navigation(title,back);
// Bound each selectable accessibility node while keeping every character of long notices.
java.util.List<String> chunks=new java.util.ArrayList<>();
for(int start=0;start<value.length();){int end=Math.min(start+4000,value.length());if(end<value.length()){int newline=value.lastIndexOf('\n',end-1);if(newline>start)end=newline+1;else if(Character.isHighSurrogate(value.charAt(end-1)))end--;}chunks.add(value.substring(start,end));start=end;}
ListView paragraphs=new ListView(this);paragraphs.setBackgroundColor(Color.WHITE);paragraphs.setDivider(null);paragraphs.setClipToPadding(false);paragraphs.setPadding(0,dp(8),0,dp(8));
paragraphs.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,chunks){
@Override public View getView(int position,View reuse,ViewGroup parent){
TextView item=(TextView)super.getView(position,reuse,parent);item.setTextColor(INK);item.setTextSize(16);item.setAutoLinkMask(android.text.util.Linkify.WEB_URLS);item.setText(getItem(position));item.setTextIsSelectable(true);item.setLinksClickable(true);item.setLinkTextColor(BLUE);item.setPadding(dp(16),dp(8),dp(16),dp(8));return item;
}
});root.addView(paragraphs,new LinearLayout.LayoutParams(-1,0,1));
}
private void ensureSignaling(){
if(!foreground||!preferences.getBoolean("networkConsent",false))return;
if(signaling!=null&&!signaling.isClosed()&&signalingServer.equals(serverKey()))return;
if(!announcementServer.equals(serverKey())){announcementInbox.reset();announcementServer=serverKey();}
stopSignaling();signalState=0;signalError="";signalingServer=serverKey();
signaling=new NativeSession(this,host,port,"","",this);
renderSignaling();signaling.start();
}
private void stopSignaling(){
if(backgroundSession!=null&&backgroundSession.session==signaling){BackgroundSession retained=backgroundSession;backgroundSession=null;retained.detach(this);retained.finish("");}
mainHandler.removeCallbacks(presenceTick);recentPresence.setConnected(false,android.os.SystemClock.elapsedRealtime());
announcementInbox.setConnected(false);
if(signaling!=null)signaling.close();
signaling=null;signalingServer="";localIdentity="";signalState=-1;signalError="";renderSignaling();
}
private void renderSignaling(){
boolean consent=preferences.getBoolean("networkConsent",false);
boolean connected=consent&&signalError.isEmpty()&&signalState==1;
String label;int tint,background;
if(!consent){label="等待隐私授权";tint=0xFFB76A00;background=0xFFFFEBD2;}
else if(!signalError.isEmpty()){label=signalError.contains("TLS")?"证书校验失败 · 点击重试":"连接失败 · 点击重试";tint=RED;background=0xFFFFE8E6;}
else if(connected){label="已连接服务器";tint=GREEN;background=0xFFE5F4E8;}
else{label=signalState==0?"正在连接服务器…":signalState==4?"正在重连服务器…":"未连接服务器 · 点击重试";tint=0xFFB76A00;background=0xFFFFEBD2;}
if(signalBadge!=null){
android.graphics.drawable.Drawable icon=connected?getDrawable(R.drawable.ic_check_circle):null;
if(icon!=null){int size=dp(14);icon.setBounds(0,0,size,size);}
signalBadge.setCompoundDrawablesRelative(icon,null,null,null);signalBadge.setCompoundDrawablePadding(dp(6));
signalBadge.setText(label);signalBadge.setTextColor(tint);signalBadge.setBackground(ui.background(background,20));signalBadge.setContentDescription(signalError.isEmpty()?label:signalError+",点击重试");
}
if(identitySummary!=null)identitySummary.setText(!consent?"完成隐私授权后登记本机身份":!localIdentity.isEmpty()?"本机 ID "+localIdentity:!signalError.isEmpty()?signalError:"正在获取本机 ID…");
}
@Override public void signaling(int state,String deviceId){
signalState=state;localIdentity=deviceId;signalError="";renderSignaling();
long now=android.os.SystemClock.elapsedRealtime();recentPresence.watch(history.list(serverKey()),now);
recentPresence.setConnected(foreground&&preferences.getBoolean("networkConsent",false)&&state==1&&!deviceId.isEmpty(),now);
mainHandler.removeCallbacks(presenceTick);if(recentPresence.isConnected())mainHandler.postDelayed(presenceTick,1000);
if(preferences.getBoolean("networkConsent",false)){announcementInbox.configure(host,port,deviceId);announcementInbox.setConnected(state==1);}
}
@Override public void presence(JSONObject message){recentPresence.receive(message,android.os.SystemClock.elapsedRealtime());}
@Override public void status(String value){if(session!=null&&status!=null)status.setText(value);}
@Override public void connected(){
// Transport readiness can be reported again after ICE changes its selected path.
// The first success consumes pendingPassword; a duplicate must not save it again.
if(session==null||ready)return;ready=true;if(progressDialog!=null){progressDialog.dismiss();progressDialog=null;}
try{history.save(serverKey(),connectedRemote,connectedRemote,hostPlatform,rememberPassword,pendingPassword);}catch(Exception error){toast("密码保存失败,本次连接仍可使用");}pendingPassword="";sessionScreen();
if(!canUsePictureInPicture())prepareBackgroundSession(true);
if(videoSettings.supported&&videoSettings.requestId==0)updateVideoSettings(videoSettings.selection);
if(foreground&&preferences.getBoolean("networkConsent",false))remoteVersionCheck.connected();
}
@Override public void ended(String reason){
if(session!=null){end(reason);return;}
stopSignaling();signalError=reason;renderSignaling();
}
@Override public void passwordRejected(){
if(session==null)return;
String id=connectedRemote;boolean remember=rememberPassword;
end("");
// Let the user replace an expired credential; never retry it automatically.
if(foreground)passwordSheet(id,"访问密码错误,请重新输入",remember);
}
private void cancelVideoSettingsTimeout(){if(videoSettingsTimeout!=null)mainHandler.removeCallbacks(videoSettingsTimeout);videoSettingsTimeout=null;}
private void showRemoteUpdate(){
if(!ready||session==null||!foreground||pictureInPictureUi||isInPictureInPictureMode()||isFinishing()||!preferences.getBoolean("networkConsent",false))return;
remoteUpdateDialog=new AlertDialog.Builder(this).setTitle("升级提示").setMessage(RemoteVersionCheck.NOTICE).setPositiveButton("知道了",null).create();
remoteUpdateDialog.setOnDismissListener(dialog->remoteUpdateDialog=null);
remoteUpdateDialog.setCanceledOnTouchOutside(false);
remoteUpdateDialog.show();
}
private void resetRemoteVersionCheck(){
remoteVersionCheck.reset();
if(remoteUpdateDialog!=null){remoteUpdateDialog.dismiss();remoteUpdateDialog=null;}
}
private void resetVideoSettings(){
cancelVideoSettingsTimeout();
android.util.DisplayMetrics metrics=getResources().getDisplayMetrics();
videoSettings=new RemoteVideoSettings(preferences.getInt("videoPreference",1),Math.max(metrics.widthPixels,metrics.heightPixels));
}
private void updateVideoSettings(RemoteVideoSettings.Values value){
if(!ready||session==null||!preferences.getBoolean("networkConsent",false))return;
long request=videoSettings.begin(value);if(request<0)return;
cancelVideoSettingsTimeout();if(controls!=null)controls.videoSettings(videoSettings);session.videoSettings(value,request);
videoSettingsTimeout=()->{videoSettings.expire(request);if(controls!=null)controls.videoSettings(videoSettings);};mainHandler.postDelayed(videoSettingsTimeout,5000);
}
@Override public void data(JSONObject message){
if(session==null)return;
if(message.optInt("type",-1)==5){JSONObject service=message.optJSONObject("service_status");remoteServiceAvailable=service!=null&&service.optBoolean("available",false);return;}
if(message.optInt("type",-1)==12){if(!ready)return;videoSettings.receive(message);if(!videoSettings.pending)cancelVideoSettingsTimeout();if(controls!=null)controls.videoSettings(videoSettings);return;}
JSONObject info=message.optJSONObject("host_info");
if(info!=null){
hostPlatform=info.optString("platform","");JSONArray list=info.optJSONArray("displays");if(list!=null)displays=list;history.metadata(serverKey(),connectedRemote,info.optString("host_name",connectedRemote),hostPlatform);
boolean wasSupported=videoSettings.supported;videoSettings.setSupported(info.optBoolean("supports_video_settings",false));
if(!videoSettings.supported)cancelVideoSettingsTimeout();
if(controls!=null)controls.videoSettings(videoSettings);
if(videoSettings.supported&&!wasSupported)updateVideoSettings(videoSettings.selection);
if(foreground&&preferences.getBoolean("networkConsent",false))remoteVersionCheck.hostInfo(info);
}
}
@Override public void videoSize(int width,int height){videoWidth=width;videoHeight=height;if(video!=null)video.videoSize(width,height);if(controls!=null)controls.videoSize(width,height);pictureInPicture.videoSize(width,height);updatePictureInPicture();}
@Override public void clipboard(String value){remoteClipboard=value;}
@Override public void statistics(RemoteNetworkStatistics.Snapshot value){if(controls!=null)controls.statistics(value);if(value.fps>0)capturePreviewIfNeeded();}
@Override public boolean dispatchKeyEvent(KeyEvent event){
if(ready&&session!=null&&!pictureInPictureUi&&hasWindowFocus()&&!(getCurrentFocus() instanceof EditText)&&event.getKeyCode()!=KeyEvent.KEYCODE_BACK){int code=KeyMap.windowsCode(event.getKeyCode());if(code!=0){boolean down=event.getAction()==KeyEvent.ACTION_DOWN;if(down)pressed.add(code);else pressed.remove(code);session.key(code,down);return true;}}return super.dispatchKeyEvent(event);
}
private void releaseKeys(){if(session!=null)for(int code:pressed)session.key(code,false);pressed.clear();}
private void navigateBack(){if(backAction==null)return;navigatingBack=true;try{backAction.run();}finally{navigatingBack=false;}}
private void back(){pageHost.finish();if(session!=null){if(ready)confirmDisconnect();else end("");}else if(backAction!=null)navigateBack();else finish();}
@Override public void onWindowFocusChanged(boolean focus){super.onWindowFocusChanged(focus);if(!focus)releaseKeys();else applySystemBars(ready);}
@android.annotation.SuppressLint("GestureBackNavigation") @Override public void onBackPressed(){back();}
@Override public void onConfigurationChanged(Configuration config){
super.onConfigurationChanged(config);
releaseKeys();
if(!page.equals("session"))updateHomeOrientation();
sizePasswordDialog();
if(privacyDialog instanceof PrivacyConsentDialog)((PrivacyConsentDialog)privacyDialog).updateSize();
if(controls!=null&&!pictureInPictureUi)controls.post(controls::constrainPanels);
if(video!=null)video.post(this::updatePictureInPicture);
}
private boolean supportsPictureInPicture(){return getPackageManager().hasSystemFeature(android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE);}
private boolean canUsePictureInPicture(){
if(!supportsPictureInPicture())return false;
android.app.AppOpsManager ops=getSystemService(android.app.AppOpsManager.class);
int mode=ops.checkOpNoThrow(android.app.AppOpsManager.OPSTR_PICTURE_IN_PICTURE,android.os.Process.myUid(),getPackageName());
return mode==android.app.AppOpsManager.MODE_ALLOWED||mode==android.app.AppOpsManager.MODE_DEFAULT;
}
private void captureBackgroundSession(){
BackgroundSession retained=backgroundSession;if(retained==null)return;
retained.identity=localIdentity;retained.signalState=signalState;retained.platform=hostPlatform;retained.displays=displays;
retained.muted=muted;retained.selectedDisplay=selectedDisplay;retained.remoteServiceAvailable=remoteServiceAvailable;
retained.clipboard=remoteClipboard;retained.videoSettings=videoSettings;retained.receivedFile=receivedFile;
retained.width=videoWidth;retained.height=videoHeight;
}
private boolean prepareBackgroundSession(boolean inform){
if(!ready||session==null||session.isClosed()||isFinishing()||!hasNetworkConsent())return false;
if(backgroundSession!=null&&!backgroundSession.ended)return RemoteSessionService.current()==backgroundSession;
BackgroundSession retained=new BackgroundSession(this,session,host,port,connectedRemote);
backgroundSession=retained;captureBackgroundSession();retained.attach(this);session.setListener(retained);
if(!RemoteSessionService.retain(this,retained)){
session.setListener(this);retained.detach(this);backgroundSession=null;
if(inform)toast("后台保活未能启动,请保持应用在前台");return false;
}
if(inform){
toast("已启用后台保活,可从连接通知返回或断开");
requestBackgroundNotifications();
}
return true;
}
private void requestBackgroundNotifications(){
if(android.os.Build.VERSION.SDK_INT>=33&&checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS)!=android.content.pm.PackageManager.PERMISSION_GRANTED&&!preferences.getBoolean("notificationPermissionAsked",false)){
preferences.edit().putBoolean("notificationPermissionAsked",true).apply();
requestPermissions(new String[]{android.Manifest.permission.POST_NOTIFICATIONS},43);
}
}
private boolean restoreBackgroundSession(){
BackgroundSession retained=backgroundSession!=null?backgroundSession:RemoteSessionService.current();
if(retained==null)return false;
if(retained.ended||retained.session.isClosed()||!hasNetworkConsent()||!host.equals(retained.host)||port!=retained.port){
retained.detach(this);retained.finish("后台连接已结束,请重新连接");backgroundSession=null;
if(session==retained.session)end(retained.endReason);return false;
}
boolean rebuild=session!=retained.session||video==null||!page.equals("session");
backgroundSession=retained;session=signaling=retained.session;signalingServer=serverKey();
connectedRemote=retained.remote;localIdentity=retained.identity;signalState=retained.signalState;signalError="";
hostPlatform=retained.platform;displays=retained.displays;muted=retained.muted;selectedDisplay=retained.selectedDisplay;
remoteServiceAvailable=retained.remoteServiceAvailable;remoteClipboard=retained.clipboard;receivedFile=retained.receivedFile;
videoSettings=retained.videoSettings;ready=true;retained.attach(this);
if(rebuild)sessionScreen();
if(retained.width>0&&retained.height>0)videoSize(retained.width,retained.height);
if(controls!=null){controls.setMuted(muted);controls.videoSettings(videoSettings);controls.fileStatus(retained.fileStatus,receivedFile!=null);}
retained.setBackground(false);signaling(signalState,localIdentity);
return true;
}
private android.app.PictureInPictureParams pictureInPictureParams(){
return pictureInPicture.parameters(video==null||pictureInPictureUi||isInPictureInPictureMode()?null:video.pictureInPictureBounds());
}
private void updatePictureInPicture(){
if(!supportsPictureInPicture()||isDestroyed())return;
try{setPictureInPictureParams(pictureInPictureParams());}
catch(IllegalArgumentException|IllegalStateException error){android.util.Log.w("CrossDesk","Picture in Picture parameters unavailable",error);}
}
private void enterRemotePictureInPicture(){
if(isInPictureInPictureMode())return;
if(!canUsePictureInPicture()){
prepareBackgroundSession(false);return;
}
if(!pictureInPicture.canEnter()||session==null||session.isClosed()||isFinishing())return;
android.app.PictureInPictureParams params=pictureInPictureParams();
setPictureInPictureUi(true);
boolean entered=false;
try{entered=enterPictureInPictureMode(params);}
catch(IllegalArgumentException|IllegalStateException error){android.util.Log.w("CrossDesk","Picture in Picture could not start",error);}
if(!entered){setPictureInPictureUi(false);prepareBackgroundSession(false);}
}
private void setPictureInPictureUi(boolean value){
pictureInPictureUi=value;
if(value){releaseKeys();hideKeyboard();pageHost.finish();if(disconnectDialog!=null)disconnectDialog.dismiss();if(remoteUpdateDialog!=null)remoteUpdateDialog.dismiss();}
if(controls!=null)controls.setPictureInPicture(value);
if(video!=null)video.setPictureInPicture(value);
}
@Override protected void onUserLeaveHint(){
super.onUserLeaveHint();
if(documentSession!=null)return;
if(!canUsePictureInPicture()||!pictureInPicture.canEnter())prepareBackgroundSession(false);
else if(android.os.Build.VERSION.SDK_INT<31)enterRemotePictureInPicture();
}
@Override public void onPictureInPictureModeChanged(boolean active,Configuration config){
super.onPictureInPictureModeChanged(active,config);if(active)enteredPictureInPicture=true;setPictureInPictureUi(active);
if(!active&&video!=null)video.post(this::updatePictureInPicture);
}
@android.annotation.TargetApi(31)
@Override public void onPictureInPictureUiStateChanged(android.app.PictureInPictureUiState state){
super.onPictureInPictureUiStateChanged(state);
if(android.os.Build.VERSION.SDK_INT>=35&&state.isTransitioningToPip())setPictureInPictureUi(true);
}
@Override protected void onResume(){super.onResume();if(!isInPictureInPictureMode())enteredPictureInPicture=false;setPictureInPictureUi(isInPictureInPictureMode());updatePictureInPicture();if(ready&&!canUsePictureInPicture())prepareBackgroundSession(true);if(backgroundSession!=null)requestBackgroundNotifications();}
// onStart marks a new visit; focus/resume callbacks must not reopen a refused notice.
@Override protected void onPause(){releaseKeys();if(controls!=null)controls.cancelMouseInput();if(video!=null)video.releaseMouse();super.onPause();}
@Override protected void onStart(){super.onStart();foreground=true;restoreBackgroundSession();appUpdates.setEnabled(preferences.getBoolean("networkConsent",false));if(!preferences.getBoolean("networkConsent",false))consent(this::renderSignaling);ensureSignaling();showConnectionMessage();}
@Override protected void onStop(){foreground=false;appUpdates.setEnabled(false);if(privacyDialog!=null)privacyDialog.dismiss();pageHost.finish();
if(connectionDialog!=null)connectionDialog.dismiss();
// Closing native PiP is an explicit end, not a request for invisible
// fallback. An unavailable/failed PiP can hand its live session off.
if(!isFinishing()&&!enteredPictureInPicture&&ready&&(backgroundSession!=null||documentSession==null)&&prepareBackgroundSession(false)){
captureBackgroundSession();backgroundSession.detach(this);backgroundSession.setBackground(true);
mainHandler.removeCallbacks(presenceTick);recentPresence.setConnected(false,android.os.SystemClock.elapsedRealtime());announcementInbox.setConnected(false);
cancelVideoSettingsTimeout();if(videoSettings.pending)videoSettings.expire(videoSettings.requestId);
resetRemoteVersionCheck();if(disconnectDialog!=null)disconnectDialog.dismiss();
}else if(documentSession==null||documentSession!=session||isFinishing()){if(session!=null)end(isFinishing()?"":"远程窗口已关闭,或后台保活未能启动,会话已结束");stopSignaling();}
super.onStop();}
@Override protected void onDestroy(){mainHandler.removeCallbacks(documentTimeout);documentSession=null;documentToSave=null;appUpdates.setEnabled(false);pageHost.finish();resetRemoteVersionCheck();cancelVideoSettingsTimeout();previews.removeListener(previewChanged);if(privacyDialog!=null)privacyDialog.dismiss();if(previewDialog!=null)previewDialog.dismiss();announcementInbox.close();if(disconnectDialog!=null)disconnectDialog.dismiss();if(passwordDialog!=null)passwordDialog.dismiss();if(progressDialog!=null)progressDialog.dismiss();
if(connectionDialog!=null)connectionDialog.dismiss();
boolean retained=!isFinishing()&&backgroundSession!=null&&!backgroundSession.ended&&RemoteSessionService.current()==backgroundSession;
if(backgroundSession!=null)backgroundSession.detach(this);
if(!retained){if(session!=null)session.close();stopSignaling();}else{mainHandler.removeCallbacks(presenceTick);session=signaling=null;}
super.onDestroy();}
}
@@ -0,0 +1,142 @@
package cn.crossdesk.mobile;
import android.content.Context;
import android.graphics.*;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.view.*;
import android.widget.*;
/** Shared visual tokens matching the SwiftUI mobile screens. Values are in dp/sp. */
final class MobileUi {
static final int BACKGROUND=0xFFF2F2F7, INK=0xFF1C1C1E, SECONDARY=0xFF737378,
LINE=0xFFE2E2E7, BLUE=0xFF2E7ADB, RED=0xFFFF3B30, GREEN=0xFF248A3D;
// Match the iOS 26 Form sections and segmented Picker dimensions.
static final int SETTINGS_CARD_RADIUS=26, SEGMENT_HEIGHT=32, SEGMENT_INSET=2;
final Context context;
MobileUi(Context context) { this.context=context; }
int dp(float value) { return Math.round(value*context.getResources().getDisplayMetrics().density); }
GradientDrawable background(int color,int radius) {
GradientDrawable shape=new GradientDrawable();shape.setColor(color);shape.setCornerRadius(dp(radius));return shape;
}
void card(View view,int radius) { GradientDrawable shape=background(Color.WHITE,radius);shape.setStroke(dp(.5f),LINE);view.setBackground(shape);view.setClipToOutline(true); }
FrameLayout shadowCard(View content,int radius) {
card(content,radius);
FrameLayout wrapper=new FrameLayout(context);
wrapper.setClipChildren(false);wrapper.setClipToPadding(false);
wrapper.setBackground(new CardShadow(dp(radius),dp(14),dp(5)));
wrapper.addView(content,new FrameLayout.LayoutParams(-1,-2));
return wrapper;
}
LinearLayout column() { LinearLayout v=new LinearLayout(context);v.setOrientation(LinearLayout.VERTICAL);return v; }
LinearLayout pageColumn(int maxWidth) {
LinearLayout v=new LinearLayout(context){
@Override protected void onMeasure(int widthSpec,int heightSpec){
if(maxWidth>0&&MeasureSpec.getSize(widthSpec)>dp(maxWidth))
widthSpec=MeasureSpec.makeMeasureSpec(dp(maxWidth),MeasureSpec.EXACTLY);
super.onMeasure(widthSpec,heightSpec);
}
};
v.setOrientation(LinearLayout.VERTICAL);return v;
}
LinearLayout row() { LinearLayout v=new LinearLayout(context);v.setGravity(Gravity.CENTER_VERTICAL);return v; }
TextView text(String title,int size,boolean bold) {
TextView v=new TextView(context);v.setText(title);v.setTextSize(size);v.setTextColor(INK);v.setIncludeFontPadding(false);
if(bold)v.setTypeface(null,Typeface.BOLD);return v;
}
TextView action(String title,int color,Runnable click) {
TextView v=text(title,16,true);v.setGravity(Gravity.CENTER);v.setTextColor(color);
v.setMinHeight(dp(48));v.setClickable(true);v.setFocusable(true);v.setOnClickListener(ignored->click.run());
v.setAccessibilityDelegate(new View.AccessibilityDelegate(){@Override public void onInitializeAccessibilityNodeInfo(View host,android.view.accessibility.AccessibilityNodeInfo info){super.onInitializeAccessibilityNodeInfo(host,info);info.setClassName("android.widget.Button");}});
return v;
}
TextView primary(String title,Runnable click) {
TextView v=action(title,Color.WHITE,click);
GradientDrawable gradient=new GradientDrawable(GradientDrawable.Orientation.TL_BR,new int[]{BLUE,0xFF1F61C7});gradient.setCornerRadius(dp(12));v.setBackground(gradient);return v;
}
View iconButton(String icon,String label,Runnable click) {
FrameLayout box=new FrameLayout(context);box.setBackground(background(Color.WHITE,10));
Icon glyph=new Icon(context,icon,INK);FrameLayout.LayoutParams p=new FrameLayout.LayoutParams(dp(22),dp(22),Gravity.CENTER);box.addView(glyph,p);
box.setContentDescription(label);box.setClickable(true);box.setFocusable(true);box.setOnClickListener(v->click.run());return box;
}
View icon(String name,int color) { return new Icon(context,name,color); }
void gap(LinearLayout parent,int height){parent.addView(new View(context),new LinearLayout.LayoutParams(1,dp(height)));}
void divider(LinearLayout parent){View line=new View(context);line.setBackgroundColor(LINE);parent.addView(line,new LinearLayout.LayoutParams(-1,dp(.5f)));}
LinearLayout.LayoutParams size(int width,int height){return new LinearLayout.LayoutParams(width<0?width:dp(width),height<0?height:dp(height));}
/** The iOS connection panel uses black at 5.5%, blur 14, y 5, rather than elevation. */
private static final class CardShadow extends Drawable {
private final Paint bitmapPaint=new Paint(Paint.ANTI_ALIAS_FLAG|Paint.FILTER_BITMAP_FLAG);
private final float cornerRadius,blurRadius,offsetY;
private final int inset;
private Bitmap bitmap;
CardShadow(float cornerRadius,float blurRadius,float offsetY) {
this.cornerRadius=cornerRadius;this.blurRadius=blurRadius;this.offsetY=offsetY;
inset=(int)Math.ceil(blurRadius*2+Math.abs(offsetY));
}
@Override protected void onBoundsChange(Rect bounds) {
bitmap=null;
if(bounds.isEmpty())return;
// Render once on a bitmap canvas: shadow layers need software rendering on API 26.
bitmap=Bitmap.createBitmap(bounds.width()+inset*2,bounds.height()+inset*2,Bitmap.Config.ARGB_8888);
bitmap.setDensity(Bitmap.DENSITY_NONE);
Paint shadowPaint=new Paint(Paint.ANTI_ALIAS_FLAG);
shadowPaint.setColor(Color.WHITE);
shadowPaint.setShadowLayer(blurRadius,0,offsetY,Color.argb(Math.round(255*.055f),0,0,0));
new Canvas(bitmap).drawRoundRect(inset,inset,inset+bounds.width(),inset+bounds.height(),cornerRadius,cornerRadius,shadowPaint);
}
@Override public void draw(Canvas canvas) {
if(bitmap!=null)canvas.drawBitmap(bitmap,getBounds().left-inset,getBounds().top-inset,bitmapPaint);
}
@Override public void setAlpha(int alpha) { bitmapPaint.setAlpha(alpha);invalidateSelf(); }
@Override public void setColorFilter(ColorFilter filter) { bitmapPaint.setColorFilter(filter);invalidateSelf(); }
@Override public int getOpacity() { return PixelFormat.TRANSLUCENT; }
}
@android.annotation.SuppressLint("ViewConstructor") // Programmatic icon primitive, not inflated from XML.
static final class Icon extends View {
private final Paint paint=new Paint(Paint.ANTI_ALIAS_FLAG); private final String name;
Icon(Context context,String name,int color){super(context);this.name=name;paint.setColor(color);setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);}
@Override protected void onDraw(Canvas c){
c.save();c.scale(getWidth()/24f,getHeight()/24f);paint.setStyle(Paint.Style.STROKE);paint.setStrokeWidth(1.7f);paint.setStrokeCap(Paint.Cap.ROUND);paint.setStrokeJoin(Paint.Join.ROUND);
switch(name){
case "settings":
Path gear=new Path();
float[] toothAngles={-17,-10,10,17};
for(int tooth=0;tooth<8;tooth++){
for(int corner=0;corner<4;corner++){
double angle=Math.toRadians(tooth*45-90+toothAngles[corner]);
float radius=corner==0||corner==3?7.5f:10f;
float x=12+radius*(float)Math.cos(angle),y=12+radius*(float)Math.sin(angle);
if(tooth==0&&corner==0)gear.moveTo(x,y);else gear.lineTo(x,y);
}
}
gear.close();c.drawPath(gear,paint);c.drawCircle(12,12,3.2f,paint);break;
case "envelope":
c.drawRoundRect(2,5,22,19,2,2,paint);path(c,3,6,12,13,21,6);break;
case "history":
c.drawArc(4,4,21,21,215,315,false,paint);path(c,3,4,3,10,9,10);path(c,12,7,12,13,16,15);break;
case "back":path(c,15,4,7,12,15,20);break;
case "refresh":c.drawArc(4,4,20,20,35,310,false,paint);path(c,20,3,20,9,14,9);break;
case "close":path(c,6,6,18,18);path(c,18,6,6,18);break;
case "arrow":path(c,4,12,20,12);path(c,14,6,20,12,14,18);break;
case "keyboard":
c.drawRoundRect(2,5,22,19,3,3,paint);for(int y=9;y<=12;y+=3)for(int x=6;x<=18;x+=4)c.drawPoint(x,y,paint);c.drawLine(7,16,17,16,paint);break;
case "display":c.drawRoundRect(2,3,22,17,2,2,paint);path(c,12,17,12,21);path(c,7,21,17,21);break;
case "sliders":
for(int y=6;y<=18;y+=6){c.drawLine(3,y,21,y,paint);c.drawCircle(y==12?15:8,y,2,paint);}break;
case "audio":path(c,3,9,7,9,12,4,12,20,7,15,3,15,3,9);c.drawArc(10,5,21,19,-65,130,false,paint);break;
case "mouse":c.drawRoundRect(5,2,19,22,7,7,paint);path(c,12,3,12,10);break;
case "folder":path(c,2,19,2,5,9,5,12,8,22,8,22,19,2,19);break;
case "chart":path(c,3,3,3,21,22,21);path(c,7,17,7,13);path(c,12,17,12,8);path(c,18,17,18,4);break;
case "lock":c.drawRoundRect(5,10,19,22,2,2,paint);c.drawArc(8,2,16,15,180,180,false,paint);c.drawPoint(12,16,paint);break;
case "key":
paint.setStyle(Paint.Style.FILL);c.drawCircle(7,8,5,paint);paint.setStyle(Paint.Style.STROKE);paint.setStrokeWidth(4);path(c,10,11,19,20);path(c,15,16,18,13);path(c,18,19,21,16);
paint.setStyle(Paint.Style.FILL);int keyColor=paint.getColor();paint.setColor(Color.WHITE);c.drawCircle(6,7,1.5f,paint);paint.setColor(keyColor);break;
case "unlock":c.drawRoundRect(5,10,19,22,2,2,paint);c.drawArc(8,2,16,15,180,150,false,paint);c.drawPoint(12,16,paint);break;
case "clipboard":c.drawRoundRect(4,4,20,22,2,2,paint);c.drawRoundRect(8,2,16,7,2,2,paint);break;
case "eye":path(c,2,12,6,7,12,5,18,7,22,12,18,17,12,19,6,17,2,12);c.drawCircle(12,12,3,paint);break;
default:c.drawCircle(12,12,9,paint);path(c,12,10,12,17);c.drawPoint(12,6,paint);
}c.restore();
}
private void path(Canvas c,float... values){Path p=new Path();p.moveTo(values[0],values[1]);for(int i=2;i<values.length;i+=2)p.lineTo(values[i],values[i+1]);c.drawPath(p,paint);}
}
}
@@ -0,0 +1,304 @@
package cn.crossdesk.mobile;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Base64;
import android.view.Surface;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.security.KeyStore;
import java.security.cert.X509Certificate;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
final class NativeSession implements AutoCloseable {
static { System.loadLibrary("crossdesk_android"); }
interface Listener {
void status(String message);
void connected();
void ended(String reason);
void data(JSONObject message);
void videoSize(int width, int height);
void clipboard(String text);
void statistics(RemoteNetworkStatistics.Snapshot value);
default void fileTransfer(String name,double progress,boolean sending,File received) { }
default void controlFeedback(String message) { }
default void signaling(int state, String deviceId) { }
default void presence(JSONObject message) { }
default void announcement(JSONObject message) { }
default void announcementFailed(String requestId) { }
default void passwordRejected() { ended("远端密码错误"); }
}
// Serializes all peer creation/API calls/destruction, including across activities.
private static final ExecutorService RTC = Executors.newSingleThreadExecutor(r -> new Thread(r, "CrossDesk RTC"));
private final Handler main = new Handler(Looper.getMainLooper());
private final Context context;
private volatile Listener listener;
private final SecretStore secrets;
private final String host, scope;
private volatile String remote;
private String password, identity = "";
private final int port;
private long handle;
private boolean signalReady, joining, connected, started;
private int signalState;
private volatile long signalGeneration;
private boolean presenceRequested;
private volatile boolean closed;
private Surface surface;
private volatile AudioPlayer audio;
private final SessionDocuments documents;
private boolean sendingFile;
private final Runnable fileTick=new Runnable(){public void run(){
execute(()->{boolean sending=connected&&handle!=0&&nPumpFiles(handle);if(!closed)main.postDelayed(this,sending?10:1000);});
}};
private final RemoteNetworkStatistics networkStatistics=new RemoteNetworkStatistics();
private final Runnable statisticsTick=new Runnable(){public void run(){
if(closed)return;
listener.statistics(networkStatistics.snapshot(RemoteNetworkStatistics.now()));
if(!closed)main.postDelayed(this,1000);
}};
private final Runnable timeout = () -> fail(remote.isEmpty()
? "服务器连接超时,请检查服务器地址和网络"
: "连接超时,请检查设备 ID、服务器及远端在线状态");
NativeSession(Context context, String host, int port, String remote, String password, Listener listener) {
this.context = context.getApplicationContext(); this.listener = listener;
this.host = host; this.port = port; this.remote = remote; this.password = password;
scope = host.toLowerCase(java.util.Locale.ROOT) + ":" + port;
secrets = new SecretStore(this.context);
documents = new SessionDocuments(this.context);
}
void start() {
if (started || closed) return;
started = true;
main.postDelayed(timeout, 40000);
execute(() -> {
try {
identity = secrets.get(scope);
File certificates = exportTrust();
File logs = new File(context.getNoBackupFilesDir(), "logs");
if (!logs.isDirectory() && !logs.mkdirs()) throw new IllegalStateException("Log directory unavailable");
handle = nCreate(this, host, port, identity, logs.getAbsolutePath(), certificates.getAbsolutePath());
if (handle == 0) { fail("原生连接初始化失败"); return; }
nFileDirectory(handle,new File(documents.directory,"received").getAbsolutePath());
if (surface != null && surface.isValid()) nSurface(handle, surface);
} catch (Exception error) { fail("安全存储或证书初始化失败,请重试或清除应用数据"); }
});
}
/** Promote the already registered identity peer to an outgoing desktop session. */
void connect(String remoteId, String secret) {
execute(() -> {
if (joining || connected) return;
remote = remoteId;
password = secret;
// Serialize arming with identity callbacks, which cancel the idle
// login timeout. Otherwise a just-completed login can cancel this
// outgoing connection's timeout before tryJoin runs.
main.removeCallbacks(timeout);
main.postDelayed(timeout, 40000);
tryJoin();
});
}
boolean isClosed() { return closed; }
// UI callbacks run on the main thread. A service-owned state can replace
// the Activity listener without recreating either native peer.
void setListener(Listener value) { listener = java.util.Objects.requireNonNull(value); }
private void publishSignaling() {
int state = signalState;
// Only expose the public device ID, never the identity's @password suffix.
String deviceId = identity.split("@", 2)[0];
ui(() -> listener.signaling(state, deviceId));
}
private File exportTrust() throws Exception {
TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
factory.init((KeyStore) null);
StringBuilder pem = new StringBuilder();
for (TrustManager manager : factory.getTrustManagers()) {
if (manager instanceof X509TrustManager trust) {
for (X509Certificate certificate : trust.getAcceptedIssuers()) {
pem.append("-----BEGIN CERTIFICATE-----\n")
.append(Base64.encodeToString(certificate.getEncoded(), Base64.NO_WRAP))
.append("\n-----END CERTIFICATE-----\n");
}
}
}
if (pem.length() == 0) throw new IllegalStateException("Empty Android trust store");
File output = new File(context.getNoBackupFilesDir(), "trusted-roots.pem");
Files.write(output.toPath(), pem.toString().getBytes(StandardCharsets.US_ASCII));
return output;
}
private void execute(Runnable task) { RTC.execute(() -> { if (!closed) task.run(); }); }
private void ui(Runnable task) { main.post(() -> { if (!closed) task.run(); }); }
private void fail(String reason) { ui(() -> { listener.ended(reason); close(); }); }
private void tryJoin() {
if (handle == 0 || joining || remote.isEmpty() || !signalReady || identity.isEmpty()) return;
joining = true;
String base = identity.split("@", 2)[0];
if (!nConnect(handle, base, remote, password)) fail("无法发起远程连接");
password = "";
}
// Called on arbitrary native callback threads; borrowed payloads were copied by JNI.
@SuppressWarnings("unused") private void onNativeEvent(int type, byte[] bytes) {
execute(() -> {
String value = new String(bytes, StandardCharsets.UTF_8);
try {
if (type == 3) {
if (value.contains("@")) {
identity = value;
secrets.put(scope, identity);
} else if (!identity.startsWith(value + "@")) identity = value;
publishSignaling(); tryJoin(); return;
}
if (type == 6) { ui(() -> listener.clipboard(value)); return; }
JSONObject event = new JSONObject(value);
if (type == 1) {
int status = event.getInt("status");
if (!event.getBoolean("controller")) {
long generation=event.optLong("generation");
if(signalGeneration!=generation){signalGeneration=generation;presenceRequested=false;}
signalState = status;
signalReady = status == 1;
if (signalReady && remote.isEmpty()) main.removeCallbacks(timeout);
publishSignaling();
tryJoin();
}
if (status == 6) fail("服务器 TLS 证书校验失败");
else if (status == 2) fail("服务器登录失败,请检查服务器地址和网络");
else if (status >= 3 && connected) fail("信令连接中断,请重新连接");
else if (status == 0 || status == 4) ui(() -> listener.status("正在连接信令服务器…"));
} else if (type == 2) {
int status = event.getInt("status");
if (status == 1) {
if (connected) return; // Repeated transport readiness is the same desktop session.
connected = true; main.removeCallbacks(timeout); nReady(handle);
audio = new AudioPlayer();
nControl(handle, 2, 1);
ui(() -> { listener.connected(); if(!closed){statisticsTick.run();fileTick.run();} });
} else if (status == 0 || status == 2) ui(() -> listener.status("正在建立安全连接…"));
else if (status == 6) ui(() -> { listener.passwordRejected(); close(); });
else {
String[] reasons = {"", "", "", "连接已断开", "连接失败", "远端已关闭连接",
"远端密码错误", "找不到该设备 ID", "远端当前不可用"};
fail(status >= 0 && status < reasons.length ? reasons[status] : "连接已结束");
}
} else if (type == 4) ui(() -> listener.data(event));
else if (type == 5) {
int width = event.getInt("width"), height = event.getInt("height");
ui(() -> listener.videoSize(width, height));
} else if (type == 7) networkStatistics.receive(new RemoteNetworkStatistics.Report(event),RemoteNetworkStatistics.now());
else if (type == 8 && signalReady) ui(() -> listener.announcement(event));
else if (type == 9 && signalReady && presenceRequested) {
long generation=event.optLong("generation");
if(generation==signalGeneration)ui(()->{if(generation==signalGeneration)listener.presence(event);});
} else if(type==10){
String name=event.getString("name"),path=event.optString("path");
double progress=event.getDouble("progress");boolean sending=event.getBoolean("sending");
ui(()->{if(sending&&(progress<0||progress>=1))sendingFile=false;
listener.fileTransfer(name,progress,sending,path.isEmpty()?null:new File(path));});
}
} catch (Exception error) {
if (type == 3) fail("设备身份保存失败,请检查安全存储");
}
});
}
@SuppressWarnings("unused") private void onNativeAudio(byte[] pcm) {
AudioPlayer player = audio;
if (!closed && player != null) player.offer(pcm);
}
@SuppressWarnings("unused") private void onNativeVideoFrame(long id,double latency,int width,int height){
if(!closed)networkStatistics.frame(id,latency,width,height,RemoteNetworkStatistics.now());
}
void videoSettings(RemoteVideoSettings.Values settings,long requestId){
if(!settings.valid()||requestId<0||requestId>0xffffffffL)return;
execute(()->{if(connected&&!nVideoSettings(handle,settings.quality,settings.frameRate,settings.preference,requestId))ui(()->listener.data(settings.status(requestId,false)));});
}
void announcementRequest(JSONObject request,String requestId){
byte[] bytes=request.toString().getBytes(StandardCharsets.UTF_8);
execute(()->{if(!signalReady||identity.isEmpty()||!nAnnouncementRequest(handle,bytes))ui(()->listener.announcementFailed(requestId));});
}
void presenceRequest(JSONArray ids){
// Own the caller's list before crossing to the serialized RTC executor.
String devices=ids.toString();
execute(()->{
if(!signalReady||identity.isEmpty())return;
try{
JSONObject request=new JSONObject().put("type","recent_connections_presence")
.put("user_id",identity.split("@",2)[0]).put("devices",new JSONArray(devices)).put("subscribe",true);
if(nPresenceRequest(handle,request.toString().getBytes(StandardCharsets.UTF_8)))presenceRequested=true;
}catch(org.json.JSONException ignored){ }
});
}
void surface(Surface value) { execute(() -> { surface = value; if (handle != 0) nSurface(handle, value); }); }
void pointer(float x, float y, int flag, int wheel) { execute(() -> { if (connected) nPointer(handle, x, y, flag, wheel); }); }
void key(int code, boolean down) { execute(() -> { if (connected) nKey(handle, code, down); }); }
void control(int type, int value) {
AudioPlayer player = audio;
if (type == 2 && player != null) player.setEnabled(value != 0);
execute(() -> { if (connected){nControl(handle, type, value);if(type==4)networkStatistics.resetVideo();} });
}
void clipboard(String value) {
byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
if (bytes.length == 0 || bytes.length > 128 * 1024) return;
execute(() -> { if (connected) nClipboard(handle, bytes); });
}
void secureAttention(){execute(()->{
boolean sent=connected&&nSecureAttention(handle);
ui(()->listener.controlFeedback(sent?"已发送 Ctrl+Alt+Del":"指令发送失败,请重试"));
});}
void sendFile(android.net.Uri uri){
if(closed)return;
if(sendingFile){listener.controlFeedback("请等待当前文件发送完成");return;}
sendingFile=true;listener.fileTransfer("正在读取所选文件…",0,true,null);
documents.prepare(uri,new SessionDocuments.Prepared(){
public void ready(File file,String name){execute(()->{
if(!connected||!nSendFile(handle,file.getAbsolutePath(),name.getBytes(StandardCharsets.UTF_8))){
file.delete();ui(()->{sendingFile=false;listener.fileTransfer(name,-1,true,null);});
}
});}
public void failed(){ui(()->{sendingFile=false;listener.fileTransfer("所选文件(无法读取或空间不足)",-1,true,null);});}
});
}
void saveFile(File file,android.net.Uri destination){
if(closed)return;
documents.save(file,destination,success->ui(()->listener.controlFeedback(success?"文件已保存":"文件保存失败,请重试")));
}
@Override public void close() {
if (closed) return;
closed = true; main.removeCallbacks(timeout);main.removeCallbacks(statisticsTick);main.removeCallbacks(fileTick);
RTC.execute(() -> {
main.removeCallbacks(timeout);
if (audio != null) { audio.close(); audio = null; }
password = "";
if (handle != 0) { nDestroy(handle); handle = 0; }
documents.close();
surface = null;
});
}
static native boolean nValidAppVersion(String version);
static native boolean nHasAppUpdate(String version, byte[] releaseJson);
static native String nCheckMobileUpdate(String version, byte[] releaseJson);
private static native long nCreate(NativeSession owner, String host, int port, String identity, String logs, String roots);
private static native boolean nConnect(long handle, String identity, String remote, String password);
private static native void nReady(long handle);
private static native void nPointer(long handle, float x, float y, int flag, int wheel);
private static native void nKey(long handle, int code, boolean down);
private static native void nControl(long handle, int type, int value);
private static native boolean nVideoSettings(long handle,int quality,int frameRate,int preference,long requestId);
private static native boolean nAnnouncementRequest(long handle,byte[] data);
private static native boolean nPresenceRequest(long handle,byte[] data);
private static native void nClipboard(long handle, byte[] data);
private static native boolean nSecureAttention(long handle);
private static native void nFileDirectory(long handle,String directory);
private static native boolean nSendFile(long handle,String path,byte[] name);
private static native boolean nPumpFiles(long handle);
private static native void nSurface(long handle, Surface surface);
private static native void nDestroy(long handle);
}
@@ -0,0 +1,95 @@
package cn.crossdesk.mobile;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.PathInterpolator;
import android.widget.FrameLayout;
/** Retains only the current page and, during a transition, the outgoing page. */
final class PageHost extends FrameLayout {
enum Motion { NONE, PUSH, POP, SESSION_IN, SESSION_OUT }
private FrameLayout current, outgoing;
private Motion motion=Motion.NONE;
private ValueAnimator animator;
private ViewTreeObserver pendingObserver;
private ViewTreeObserver.OnPreDrawListener pendingStart;
private int accessibility, focusability;
private float distance;
private long generation;
PageHost(Context context){super(context);setBackgroundColor(MobileUi.BACKGROUND);}
void show(FrameLayout page,Motion requested){
finish();
FrameLayout previous=current;current=page;
if(previous==null||requested==Motion.NONE||!ValueAnimator.areAnimatorsEnabled()||!isAttachedToWindow()){
removeAllViews();addView(page,new LayoutParams(-1,-1));page.requestApplyInsets();return;
}
outgoing=previous;motion=requested;
accessibility=page.getImportantForAccessibility();
focusability=page.getDescendantFocusability();
previous.clearFocus();previous.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);
page.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);
page.setDescendantFocusability(FOCUS_BLOCK_DESCENDANTS);
boolean underneath=motion==Motion.POP||motion==Motion.SESSION_IN;
addView(page,underneath?0:getChildCount(),new LayoutParams(-1,-1));
// SurfaceView pages stay opaque and unlayered. Fade the ordinary UI above them.
if(motion==Motion.PUSH||motion==Motion.POP){
previous.setLayerType(LAYER_TYPE_HARDWARE,null);page.setLayerType(LAYER_TYPE_HARDWARE,null);
(motion==Motion.PUSH?page:previous).setElevation(8*getResources().getDisplayMetrics().density);
}else (motion==Motion.SESSION_IN?previous:page).setLayerType(LAYER_TYPE_HARDWARE,null);
distance=getWidth()*(getLayoutDirection()==LAYOUT_DIRECTION_RTL?-1:1);
progress(0);page.requestApplyInsets();
// Wait for content and insets, so the first drawn frame already has the right position.
long transition=generation;
pendingObserver=getViewTreeObserver();
pendingStart=()->{
if(transition!=generation||outgoing==null)return true;
clearPendingStart();distance=getWidth()*(getLayoutDirection()==LAYOUT_DIRECTION_RTL?-1:1);progress(0);
ValueAnimator next=ValueAnimator.ofFloat(0,1);animator=next;
boolean session=motion==Motion.SESSION_IN||motion==Motion.SESSION_OUT;
next.setDuration(session?200:350);
next.setInterpolator(session?new PathInterpolator(.42f,0,.58f,1):new PathInterpolator(.25f,.1f,.25f,1));
next.addUpdateListener(value->{if(animator==value)progress((float)value.getAnimatedValue());});
next.addListener(new AnimatorListenerAdapter(){@Override public void onAnimationEnd(Animator value){if(animator==value)finish();}});
next.start();return true;
};
pendingObserver.addOnPreDrawListener(pendingStart);
}
private void progress(float value){
switch(motion){
case PUSH -> {current.setTranslationX(distance*(1-value));outgoing.setTranslationX(-distance*.3f*value);}
case POP -> {current.setTranslationX(-distance*.3f*(1-value));outgoing.setTranslationX(distance*value);}
case SESSION_IN -> outgoing.setAlpha(1-value);
case SESSION_OUT -> current.setAlpha(value);
default -> {}
}
}
void finish(){
generation++;
clearPendingStart();
ValueAnimator running=animator;animator=null;if(running!=null)running.cancel();
if(outgoing==null)return;
reset(outgoing);removeView(outgoing);outgoing=null;
reset(current);current.setImportantForAccessibility(accessibility);
current.setDescendantFocusability(focusability);motion=Motion.NONE;
}
private void clearPendingStart(){
if(pendingObserver!=null&&pendingObserver.isAlive()&&pendingStart!=null)pendingObserver.removeOnPreDrawListener(pendingStart);
pendingObserver=null;pendingStart=null;
}
private static void reset(View page){page.setTranslationX(0);page.setAlpha(1);page.setElevation(0);page.setLayerType(LAYER_TYPE_NONE,null);}
@Override public boolean onInterceptTouchEvent(MotionEvent event){return outgoing!=null||super.onInterceptTouchEvent(event);}
@android.annotation.SuppressLint("ClickableViewAccessibility") // A temporary input shield; the pages own all click actions.
@Override public boolean onTouchEvent(MotionEvent event){return outgoing!=null||super.onTouchEvent(event);}
@Override protected void onSizeChanged(int w,int h,int oldw,int oldh){super.onSizeChanged(w,h,oldw,oldh);if(oldw>0&&oldh>0&&(w!=oldw||h!=oldh))finish();}
@Override protected void onDetachedFromWindow(){finish();super.onDetachedFromWindow();}
}
@@ -0,0 +1,47 @@
package cn.crossdesk.mobile;
import android.app.Activity;
import android.app.Dialog;
import android.view.Gravity;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import static cn.crossdesk.mobile.MobileUi.*;
/** Explicit agreement is required; refusal dismisses only the current visit. */
final class PrivacyConsentDialog extends Dialog {
private final Activity activity;
private final MobileUi ui;
PrivacyConsentDialog(Activity activity,MobileUi ui,Runnable accepted){
this(activity,ui,new PrivacyPolicyDocument(activity),accepted);
}
PrivacyConsentDialog(Activity activity,MobileUi ui,PrivacyPolicyDocument policy,Runnable accepted){
super(activity);this.activity=activity;this.ui=ui;requestWindowFeature(Window.FEATURE_NO_TITLE);setCancelable(false);setCanceledOnTouchOutside(false);
LinearLayout sheet=ui.column();sheet.setBackground(ui.background(android.graphics.Color.WHITE,20));sheet.setClipToOutline(true);
TextView title=ui.text("隐私政策",17,true);title.setGravity(Gravity.CENTER);sheet.addView(title,ui.size(-1,56));ui.divider(sheet);
sheet.addView(policy.view(ui),new LinearLayout.LayoutParams(-1,0,1));ui.divider(sheet);
LinearLayout actions=ui.column();actions.setPadding(ui.dp(20),ui.dp(12),ui.dp(20),ui.dp(12));sheet.addView(actions);
CheckBox hasReadPolicy=new CheckBox(activity);hasReadPolicy.setText("我已阅读并同意《隐私政策》");hasReadPolicy.setTextColor(INK);hasReadPolicy.setTextSize(14);hasReadPolicy.setMinHeight(ui.dp(44));actions.addView(hasReadPolicy,ui.size(-1,-2));ui.gap(actions,12);
TextView agree=ui.primary("同意并继续",()->{
if(!hasReadPolicy.isChecked()||!policy.available)return;
dismiss();accepted.run();
});agree.setEnabled(false);agree.setAlpha(.45f);actions.addView(agree,ui.size(-1,48));
hasReadPolicy.setOnCheckedChangeListener((button,checked)->{boolean enabled=checked&&policy.available;agree.setEnabled(enabled);agree.setAlpha(enabled?1:.45f);});
ui.gap(actions,12);actions.addView(ui.action("暂不同意",SECONDARY,this::dismiss),ui.size(-1,44));
setContentView(sheet);Window window=getWindow();if(window!=null){window.setBackgroundDrawableResource(android.R.color.transparent);window.setDimAmount(.22f);}
}
@Override public void show(){
super.show();updateSize();
}
void updateSize(){
android.content.res.Configuration configuration=activity.getResources().getConfiguration();
boolean wide=configuration.screenWidthDp>=600;
Window window=getWindow();if(window!=null){
window.setLayout(wide?ui.dp(Math.min(640,configuration.screenWidthDp-48)):-1,
Math.min(ui.dp(760),Math.round(ui.dp(configuration.screenHeightDp)*.9f)));
window.setGravity(wide?Gravity.CENTER:Gravity.BOTTOM);
}
}
}
@@ -0,0 +1,39 @@
package cn.crossdesk.mobile;
import android.content.Context;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import java.io.IOException;
import static cn.crossdesk.mobile.MobileUi.*;
/** The same bundled policy as iOS, readable before any network consent. */
final class PrivacyPolicyDocument {
final boolean available;
final String text;
PrivacyPolicyDocument(Context context){this(load(context));}
PrivacyPolicyDocument(String document){
available=document!=null&&!document.trim().isEmpty();
String value=available?document:"隐私政策暂时无法读取,请拒绝联网并重新安装应用。";
int start=value.indexOf("## 中文\n"),end=start<0?-1:value.indexOf("## English",start);
text=start>=0&&end>start?value.substring(start+"## 中文\n".length(),end).trim():value;
}
private static String load(Context context){
try{return LicenseCatalog.read(context,"PRIVACY.md");}catch(IOException error){return null;}
}
ScrollView view(MobileUi ui){
ScrollView scroll=new ScrollView(ui.context);scroll.setBackgroundColor(android.graphics.Color.WHITE);
LinearLayout content=ui.column();content.setPadding(ui.dp(20),ui.dp(20),ui.dp(20),ui.dp(20));scroll.addView(content);
for(String paragraph:text.split("\n\n")){
paragraph=paragraph.trim();if(paragraph.isEmpty()||paragraph.equals("---"))continue;
boolean heading=paragraph.startsWith("#"),date=paragraph.startsWith("更新日期:");
String value=heading?paragraph.replaceFirst("^#+\\s*",""):paragraph.replace("**","");
TextView label=ui.text(value,date?12:16,heading);label.setTextIsSelectable(true);label.setLineSpacing(ui.dp(4),1);
if(date)label.setTextColor(SECONDARY);
LinearLayout.LayoutParams spacing=new LinearLayout.LayoutParams(-1,-2);spacing.bottomMargin=ui.dp(14);content.addView(label,spacing);
}
return scroll;
}
}
@@ -0,0 +1,85 @@
package cn.crossdesk.mobile;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
/** Main-thread presence cache, with the same refresh and expiry intervals as iOS. */
final class RecentConnectionPresence {
private static final long REFRESH_INTERVAL=30_000, MAX_AGE=60_000;
private final Set<String> watched=new LinkedHashSet<>();
private final Map<String,Boolean> online=new HashMap<>();
private final Map<String,Long> updatedAt=new HashMap<>();
private boolean connected,awaitingSnapshot=true;
private long lastRefresh;
Consumer<JSONArray> sender=ids->{};
Runnable changed=()->{};
void watch(JSONArray records,long now){
Set<String> next=new LinkedHashSet<>();
for(int i=0;i<records.length();i++){
JSONObject record=records.optJSONObject(i);
if(record!=null&&!record.optString("id").isEmpty())next.add(record.optString("id"));
}
if(watched.equals(next))return;
watched.clear();watched.addAll(next);
online.keySet().retainAll(watched);updatedAt.keySet().retainAll(watched);
refresh(now);changed.run();
}
void setConnected(boolean value,long now){
if(connected==value)return;
connected=value;online.clear();updatedAt.clear();awaitingSnapshot=true;
refresh(now);changed.run();
}
boolean isConnected(){return connected;}
boolean isOnline(String id,long now){
Long time=updatedAt.get(id);
return connected&&!awaitingSnapshot&&Boolean.TRUE.equals(online.get(id))&&time!=null&&now-time<MAX_AGE;
}
void receive(JSONObject message,long now){
if(!connected)return;
boolean snapshot="presence".equals(message.optString("type"));
Map<String,Boolean> values=new HashMap<>();
if(snapshot){
JSONArray devices=message.optJSONArray("devices");if(devices==null)return;
for(int i=0;i<devices.length();i++){JSONObject device=devices.optJSONObject(i);if(device!=null)read(device,values);}
}else{
if(!"presence_update".equals(message.optString("type"))||awaitingSnapshot)return;
read(message,values);
}
Map<String,Boolean> previous=new HashMap<>(online);
if(snapshot){online.clear();updatedAt.clear();awaitingSnapshot=false;}
for(var entry:values.entrySet()){online.put(entry.getKey(),entry.getValue());updatedAt.put(entry.getKey(),now);}
if(!previous.equals(online))changed.run();
}
private void read(JSONObject device,Map<String,Boolean> values){
Object id=device.opt("id"),value=device.opt("online");
if(id instanceof String&&watched.contains(id)&&value instanceof Boolean)values.put((String)id,(Boolean)value);
}
private void refresh(long now){
if(!connected)return;
lastRefresh=now;JSONArray ids=new JSONArray();for(String id:watched)ids.put(id);sender.accept(ids);
}
void maintain(long now){
if(!connected)return;
boolean expired=updatedAt.entrySet().removeIf(entry->{
if(now-entry.getValue()<MAX_AGE)return false;
online.remove(entry.getKey());return true;
});
if(expired)changed.run();
if(now-lastRefresh>=REFRESH_INTERVAL)refresh(now);
}
JSONArray ordered(JSONArray records,long now){
JSONArray result=new JSONArray();
// Preserve history order within each group, including when all devices are offline.
for(boolean available:new boolean[]{true,false})for(int i=0;i<records.length();i++){
JSONObject record=records.optJSONObject(i);
if(record!=null&&isOnline(record.optString("id"),now)==available)result.put(record);
}
return result;
}
}
@@ -0,0 +1,52 @@
package cn.crossdesk.mobile;
import android.content.Context;
import android.content.SharedPreferences;
import org.json.JSONArray;
import org.json.JSONObject;
/** History and encrypted passwords are isolated by server; history never contains secrets. */
final class RecentConnections {
private final SharedPreferences preferences;
private final SecretStore secrets;
private final Context context;
RecentConnections(Context context){this.context=context.getApplicationContext();preferences=context.getSharedPreferences("settings",Context.MODE_PRIVATE);secrets=new SecretStore(context);}
private String key(String server){return "recentList:"+server;}
private String credential(String server,String id){return "remote-password:"+server+":"+id;}
JSONArray list(String server){
try {
if(!preferences.contains(key(server))){
String legacy=preferences.getString("recent:"+server,"");
if(!legacy.isEmpty())return new JSONArray().put(new JSONObject().put("id",legacy).put("name",legacy));
}
return new JSONArray(preferences.getString(key(server),"[]"));
}
catch(org.json.JSONException error){return new JSONArray();}
}
boolean remembersPassword(String server,String id){
JSONArray records=list(server);
for(int i=0;i<records.length();i++){JSONObject item=records.optJSONObject(i);if(item!=null&&id.equals(item.optString("id")))return item.optBoolean("remember");}
return false;
}
String password(String server,String id)throws Exception{return secrets.get(credential(server,id));}
boolean contains(String server,String id){JSONArray all=list(server);for(int i=0;i<all.length();i++){JSONObject item=all.optJSONObject(i);if(item!=null&&id.equals(item.optString("id")))return true;}return false;}
void save(String server,String id,String name,String platform,boolean remember,String password)throws Exception{
if(remember&&password.isEmpty())throw new IllegalArgumentException("Cannot remember an empty password");
if(remember)secrets.put(credential(server,id),password);else secrets.remove(credential(server,id));
JSONObject item=new JSONObject().put("id",id).put("name",name.isEmpty()?id:name).put("platform",platform).put("remember",remember);
JSONArray result=new JSONArray().put(item),old=list(server);
for(int i=0;i<old.length();i++){JSONObject entry=old.optJSONObject(i);if(entry!=null&&!id.equals(entry.optString("id"))){if(result.length()<20)result.put(entry);else RemotePreviewStore.get(context).remove(server,entry.optString("id"));}}
preferences.edit().putString(key(server),result.toString()).apply();
}
void metadata(String server,String id,String name,String platform){
JSONArray all=list(server);
try{for(int i=0;i<all.length();i++){JSONObject item=all.optJSONObject(i);if(item!=null&&id.equals(item.optString("id"))){item.put("name",name.isEmpty()?id:name);item.put("platform",platform);}}}
catch(org.json.JSONException ignored){return;}
preferences.edit().putString(key(server),all.toString()).apply();
}
void delete(String server,String id){
JSONArray result=new JSONArray(),old=list(server);for(int i=0;i<old.length();i++){JSONObject entry=old.optJSONObject(i);if(entry!=null&&!id.equals(entry.optString("id")))result.put(entry);}
preferences.edit().putString(key(server),result.toString()).apply();secrets.remove(credential(server,id));
RemotePreviewStore.get(context).remove(server,id);
}
}
@@ -0,0 +1,54 @@
package cn.crossdesk.mobile;
/** Shared button ownership and cursor position for the video surface and mouse bar. */
final class RemoteMouseInput {
interface Sender { void send(float x, float y, int flag, int wheel); }
private final Sender sender;
private float x = .5f, y = .5f;
private boolean gestureLeft, virtualLeft, virtualRight;
private long revision;
Runnable didCancel;
float viewportWidth, viewportHeight;
RemoteMouseInput(Sender sender) { this.sender = sender; }
boolean hasVirtualButton() { return virtualLeft || virtualRight; }
long revision() { return revision; }
void move(float x, float y) {
this.x = Math.max(0, Math.min(1, x)); this.y = Math.max(0, Math.min(1, y));
send(0, 0);
}
void drag(float dx, float dy) {
if (!hasVirtualButton() || viewportWidth <= 0 || viewportHeight <= 0) return;
move(x + dx / viewportWidth, y + dy / viewportHeight);
}
void gestureLeft(boolean down) {
if (down && hasVirtualButton()) return;
if (gestureLeft == down) return;
gestureLeft = down;
send(down ? 1 : 2, 0);
}
void click(int down, int up) {
if (hasVirtualButton()) return;
send(down, 0); send(up, 0);
}
void virtualButton(boolean left, boolean down) {
if ((left ? virtualLeft : virtualRight) == down) return;
if (down) {
gestureLeft(false);
revision++;
}
if (left) virtualLeft = down; else virtualRight = down;
send(left ? (down ? 1 : 2) : (down ? 3 : 4), 0);
}
void scroll(int direction) {
if (direction != 0) send(7, direction > 0 ? 1 : -1);
}
void releaseAll() {
gestureLeft(false);
virtualButton(true, false);
virtualButton(false, false);
revision++;
if (didCancel != null) didCancel.run();
}
private void send(int flag, int wheel) { sender.send(x, y, flag, wheel); }
}
@@ -0,0 +1,62 @@
package cn.crossdesk.mobile;
import org.json.JSONObject;
import java.util.ArrayDeque;
import java.util.Locale;
/** Monotonic, thread-safe measurements; the UI samples these once a second, as on iOS. */
final class RemoteNetworkStatistics {
static final class Traffic {
final long inbound,outbound;final double loss;
Traffic(JSONObject json){inbound=json.optLong("inbound",-1);outbound=json.optLong("outbound",-1);loss=json.optDouble("loss",Double.NaN);}
}
static final class Report {
final Traffic[] traffic=new Traffic[4];final int mode;final boolean srtp;final double rtt;
Report(JSONObject json){
String[] keys={"video","audio","data","total"};
for(int i=0;i<keys.length;i++){JSONObject item=json.optJSONObject(keys[i]);traffic[i]=item==null?null:new Traffic(item);}
mode=json.optInt("mode",2);srtp=json.optBoolean("srtp");rtt=json.optDouble("rtt",Double.NaN);
}
}
static final class Snapshot {
final Report report;final int fps,width,height;final double latency,rtt;
Snapshot(Report report,int fps,int width,int height,double latency,double rtt){this.report=report;this.fps=fps;this.width=width;this.height=height;this.latency=latency;this.rtt=rtt;}
String mode(){return report==null?"—":report.mode==0?"P2P 直连":report.mode==1?"TURN 中继":"—";}
String resolution(){return width>0&&height>0?width+" × "+height:"—";}
String summary(){
String value=mode()+(width>0&&height>0?" · "+width+"×"+height:"")+" · "+bitrate(report==null||report.traffic[3]==null?-1:report.traffic[3].inbound);
if(report!=null&&report.traffic[0]!=null&&report.traffic[0].loss>0)value+=" · 丢包 "+loss(report.traffic[0].loss);return value;
}
}
private static final class Frame {
final double time,latency;Frame(double time,double latency){this.time=time;this.latency=latency;}
}
private Report report;
private double reportTime,rttTime,averageRtt=Double.NaN;
private long lastFrameId;
private int width,height;
private final ArrayDeque<Frame> frames=new ArrayDeque<>();
static double now(){return System.nanoTime()/1_000_000_000.0;}
synchronized void receive(Report value,double now){
report=value;reportTime=now;
if(!Double.isFinite(value.rtt)||value.rtt<0||value.rtt>2000)return;
averageRtt=Double.isFinite(averageRtt)&&now-rttTime<3?averageRtt+.25*(value.rtt-averageRtt):value.rtt;rttTime=now;
}
synchronized void frame(long id,double latency,int width,int height,double now){
if(id<=lastFrameId||width<=0||height<=0)return;lastFrameId=id;this.width=width;this.height=height;
// Native code validates clock calibration before adding local decode/render waits.
// A valid but slow frame must not disappear just because its delay exceeds 5 s.
prune(now);frames.addLast(new Frame(now,Double.isFinite(latency)&&latency>=0?latency:Double.NaN));
while(frames.size()>240)frames.removeFirst();
}
synchronized void resetVideo(){frames.clear();width=height=0;}
synchronized Snapshot snapshot(double now){
prune(now);double total=0;int count=0;
for(Frame frame:frames)if(Double.isFinite(frame.latency)){total+=frame.latency;count++;}
return new Snapshot(now-reportTime<3?report:null,frames.size(),width,height,count==0?Double.NaN:total/count,now-rttTime<3?averageRtt:Double.NaN);
}
private void prune(double now){while(!frames.isEmpty()&&now-frames.peekFirst().time>=1)frames.removeFirst();}
static String bitrate(long value){return value<0?"—":value>=1_000_000?String.format(Locale.ROOT,"%.1f Mbps",value/1_000_000.0):value>=1000?String.format(Locale.ROOT,"%.0f Kbps",value/1000.0):value+" bps";}
static String loss(double value){return Double.isFinite(value)&&value>=0?String.format(Locale.ROOT,"%.1f%%",value*100):"—";}
static String latency(double value){return !Double.isFinite(value)||value<0?"—":value<1?"<1 ms":String.format(Locale.ROOT,"%.0f ms",value);}
}
@@ -0,0 +1,39 @@
package cn.crossdesk.mobile;
import android.app.PictureInPictureParams;
import android.graphics.Rect;
import android.os.Build;
import android.util.Rational;
/** Builds platform PiP parameters only for a live, visible desktop video. */
final class RemotePictureInPicture {
private boolean connected, choosingDocument;
private int width, height;
void connected() { connected = true; }
void videoSize(int width, int height) { this.width = width; this.height = height; }
void choosingDocument(boolean value) { choosingDocument = value; }
void clearVideo() { width = height = 0; }
void disconnect() { connected = choosingDocument = false; clearVideo(); }
boolean canEnter() { return connected && !choosingDocument && width > 0 && height > 0; }
PictureInPictureParams parameters(Rect source) {
PictureInPictureParams.Builder builder = new PictureInPictureParams.Builder()
.setAspectRatio(aspectRatio(width, height));
if (source != null && !source.isEmpty()) builder.setSourceRectHint(source);
if (Build.VERSION.SDK_INT >= 31) {
builder.setAutoEnterEnabled(canEnter()).setSeamlessResizeEnabled(true);
}
return builder.build();
}
static Rational aspectRatio(int width, int height) {
if (width <= 0 || height <= 0) return new Rational(16, 9);
// Android's standard PiP accepts only 1/2.39 through 2.39. Keep
// ultrawide and portrait desktops valid, with letterboxing in the view.
if ((long) width * 100 > (long) height * 239) return new Rational(239, 100);
if ((long) height * 100 > (long) width * 239) return new Rational(100, 239);
return new Rational(width, height);
}
}
@@ -0,0 +1,163 @@
package cn.crossdesk.mobile;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Looper;
import android.util.AtomicFile;
import org.json.JSONArray;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.security.MessageDigest;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.Consumer;
/** Process-wide, serialized preview I/O. Clears invalidate even captures not yet queued for saving. */
final class RemotePreviewStore {
static final String OPTION="saveRemotePreviews";
static final int WIDTH=640,HEIGHT=360;
private static RemotePreviewStore instance;
static synchronized RemotePreviewStore get(Context context){
if(instance==null){
Context app=context.getApplicationContext();
instance=new RemotePreviewStore(new File(app.getNoBackupFilesDir(),"RecentConnectionThumbnails"),
app.getSharedPreferences("settings",Context.MODE_PRIVATE),app.getSharedPreferences("remote-previews",Context.MODE_PRIVATE));
instance.enforceConsent();
}
return instance;
}
static final class Capture {
final String key;final long generation,version;
private Capture(String key,long generation,long version){this.key=key;this.generation=generation;this.version=version;}
}
final File directory;
final ExecutorService io=Executors.newSingleThreadExecutor(r->new Thread(r,"CrossDesk previews"));
private final Handler main=new Handler(Looper.getMainLooper());
private final SharedPreferences options,index;
private final Set<String> files=new HashSet<>();
private final Map<String,Long> versions=new HashMap<>();
private final Set<Runnable> listeners=new CopyOnWriteArraySet<>();
private long generation;
volatile boolean cleaning;
volatile String cleanupError="";
RemotePreviewStore(File directory,SharedPreferences options,SharedPreferences index){
this.directory=directory;this.options=options;this.index=index;
for(String key:index.getStringSet("files",Collections.emptySet()))if(key.matches("[a-f0-9]{64}"))files.add(key);
}
boolean enabled(){return options.getBoolean("networkConsent",false)&&options.getBoolean(OPTION,false);}
void addListener(Runnable listener){listeners.add(listener);}
void removeListener(Runnable listener){listeners.remove(listener);}
private void changed(){main.post(()->{for(Runnable listener:listeners)listener.run();});}
synchronized void enforceConsent(){
if(!options.getBoolean("networkConsent",false))options.edit().putBoolean(OPTION,false).apply();
if(!enabled()&&!cleaning)clear();
}
void setEnabled(boolean enabled){
options.edit().putBoolean(OPTION,enabled&&options.getBoolean("networkConsent",false)).apply();
if(!enabled())clear();else changed();
}
synchronized Capture begin(String server,String id){
if(!enabled()||cleaning||id.isEmpty())return null;
String key=key(server,id);long version=versions.getOrDefault(key,0L)+1;versions.put(key,version);
return new Capture(key,generation,version);
}
synchronized boolean current(Capture capture){
return capture!=null&&enabled()&&!cleaning&&capture.generation==generation&&
capture.version==versions.getOrDefault(capture.key,0L);
}
/** Takes ownership of the small bitmap; JPEG compression and writes never run on the UI thread. */
void save(Capture capture,Bitmap bitmap){
io.execute(()->{
boolean saved=false;
try{
if(current(capture)&&bitmap.getWidth()==WIDTH&&bitmap.getHeight()==HEIGHT)saved=write(capture.key,bitmap);
}finally{bitmap.recycle();}
synchronized(this){
if(!saved||!current(capture))return;
Set<String> next=new HashSet<>(files);next.add(capture.key);
if(!index.edit().putStringSet("files",next).commit())return;
files.add(capture.key);
}
changed();
});
}
private boolean write(String key,Bitmap bitmap){
AtomicFile file=new AtomicFile(new File(directory,key+".jpg"));FileOutputStream output=null;
try{
ByteArrayOutputStream encoded=new ByteArrayOutputStream();
if(!bitmap.compress(Bitmap.CompressFormat.JPEG,78,encoded))return false;
byte[] bytes=encoded.toByteArray();
if(!directory.isDirectory()&&!directory.mkdirs())return false;
output=file.startWrite();output.write(bytes);
output.getFD().sync();file.finishWrite(output);output=null;
return Arrays.equals(bytes,file.readFully());
}catch(IOException|RuntimeException error){if(output!=null)file.failWrite(output);return false;}
}
void load(String server,String id,Consumer<Bitmap> receive){
final Capture read;
synchronized(this){
String key=key(server,id);
if(!enabled()||cleaning||!files.contains(key)){main.post(()->receive.accept(null));return;}
read=new Capture(key,generation,versions.getOrDefault(key,0L));
}
io.execute(()->{
Bitmap bitmap=null;
if(current(read)){
File file=new File(directory,read.key+".jpg");
if(file.isFile()&&file.length()<=2*1024*1024){
BitmapFactory.Options bounds=new BitmapFactory.Options();bounds.inJustDecodeBounds=true;
BitmapFactory.decodeFile(file.getAbsolutePath(),bounds);
if(bounds.outWidth==WIDTH&&bounds.outHeight==HEIGHT)bitmap=BitmapFactory.decodeFile(file.getAbsolutePath());
}
}
Bitmap image=bitmap;
main.post(()->{
boolean valid;synchronized(this){valid=current(read)&&files.contains(read.key);}
if(valid)receive.accept(image);else if(image!=null)image.recycle();
});
});
}
synchronized void remove(String server,String id){
String key=key(server,id);versions.put(key,versions.getOrDefault(key,0L)+1);files.remove(key);
io.execute(()->{
new AtomicFile(new File(directory,key+".jpg")).delete();
synchronized(this){
boolean saved=index.edit().putStringSet("files",new HashSet<>(files)).commit();
if(!saved||new File(directory,key+".jpg").exists())cleanupError="部分预览图未能清除,请重试。";
}
changed();
});changed();
}
synchronized void clear(){
final long epoch=++generation;files.clear();cleaning=true;cleanupError="";changed();
io.execute(()->{
boolean success=index.edit().clear().commit();
try{deleteTree(directory);}catch(IOException error){success=false;}
synchronized(this){
if(epoch!=generation)return;
cleaning=false;cleanupError=success?"":"部分预览图未能清除,请重试。";
}
changed();
});
}
private static void deleteTree(File file)throws IOException{
if(!file.exists())return;
if(file.isDirectory()&&!Files.isSymbolicLink(file.toPath())){
File[] children=file.listFiles();if(children==null)throw new IOException("Cannot list previews");
boolean failed=false;for(File child:children)try{deleteTree(child);}catch(IOException error){failed=true;}
if(failed)throw new IOException("Cannot clear all previews");
}
if(!file.delete())throw new IOException("Cannot delete preview");
}
private static String key(String server,String id){
try{
byte[] bytes=new JSONArray().put(server).put(id).toString().getBytes(StandardCharsets.UTF_8);
byte[] hash=MessageDigest.getInstance("SHA-256").digest(bytes);StringBuilder key=new StringBuilder();
for(byte b:hash)key.append(String.format(Locale.ROOT,"%02x",b&255));return key.toString();
}catch(Exception error){throw new IllegalStateException(error);}
}
}
@@ -0,0 +1,109 @@
package cn.crossdesk.mobile;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ServiceInfo;
import android.os.Build;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;
/** Foreground fallback for a user-started RTC session when native PiP is unavailable. */
public final class RemoteSessionService extends Service {
private static final String CHANNEL = "remote_connection";
private static final String STOP = "cn.crossdesk.mobile.STOP_REMOTE_SESSION";
private static final int NOTIFICATION = 41;
private static BackgroundSession current;
private static RemoteSessionService running;
private BackgroundSession owned;
private PowerManager.WakeLock wakeLock;
static BackgroundSession current() { return current; }
static boolean retain(Context context, BackgroundSession value) {
if (value.ended || value.session.isClosed()) return false;
if (current == value) return true;
if (current != null) return false;
current = value;
try {
context.startForegroundService(new Intent(context, RemoteSessionService.class).putExtra("session", value.token));
return true;
} catch (RuntimeException error) {
current = null;
Log.w("CrossDesk", "Background session service could not start", error);
return false;
}
}
static void release(Context context, BackgroundSession value) {
if (current != value) return;
current = null;
if (running != null) running.releaseWakeLock();
context.stopService(new Intent(context, RemoteSessionService.class));
}
static void refresh(BackgroundSession value) {
if (current == value && running != null && running.owned == value) running.update();
}
@Override public IBinder onBind(Intent intent) { return null; }
@Override public void onCreate() {
super.onCreate(); running = this;
getSystemService(NotificationManager.class).createNotificationChannel(
new NotificationChannel(CHANNEL, "远程连接", NotificationManager.IMPORTANCE_LOW));
wakeLock = getSystemService(PowerManager.class).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "CrossDesk:RemoteSession");
wakeLock.setReferenceCounted(false);
}
@Override public int onStartCommand(Intent intent, int flags, int startId) {
BackgroundSession value = current;
if (value == null || value.ended || value.session.isClosed()) { stopSelf(startId); return START_NOT_STICKY; }
if (intent == null || !value.token.equals(intent.getStringExtra("session"))) return START_NOT_STICKY;
owned = value;
if (STOP.equals(intent.getAction())) { value.finish("已从通知断开远程连接"); return START_NOT_STICKY; }
try {
Notification notification = notification();
if (Build.VERSION.SDK_INT >= 34) startForeground(NOTIFICATION, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE);
else startForeground(NOTIFICATION, notification);
update();
} catch (RuntimeException error) {
Log.w("CrossDesk", "Background session foreground promotion failed", error);
value.finish("后台保活未能启动,请保持应用在前台后重新连接");
}
return START_NOT_STICKY;
}
private Notification notification() {
PendingIntent open = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP),
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Intent stopIntent = new Intent(this, RemoteSessionService.class).setAction(STOP)
.setData(android.net.Uri.parse("crossdesk-session:" + owned.token)).putExtra("session", owned.token);
PendingIntent stop = PendingIntent.getService(this, 1, stopIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
return new Notification.Builder(this, CHANNEL).setSmallIcon(R.drawable.ic_remote_session)
.setContentTitle("CrossDesk 远程连接")
.setContentText(owned.background ? "后台保持连接,点按返回远程桌面" : "已启用后台保活,切换应用可继续保持连接")
.setContentIntent(open).setOngoing(true).setOnlyAlertOnce(true).setShowWhen(false)
.setCategory(Notification.CATEGORY_SERVICE).setVisibility(Notification.VISIBILITY_PRIVATE)
.addAction(new Notification.Action.Builder(null, "返回", open).build())
.addAction(new Notification.Action.Builder(null, "断开", stop).build()).build();
}
@android.annotation.SuppressLint("WakelockTimeout") // Released on foreground return, disconnect, task removal and service destruction.
private void update() {
if (owned == null || owned.ended) return;
if (owned.background) { if (!wakeLock.isHeld()) wakeLock.acquire(); }
else releaseWakeLock();
getSystemService(NotificationManager.class).notify(NOTIFICATION, notification());
}
private void releaseWakeLock() { if (wakeLock != null && wakeLock.isHeld()) wakeLock.release(); }
@Override public void onTaskRemoved(Intent rootIntent) {
if (current == owned && owned != null) owned.finish("远程任务已关闭");
stopSelf();
}
@Override public void onDestroy() {
if (running == this) running = null;
releaseWakeLock(); stopForeground(STOP_FOREGROUND_REMOVE);
BackgroundSession value = owned;
if (current == value && value != null) { current = null; value.finish("后台连接服务已停止,请重新连接"); }
super.onDestroy();
}
}
@@ -0,0 +1,130 @@
package cn.crossdesk.mobile;
import android.os.Handler;
import android.os.Looper;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.function.Consumer;
import javax.net.ssl.HttpsURLConnection;
/** One check per desktop session. State and completion callbacks run on main. */
final class RemoteVersionCheck {
static final String NOTICE = "被控端版本过低,请升级到最新版本。";
static final String RELEASE_URL = "https://version.crossdesk.cn/version.json";
interface Cancellation { void cancel(); }
interface Fetcher { Cancellation fetch(Consumer<byte[]> completion); }
private final Fetcher fetcher;
private final Runnable notify;
private boolean connected, receivedHostInfo, attempted;
private String version = "";
private long generation;
private Cancellation request;
RemoteVersionCheck(Runnable notify) { this(ReleaseRequest::start, notify); }
RemoteVersionCheck(Fetcher fetcher, Runnable notify) {
this.fetcher = fetcher;
this.notify = notify;
}
void connected() { connected = true; check(); }
void hostInfo(JSONObject info) {
receivedHostInfo = true;
Object value = info.opt("app_version");
version = value instanceof String && NativeSession.nValidAppVersion((String)value)
? (String)value : "";
check();
}
private void check() {
if (!connected || !receivedHostInfo || attempted) return;
attempted = true;
// iOS treats missing/invalid peer versions as legacy, without a request.
if (version.isEmpty()) { notify.run(); return; }
long currentGeneration = generation;
String currentVersion = version;
request = fetcher.fetch(data -> {
if (generation != currentGeneration || !connected) return;
request = null;
if (data != null && NativeSession.nHasAppUpdate(currentVersion, data)) notify.run();
});
}
void reset() {
++generation;
connected = receivedHostInfo = attempted = false;
version = "";
if (request != null) request.cancel();
request = null;
}
static final class ReleaseRequest implements Cancellation, Runnable {
private static final int MAX_BYTES = 256 * 1024;
private final Handler main = new Handler(Looper.getMainLooper());
private final Consumer<byte[]> completion;
private final Runnable timeout = () -> finish(null);
private volatile boolean cancelled;
private HttpsURLConnection connection;
private ReleaseRequest(Consumer<byte[]> completion) { this.completion = completion; }
static Cancellation start(Consumer<byte[]> completion) {
ReleaseRequest request = new ReleaseRequest(completion);
request.main.postDelayed(request.timeout, 15000);
Thread worker = new Thread(request, "CrossDesk version check");
worker.setDaemon(true);
worker.start();
return request;
}
@Override public void run() {
byte[] result = null;
HttpsURLConnection opened = null;
try {
// Fetch public metadata only: no peer identity, version or credentials.
opened = (HttpsURLConnection)new URL(RELEASE_URL).openConnection();
synchronized (this) {
if (cancelled) return;
connection = opened;
}
opened.setConnectTimeout(5000);
opened.setReadTimeout(10000);
opened.setUseCaches(false);
opened.setInstanceFollowRedirects(false);
if (opened.getResponseCode() == 200 && opened.getContentLengthLong() <= MAX_BYTES) {
try (InputStream input = opened.getInputStream();
ByteArrayOutputStream output = new ByteArrayOutputStream()) {
byte[] buffer = new byte[4096];
int count;
while (!cancelled && (count = input.read(buffer)) != -1) {
if (output.size() + count > MAX_BYTES) return;
output.write(buffer, 0, count);
}
if (!cancelled) result = output.toByteArray();
}
}
} catch (Exception ignored) {
// A failed check is silent, as on iOS; it never interrupts control.
} finally {
if (opened != null) opened.disconnect();
byte[] response = result;
main.post(() -> finish(response));
}
}
private void finish(byte[] response) {
if (cancelled) return;
cancel();
completion.accept(response);
}
@Override public void cancel() {
HttpsURLConnection active;
synchronized (this) { cancelled = true; active = connection; connection = null; }
main.removeCallbacks(timeout);
if (active != null) active.disconnect();
}
}
}
@@ -0,0 +1,58 @@
package cn.crossdesk.mobile;
import org.json.JSONObject;
/** Same request/acknowledgement and rollback rules as the iOS controller. */
final class RemoteVideoSettings {
static final String[] PREFERENCES={"帧率优先","画质优先","平衡"};
static final String[] DETAILS={
"优先保持画面流畅,带宽或编码压力较大时会更积极地降低分辨率。",
"始终保持较高分辨率,带宽不足时通过降低帧率来保证画面清晰度。",
"兼顾清晰度和流畅度,只在持续压力下逐步降低分辨率。"};
static final class Values {
final int quality,frameRate,preference;
Values(int quality,int frameRate,int preference){this.quality=quality;this.frameRate=frameRate;this.preference=preference;}
boolean valid(){return quality>=0&&quality<=2&&(frameRate==30||frameRate==60)&&preference>=0&&preference<=2;}
JSONObject status(long requestId,boolean accepted){
try{return new JSONObject().put("type",12).put("video_settings",new JSONObject().put("quality",quality).put("frame_rate",frameRate).put("preference",preference).put("request_id",requestId).put("accepted",accepted));}
catch(org.json.JSONException impossible){throw new IllegalStateException(impossible);}
}
}
boolean supported,pending,failed;
Values selection,applied;
long requestId,appliedRequestId;
RemoteVideoSettings(int preference){this(preference,1920);}
RemoteVideoSettings(int preference,int displayLongEdge){
// Start within common mobile decoder limits. Hardware availability and
// maximum resolution vary, and AV1 may still need software fallback.
// Small screens need no more than 720p; larger screens start at 1080p.
// All quality/frame-rate choices remain available for manual adjustment.
selection=applied=new Values(displayLongEdge>0&&displayLongEdge<=1280?0:1,30,preference>=0&&preference<=2?preference:1);
}
void setSupported(boolean value){supported=value;if(!value){selection=applied;pending=false;failed=false;}}
long begin(Values value){
if(!supported||!value.valid())return -1;
requestId=(requestId+1)&0xffffffffL;selection=value;pending=true;failed=false;return requestId;
}
void receive(Values value,long responseId,boolean accepted){
if(!supported||!value.valid()||responseId<0||responseId>0xffffffffL||(int)(requestId-responseId)<0)return;
if(accepted&&(int)(responseId-appliedRequestId)>=0){applied=value;appliedRequestId=responseId;}
if(responseId!=requestId)return;
pending=false;failed=!accepted;selection=applied;
}
void receive(JSONObject message){
try{
if(message.getInt("type")!=12)return;
JSONObject settings=message.getJSONObject("video_settings");
for(String key:new String[]{"quality","frame_rate","preference","request_id"}){
Object value=settings.get(key);if(!(value instanceof Integer)&&!(value instanceof Long))return;
}
long quality=settings.getLong("quality"),rate=settings.getLong("frame_rate"),preference=settings.getLong("preference");
if(quality<0||quality>2||(rate!=30&&rate!=60)||preference<0||preference>2)return;
Object accepted=settings.opt("accepted");if(accepted!=null&&!(accepted instanceof Boolean))return;
receive(new Values((int)quality,(int)rate,(int)preference),settings.getLong("request_id"),Boolean.TRUE.equals(accepted));
}catch(org.json.JSONException ignored){ }
}
void expire(long expiredId){if(pending&&expiredId==requestId){selection=applied;pending=false;failed=true;}}
String feedback(){return !supported?"连接建立后可调整,需被控端支持。":failed?"调整失败,请重试。":"";}
}
@@ -0,0 +1,262 @@
package cn.crossdesk.mobile;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Looper;
import android.view.PixelCopy;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.FrameLayout;
@android.annotation.SuppressLint("ViewConstructor") // Constructed only with a live session, never from XML.
final class RemoteVideoView extends FrameLayout implements SurfaceHolder.Callback {
private final SurfaceView video;
private final Cursor cursor;
private final NativeSession session;
final RemoteMouseInput mouseInput;
private final GestureDetector gestures;
private final ScaleGestureDetector scales;
private final RemoteViewport viewport = new RemoteViewport();
private final RemoteViewport pictureInPictureViewport = new RemoteViewport();
private boolean pictureInPicture;
private int frameWidth = 16, frameHeight = 9;
private float x = .5f, y = .5f, scrollY;
private boolean dragging, twoFinger, relative, viewportGesture, viewportPanActive;
private float lastX,lastY,twoFingerX,twoFingerY;
private long touchRevision;
private boolean suppressPointerGesture;
void setRelative(boolean value) { releaseMouse(); relative=value; }
void setPictureInPicture(boolean value) {
if(pictureInPicture==value)return;
releaseMouse();pictureInPicture=value;cursor.setVisibility(value?GONE:VISIBLE);fit();
}
Rect pictureInPictureBounds() {
Rect bounds=new Rect();video.getGlobalVisibleRect(bounds);return bounds;
}
void releaseMouse() { mouseInput.releaseAll(); dragging=false; suppressPointerGesture=true; }
private boolean suppressPointerGesture() {
return suppressPointerGesture || mouseInput.hasVirtualButton() || touchRevision != mouseInput.revision();
}
RemoteVideoView(Context context, NativeSession session) {
super(context); this.session = session;
mouseInput = new RemoteMouseInput(this::sendMouse);
setBackgroundColor(Color.BLACK);
video = new SurfaceView(context); video.getHolder().addCallback(this);
addView(video, new LayoutParams(1, 1, android.view.Gravity.CENTER));
cursor = new Cursor(context);
// Keep input in container coordinates so transforms never move its hit area.
addView(cursor, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
gestures = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override public boolean onDown(MotionEvent e) { return point(e); }
@Override public boolean onSingleTapUp(MotionEvent e) {
if (!twoFinger && !suppressPointerGesture() && point(e)) cursor.performClick(); return true;
}
@Override public void onLongPress(MotionEvent e) { if (!twoFinger && !dragging && !suppressPointerGesture() && point(e)) click(3, 4); }
@Override public boolean onScroll(MotionEvent first, MotionEvent current, float dx, float dy) {
if (twoFinger) return true;
if (!relative && !dragging && !suppressPointerGesture()) {
if (!point(first)) return true;
mouseInput.gestureLeft(true); dragging = true;
}
point(current); return true;
}
});
// Let the remote desktop detect double-clicks; the default listener consumes the second tap.
gestures.setOnDoubleTapListener(null);
scales = new ScaleGestureDetector(context, new ScaleGestureDetector.SimpleOnScaleGestureListener() {
@Override public boolean onScaleBegin(ScaleGestureDetector detector) {
if (mouseInput.hasVirtualButton()) return false;
if (!viewport.contains(detector.getFocusX(), detector.getFocusY())) return false;
viewportGesture = true;
viewportPanActive = true;
return true;
}
@Override public boolean onScale(ScaleGestureDetector detector) {
viewport.zoomBy(detector.getScaleFactor(), detector.getFocusX(), detector.getFocusY());
applyViewport();
return true;
}
@Override public void onScaleEnd(ScaleGestureDetector detector) {
viewport.finishGesture();
applyViewport();
}
});
scales.setQuickScaleEnabled(false);
scales.setStylusScaleEnabled(false);
cursor.setOnGenericMotionListener((v, event) -> {
if (!point(event)) return true;
if (event.getActionMasked() == MotionEvent.ACTION_SCROLL) {
float delta = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
if (delta != 0) session.pointer(x, y, 7, delta > 0 ? 1 : -1);
}
return true;
});
setContentDescription("远程桌面:轻触点击,拖动移动,长按右键,双指捏合缩放,放大后双指拖动画面,原始比例下双指上下滑动滚动");
}
void videoSize(int width, int height) {
if (width <= 0 || height <= 0) return;
frameWidth = width; frameHeight = height; fit();
}
void resetViewport() { releaseMouse(); viewport.reset(); applyViewport(); }
static Rect previewCrop(int width,int height){
int w=width,h=height;
if((long)width*RemotePreviewStore.HEIGHT>(long)height*RemotePreviewStore.WIDTH)w=Math.max(1,height*RemotePreviewStore.WIDTH/RemotePreviewStore.HEIGHT);
else h=Math.max(1,width*RemotePreviewStore.HEIGHT/RemotePreviewStore.WIDTH);
return new Rect((width-w)/2,(height-h)/2,(width+w)/2,(height+h)/2);
}
void capturePreview(java.util.function.Consumer<Bitmap> completion){
// Copy only the decoded-video Surface, excluding cursor, controls, keyboard and black margins.
if(!isAttachedToWindow()||!video.getHolder().getSurface().isValid()){completion.accept(null);return;}
Bitmap image=Bitmap.createBitmap(RemotePreviewStore.WIDTH,RemotePreviewStore.HEIGHT,Bitmap.Config.ARGB_8888);
try{
PixelCopy.request(video.getHolder().getSurface(),previewCrop(frameWidth,frameHeight),image,result->{
if(result==PixelCopy.SUCCESS)completion.accept(image);else{image.recycle();completion.accept(null);}
},new Handler(Looper.getMainLooper()));
}catch(IllegalArgumentException error){image.recycle();completion.accept(null);}
}
private void fit() {
if (getWidth() == 0 || getHeight() == 0) return;
RemoteViewport active=pictureInPicture?pictureInPictureViewport:viewport;
active.fit(getWidth(), getHeight(), frameWidth, frameHeight);
video.setLayoutParams(new LayoutParams(active.baseWidth(),active.baseHeight(),android.view.Gravity.CENTER));
applyViewport();
}
private void applyViewport() {
// Transform the existing Surface without enlarging its decoder buffers.
RemoteViewport active=pictureInPicture?pictureInPictureViewport:viewport;
video.setScaleX(active.scale()); video.setScaleY(active.scale());
video.setTranslationX(active.offsetX()); video.setTranslationY(active.offsetY());
mouseInput.viewportWidth = active.width(); mouseInput.viewportHeight = active.height();
cursor.invalidate();
}
private void sendMouse(float x, float y, int flag, int wheel) {
this.x = x; this.y = y;
session.pointer(x,y,flag,wheel);
cursor.invalidate();
}
@Override protected void onSizeChanged(int w,int h,int oldw,int oldh) { post(this::fit); }
private boolean point(MotionEvent e) {
boolean touchpad = relative && e.getToolType(0) != MotionEvent.TOOL_TYPE_MOUSE;
float px=e.getX(),py=e.getY();
if (!touchpad && !viewport.contains(px,py)) return false;
if(touchpad){
if(e.getActionMasked()==MotionEvent.ACTION_MOVE){
x=Math.max(0,Math.min(1,x+(px-lastX)/Math.max(1,viewport.width())));
y=Math.max(0,Math.min(1,y+(py-lastY)/Math.max(1,viewport.height())));
}
}else{
x=viewport.normalizedX(px);
y=viewport.normalizedY(py);
}
lastX=px;lastY=py;
mouseInput.move(x,y); cursor.invalidate();
return true;
}
private void click(int down, int up) { mouseInput.click(down,up); }
private boolean touch(MotionEvent e) {
int action = e.getActionMasked();
if (action == MotionEvent.ACTION_DOWN) {
twoFinger = viewportGesture = viewportPanActive = false;
touchRevision = mouseInput.revision();
suppressPointerGesture = mouseInput.hasVirtualButton();
}
if (action == MotionEvent.ACTION_POINTER_DOWN) {
if (dragging) { mouseInput.gestureLeft(false); dragging = false; }
twoFinger = true;
twoFingerX = focus(e,true,-1); twoFingerY = scrollY = focus(e,false,-1);
viewportPanActive = viewport.isZoomed() && viewport.contains(twoFingerX,twoFingerY);
MotionEvent cancel = MotionEvent.obtain(e); cancel.setAction(MotionEvent.ACTION_CANCEL);
gestures.onTouchEvent(cancel); cancel.recycle();
}
scales.onTouchEvent(e);
if (twoFinger && action == MotionEvent.ACTION_MOVE && e.getPointerCount() >= 2) {
if (mouseInput.hasVirtualButton()) return true;
float focusX = focus(e,true,-1), focusY = focus(e,false,-1);
if (viewport.isZoomed() || viewportGesture || scales.isInProgress()) {
viewportGesture = true;
if (!viewportPanActive) viewportPanActive = viewport.contains(focusX,focusY);
if (viewportPanActive) {
viewport.panBy(focusX-twoFingerX,focusY-twoFingerY);
applyViewport();
}
} else if (viewport.contains(focusX,focusY)) {
float delta = focusY - scrollY;
if (Math.abs(delta) > 16 * getResources().getDisplayMetrics().density) {
session.pointer(x,y,7,delta > 0 ? 1 : -1); scrollY = focusY;
}
}
twoFingerX = focusX; twoFingerY = focusY;
} else if (!twoFinger) {
if ((e.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0 && action == MotionEvent.ACTION_DOWN) {
if (point(e)) click(3,4); return true;
}
gestures.onTouchEvent(e);
}
if (action == MotionEvent.ACTION_POINTER_UP) {
// Rebase when a finger lifts; never resume a click/drag until all lift.
twoFingerX = focus(e,true,e.getActionIndex());
twoFingerY = scrollY = focus(e,false,e.getActionIndex());
}
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
if (dragging) mouseInput.gestureLeft(false);
dragging = false;
viewport.finishGesture(); applyViewport();
viewportPanActive = false;
}
return true;
}
private static float focus(MotionEvent event, boolean horizontal, int excludedIndex) {
float total = 0; int count = 0;
for (int i=0;i<event.getPointerCount();i++) {
if (i==excludedIndex) continue;
total += horizontal ? event.getX(i) : event.getY(i); count++;
}
return total / Math.max(1,count);
}
@Override public boolean performClick() { super.performClick(); return true; }
@Override public void surfaceCreated(SurfaceHolder holder) { session.surface(holder.getSurface()); }
@Override public void surfaceChanged(SurfaceHolder holder,int format,int width,int height) { }
@Override public void surfaceDestroyed(SurfaceHolder holder) { releaseMouse(); session.surface(null); }
@Override protected void onDetachedFromWindow() { releaseMouse(); super.onDetachedFromWindow(); }
private final class Cursor extends View {
private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
private final Path arrow = new Path();
private final float arrowWidth = 12, arrowHeight = 15;
Cursor(Context context) {
super(context); setClickable(true); setContentDescription("远程桌面触控区域");
// Match the iOS RemoteCursorArrowShape in density-independent units.
arrow.moveTo(arrowWidth*.08f,arrowHeight*.04f);
arrow.lineTo(arrowWidth*.08f,arrowHeight*.78f);
arrow.lineTo(arrowWidth*.34f,arrowHeight*.60f);
arrow.lineTo(arrowWidth*.55f,arrowHeight*.94f);
arrow.lineTo(arrowWidth*.73f,arrowHeight*.84f);
arrow.lineTo(arrowWidth*.52f,arrowHeight*.51f);
arrow.lineTo(arrowWidth*.88f,arrowHeight*.49f);
arrow.close();
}
// GestureDetector calls performClick only after resolving tap vs drag/long press.
@android.annotation.SuppressLint("ClickableViewAccessibility")
@Override public boolean onTouchEvent(MotionEvent event) { return touch(event); }
@Override public boolean performClick() { super.performClick(); click(1, 2); return true; }
@Override protected void onDraw(Canvas canvas) {
int saved=canvas.save();
canvas.translate(viewport.left()+x*viewport.width(),viewport.top()+y*viewport.height());
float density=getResources().getDisplayMetrics().density;canvas.scale(density,density);
// Anchor the arrow tip to the same normalized coordinate sent to the desktop.
canvas.translate(-arrowWidth*.08f,-arrowHeight*.04f);
paint.setStyle(Paint.Style.STROKE);paint.setStrokeWidth(1.75f);paint.setColor(Color.BLACK);canvas.drawPath(arrow,paint);
paint.setStyle(Paint.Style.FILL);paint.setColor(Color.WHITE);canvas.drawPath(arrow,paint);
canvas.restoreToCount(saved);
}
}
}
@@ -0,0 +1,74 @@
package cn.crossdesk.mobile;
/** Geometry shared by the video Surface, cursor and remote pointer input. */
final class RemoteViewport {
private static final float MAXIMUM_SCALE = 10;
private int baseWidth, baseHeight, baseLeft, baseTop;
private float scale = 1, offsetX, offsetY;
void fit(int width, int height, int videoWidth, int videoHeight) {
if (width <= 0 || height <= 0 || videoWidth <= 0 || videoHeight <= 0) return;
double fitScale = Math.min((double) width / videoWidth, (double) height / videoHeight);
baseWidth = Math.max(1, (int) (videoWidth * fitScale));
baseHeight = Math.max(1, (int) (videoHeight * fitScale));
// Match the integer positioning of Gravity.CENTER, including odd margins.
baseLeft = (width - baseWidth) / 2;
baseTop = (height - baseHeight) / 2;
constrainOffset();
}
int baseWidth() { return baseWidth; }
int baseHeight() { return baseHeight; }
float scale() { return scale; }
float offsetX() { return offsetX; }
float offsetY() { return offsetY; }
float width() { return baseWidth * scale; }
float height() { return baseHeight * scale; }
float left() { return baseLeft + baseWidth * (1 - scale) / 2 + offsetX; }
float top() { return baseTop + baseHeight * (1 - scale) / 2 + offsetY; }
boolean isZoomed() { return scale > 1.001f; }
boolean contains(float x, float y) {
return baseWidth > 0 && baseHeight > 0 &&
x >= left() && x < left() + width() && y >= top() && y < top() + height();
}
float normalizedX(float x) { return clamp((x - left()) / Math.max(1, width()), 0, 1); }
float normalizedY(float y) { return clamp((y - top()) / Math.max(1, height()), 0, 1); }
void zoomBy(float factor, float focusX, float focusY) {
if (baseWidth == 0 || baseHeight == 0 || !Float.isFinite(factor) || factor <= 0) return;
float nextScale = clamp(scale * factor, 1, MAXIMUM_SCALE);
float ratio = nextScale / scale;
float focusFromCenterX = focusX - (baseLeft + baseWidth / 2f);
float focusFromCenterY = focusY - (baseTop + baseHeight / 2f);
offsetX = focusFromCenterX - (focusFromCenterX - offsetX) * ratio;
offsetY = focusFromCenterY - (focusFromCenterY - offsetY) * ratio;
scale = nextScale;
constrainOffset();
}
void panBy(float dx, float dy) {
offsetX += dx;
offsetY += dy;
constrainOffset();
}
void finishGesture() {
if (!isZoomed()) reset();
}
void reset() { scale = 1; offsetX = offsetY = 0; }
private void constrainOffset() {
// Keep the original fitted area covered, as on iOS, even with letterboxing.
float maximumX = baseWidth * (scale - 1) / 2;
float maximumY = baseHeight * (scale - 1) / 2;
offsetX = clamp(offsetX, -maximumX, maximumX);
offsetY = clamp(offsetY, -maximumY, maximumY);
}
private static float clamp(float value, float minimum, float maximum) {
return Math.max(minimum, Math.min(maximum, value));
}
}
@@ -0,0 +1,52 @@
package cn.crossdesk.mobile;
import android.content.Context;
import android.content.SharedPreferences;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import android.util.Base64;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
/** Server-scoped credentials encrypted with a non-exportable Android Keystore key. */
final class SecretStore {
private static final String ALIAS = "crossdesk.signaling.v1";
private final SharedPreferences preferences;
SecretStore(Context context) { preferences = context.getSharedPreferences("identities", Context.MODE_PRIVATE); }
private SecretKey key() throws Exception {
KeyStore store = KeyStore.getInstance("AndroidKeyStore");
store.load(null);
if (!store.containsAlias(ALIAS)) {
KeyGenerator generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
generator.init(new KeyGenParameterSpec.Builder(ALIAS,
KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE).build());
generator.generateKey();
}
return (SecretKey) store.getKey(ALIAS, null);
}
String get(String scope) throws Exception {
String stored = preferences.getString(scope, "");
if (stored.isEmpty()) return "";
String[] parts = stored.split(":", 2);
if (parts.length != 2) throw new IllegalStateException("Invalid credential record");
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, key(), new GCMParameterSpec(128, Base64.decode(parts[0], Base64.NO_WRAP)));
cipher.updateAAD(scope.getBytes(StandardCharsets.UTF_8));
return new String(cipher.doFinal(Base64.decode(parts[1], Base64.NO_WRAP)), StandardCharsets.UTF_8);
}
void remove(String scope) { preferences.edit().remove(scope).apply(); }
void put(String scope, String credential) throws Exception {
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, key());
cipher.updateAAD(scope.getBytes(StandardCharsets.UTF_8));
String value = Base64.encodeToString(cipher.getIV(), Base64.NO_WRAP) + ":" +
Base64.encodeToString(cipher.doFinal(credential.getBytes(StandardCharsets.UTF_8)), Base64.NO_WRAP);
if (!preferences.edit().putString(scope, value).commit()) throw new IllegalStateException("Credential save failed");
}
}
@@ -0,0 +1,73 @@
package cn.crossdesk.mobile;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.view.Gravity;
import android.view.View;
import android.view.animation.PathInterpolator;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.function.IntConsumer;
/** A single sliding selection highlight, matching the iOS segmented settings pickers. */
@android.annotation.SuppressLint("ViewConstructor") // Programmatic control with labels and a change callback.
final class SegmentedControl extends LinearLayout {
private final Paint paint=new Paint(Paint.ANTI_ALIAS_FLAG);
private final RectF highlight=new RectF(), destination=new RectF();
private final float radius;
private final IntConsumer changed;
private int selected;
private ValueAnimator animator;
SegmentedControl(MobileUi ui,String[] titles,int selection,boolean enabled,IntConsumer changed){
super(ui.context);this.changed=changed;selected=Math.max(0,Math.min(titles.length-1,selection));
int inset=ui.dp(MobileUi.SEGMENT_INSET),height=ui.dp(MobileUi.SEGMENT_HEIGHT)-inset*2;
radius=height/2f;
setGravity(Gravity.CENTER_VERTICAL);setPadding(inset,inset,inset,inset);setBackground(ui.background(0xFFE9E9EF,MobileUi.SEGMENT_HEIGHT/2));paint.setColor(Color.WHITE);
for(int i=0;i<titles.length;i++){
final int index=i;TextView choice=ui.action(titles[i],MobileUi.INK,()->select(index));
choice.setTextSize(13);choice.setMinHeight(height);choice.setSelected(i==selected);choice.setEnabled(enabled);choice.setAlpha(enabled?1:.45f);
addView(choice,new LayoutParams(0,height,1));
}
}
private RectF selectedBounds(){View choice=getChildAt(selected);return new RectF(choice.getLeft(),choice.getTop(),choice.getRight(),choice.getBottom());}
private void select(int index){
if(index==selected)return;
setSelection(index);changed.accept(index);
}
void setSelection(int index){
if(index==selected)return;
selected=index;for(int i=0;i<getChildCount();i++)getChildAt(i).setSelected(i==selected);
cancelAnimation();destination.set(selectedBounds());
if(!isAttachedToWindow()||!isLaidOut()||highlight.isEmpty()||!ValueAnimator.areAnimatorsEnabled()){
highlight.set(destination);invalidate();
}else{
// Restart from the displayed position, including when the user reverses mid-animation.
RectF start=new RectF(highlight),end=new RectF(destination);ValueAnimator next=ValueAnimator.ofFloat(0,1);animator=next;
next.setDuration(200);next.setInterpolator(new PathInterpolator(.25f,.1f,.25f,1));
next.addUpdateListener(value->{
if(animator!=value)return;float fraction=(float)value.getAnimatedValue();
highlight.set(start.left+(end.left-start.left)*fraction,start.top+(end.top-start.top)*fraction,start.right+(end.right-start.right)*fraction,start.bottom+(end.bottom-start.bottom)*fraction);invalidate();
});
next.addListener(new AnimatorListenerAdapter(){@Override public void onAnimationEnd(Animator value){if(animator==value){animator=null;highlight.set(destination);invalidate();}}});next.start();
}
}
void setOptionsEnabled(boolean enabled){
for(int i=0;i<getChildCount();i++){getChildAt(i).setEnabled(enabled);getChildAt(i).setAlpha(enabled?1:.45f);}
if(!enabled){cancelAnimation();highlight.set(destination);invalidate();}
}
private void cancelAnimation(){ValueAnimator old=animator;animator=null;if(old!=null)old.cancel();}
@Override protected void onLayout(boolean changed,int left,int top,int right,int bottom){
super.onLayout(changed,left,top,right,bottom);RectF bounds=selectedBounds();
// Text below the picker can reflow without interrupting an unchanged highlight path.
if(!destination.equals(bounds)){cancelAnimation();destination.set(bounds);highlight.set(bounds);}
}
@Override protected void dispatchDraw(Canvas canvas){canvas.drawRoundRect(highlight,radius,radius,paint);super.dispatchDraw(canvas);}
@Override protected void onDetachedFromWindow(){cancelAnimation();highlight.set(destination);super.onDetachedFromWindow();}
}
@@ -0,0 +1,286 @@
package cn.crossdesk.mobile;
import android.content.Context;
import android.graphics.Color;
import android.view.*;
import android.widget.*;
import static cn.crossdesk.mobile.MobileUi.*;
/** Safe-area overlay: a draggable 54 dp orb, an adaptive menu and a floating keyboard. */
@android.annotation.SuppressLint("ViewConstructor")
final class SessionControls extends FrameLayout {
interface Actions {
void disconnect(); void display(); void clipboard(); void key(int code);
void chord(int code,int[] modifiers); void shortcut(int code); void text(String value); void mute(); void mouse();
void videoSettings(int field,int value);
void sendFile(); void saveFile(); void secureAttention();
}
private final MobileUi ui;
private final Actions actions;
private final View orb;
private final LinearLayout waiting;
private View shield;
private LinearLayout menu,keyboard;
private VirtualMouseBar mouseBar;
private FrameLayout mouseHost;
private boolean mouseVisible,pictureInPicture;
private ScrollView keyboardKeys;
private ScrollView menuScroll;
private int keyboardPreferredHeight;
private int menuColumns=3;
private TextView networkLabel,videoFeedback;
private TextView transferLabel,saveFileButton;
private String transferStatus="";
private boolean hasReceivedFile;
private String menuPage="controls";
private RemoteNetworkStatistics.Snapshot network=new RemoteNetworkStatistics().snapshot(0);
private RemoteVideoSettings settings=new RemoteVideoSettings(1);
private final java.util.List<SettingRow> settingRows=new java.util.ArrayList<>();
private TextView[][] trafficCells;
private LinearLayout[] trafficRows;
private TextView[] networkDetails;
private View encryptionLock,encryptionOpen;
private boolean muted,relative=true,shift,computerKeyboard,orbPositioned;
private final java.util.Set<Integer> modifiers=new java.util.LinkedHashSet<>();
SessionControls(Context context,MobileUi ui,Actions actions){
super(context);this.ui=ui;this.actions=actions;
// This container must remain transparent to remote touch outside its controls.
waiting=ui.column();waiting.setMinimumWidth(ui.dp(200));waiting.setGravity(Gravity.CENTER);waiting.setPadding(ui.dp(20),ui.dp(20),ui.dp(20),ui.dp(20));waiting.setBackground(ui.background(0xB0202024,14));
ProgressBar progress=new ProgressBar(context);progress.setIndeterminateTintList(android.content.res.ColorStateList.valueOf(Color.WHITE));waiting.addView(progress,ui.size(28,28));ui.gap(waiting,12);TextView message=ui.text("等待远端画面…",14,false);message.setTextColor(Color.WHITE);message.setGravity(Gravity.CENTER);waiting.addView(message);addView(waiting,new LayoutParams(-2,-2,Gravity.CENTER));
orb=ui.iconButton("display","展开远程控制菜单",()->{if(menu==null)openMenu("controls");else closeMenu();});
ImageView brand=new ImageView(context);brand.setImageResource(R.drawable.mobile_brand);brand.setScaleType(ImageView.ScaleType.CENTER_CROP);brand.setBackground(ui.background(Color.WHITE,23));brand.setClipToOutline(true);brand.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);
((FrameLayout)orb).removeAllViews();((FrameLayout)orb).addView(brand,new LayoutParams(ui.dp(46),ui.dp(46),Gravity.CENTER));
orb.setBackground(ui.background(0xFFF5F5F7,27));orb.setElevation(ui.dp(7));addView(orb,new LayoutParams(ui.dp(54),ui.dp(54)));
drag(orb,orb,()->{if(menu==null)openMenu("controls");else closeMenu();});
}
void setRelative(boolean value){relative=value;if(menu!=null&&menuPage.equals("controls"))openMenu("controls");}
void attachMouseBar(FrameLayout host, VirtualMouseBar bar) {
mouseHost=host;mouseBar=bar;
// A direct, tightly bounded sibling of the video is essential: otherwise
// an existing touch in this full-screen controls container captures the
// second finger before Android can dispatch it to the remote surface.
host.addView(bar,new FrameLayout.LayoutParams(ui.dp(140),ui.dp(48)));
bar.setVisibility(GONE);
}
void cancelMouseInput(){if(mouseBar!=null)mouseBar.cancelInput();}
void setPictureInPicture(boolean value){
pictureInPicture=value;
if(value){cancelMouseInput();closeMenu();closeKeyboard();modifiers.clear();}
setVisibility(value?GONE:VISIBLE);positionMouse();
}
private void toggleMouse(){cancelMouseInput();mouseVisible=!mouseVisible;closeMenu();positionMouse();}
private void positionMouse(){
if(mouseBar==null)return;
boolean visible=!pictureInPicture&&mouseVisible&&menu==null&&waiting.getVisibility()==GONE;
if(!visible){if(mouseBar.getVisibility()==VISIBLE)cancelMouseInput();mouseBar.setVisibility(GONE);return;}
int[] location=new int[2],hostLocation=new int[2];getLocationOnScreen(location);mouseHost.getLocationOnScreen(hostLocation);
float width=ui.dp(140),height=ui.dp(48),gap=ui.dp(6),margin=ui.dp(8);
float x=orb.getX()>=width+gap+margin?orb.getX()-gap-width:orb.getX()+orb.getWidth()+gap;
float y=orb.getY()+(orb.getHeight()-height)/2;
// When the orb is near the middle of a narrow phone, use the adjacent
// row rather than letting the two controls overlap.
if(x+width>getWidth()-margin){x=bound(orb.getX(),margin,getWidth()-width-margin);y=orb.getY()+orb.getHeight()+gap;if(y+height>getHeight()-margin)y=orb.getY()-gap-height;}
if(keyboard!=null&&x<keyboard.getX()+keyboard.getWidth()&&x+width>keyboard.getX()&&y<keyboard.getY()+keyboard.getHeight()&&y+height>keyboard.getY()){
y=keyboard.getY()-gap-height;if(y<margin)y=keyboard.getY()+keyboard.getHeight()+gap;
}
mouseBar.setX(location[0]-hostLocation[0]+bound(x,margin,getWidth()-width-margin));
mouseBar.setY(location[1]-hostLocation[1]+bound(y,margin,getHeight()-height-margin));
mouseBar.setVisibility(VISIBLE);
}
void setMuted(boolean value){muted=value;if(menu!=null&&menuPage.equals("controls"))openMenu("controls");}
void videoSize(int width,int height){waiting.setVisibility(GONE);positionMouse();}
void resetVideoStatistics(){statistics(new RemoteNetworkStatistics.Snapshot(network.report,0,0,0,Double.NaN,network.rtt));}
void statistics(RemoteNetworkStatistics.Snapshot value){network=value;renderNetwork();}
void videoSettings(RemoteVideoSettings value){settings=value;renderVideoSettings();}
void fileStatus(String status,boolean received){transferStatus=status;hasReceivedFile=received;renderFileStatus();}
private void renderFileStatus(){
if(transferLabel!=null){transferLabel.setText(transferStatus);transferLabel.setVisibility(transferStatus.isEmpty()?GONE:VISIBLE);}
if(saveFileButton!=null)saveFileButton.setVisibility(hasReceivedFile?VISIBLE:GONE);
}
private void closeMenu(){if(menu!=null){removeView(menu);menu=null;menuScroll=null;}if(shield!=null){removeView(shield);shield=null;}networkLabel=videoFeedback=transferLabel=saveFileButton=null;trafficCells=null;trafficRows=null;networkDetails=null;encryptionLock=encryptionOpen=null;settingRows.clear();orb.setContentDescription("展开远程控制菜单");positionMouse();}
private void openMenu(String page){
cancelMouseInput();
closeMenu();menuPage=page;shield=new View(getContext());shield.setOnClickListener(v->closeMenu());addView(shield,new LayoutParams(-1,-1));
menu=ui.column();menu.setPadding(ui.dp(12),ui.dp(12),ui.dp(12),ui.dp(12));ui.card(menu,18);menu.setElevation(ui.dp(12));
LinearLayout header=ui.row();
if(!page.equals("controls"))header.addView(ui.iconButton("back","返回控制栏",()->openMenu("controls")),ui.size(28,32));
LinearLayout titles=ui.column();TextView title=ui.text(page.equals("controls")?"● 已连接":page.equals("video")?"画面设置":"网络状态",14,true);titles.addView(title);
if(page.equals("controls")){ui.gap(titles,3);networkLabel=ui.text(network.summary(),10,false);networkLabel.setFontFeatureSettings("tnum");networkLabel.setTextColor(SECONDARY);titles.addView(networkLabel);}header.addView(titles,new LinearLayout.LayoutParams(0,-2,1));header.addView(ui.iconButton("close","关闭控制栏",this::closeMenu),ui.size(30,32));menu.addView(header);ui.gap(menu,9);
if(page.equals("video")){videoFeedback=ui.text("",12,false);videoFeedback.setTextColor(SECONDARY);videoFeedback.setPadding(0,0,0,ui.dp(9));menu.addView(videoFeedback);}
ScrollView scroll=new ScrollView(getContext());menuScroll=scroll;menu.addView(scroll,new LinearLayout.LayoutParams(-1,0,1));LinearLayout body=ui.column();scroll.addView(body);
if(page.equals("network")){
// Reserve the scrollbar's width plus a gap before right-aligned statistics.
scroll.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_INSET);body.setPadding(0,0,ui.dp(6),0);
}
if(page.equals("controls")){
String[] labels={"键盘",relative?"相对鼠标":"绝对鼠标",mouseVisible?"收起鼠标":"虚拟鼠标","显示器","画面设置",muted?"静音":"声音","发送文件","网络状态","Ctrl+Alt+Del","剪贴板"};
String[] icons={"keyboard","mouse","mouse","display","sliders","audio","folder","chart","lock","clipboard"};
Runnable[] clicks={()->{closeMenu();toggleKeyboard();},actions::mouse,this::toggleMouse,actions::display,()->openMenu("video"),actions::mute,actions::sendFile,()->openMenu("network"),actions::secureAttention,actions::clipboard};
menuColumns=controlColumns();
for(int row=0;row<(labels.length+menuColumns-1)/menuColumns;row++){LinearLayout line=ui.row();for(int col=0;col<menuColumns;col++){int index=row*menuColumns+col;if(index>=labels.length){View spacer=new View(getContext());LinearLayout.LayoutParams p=new LinearLayout.LayoutParams(0,ui.dp(52),1);if(col>0)p.leftMargin=ui.dp(7);line.addView(spacer,p);continue;}LinearLayout control=ui.column();control.setGravity(Gravity.CENTER);control.setBackground(ui.background(0xFFF0F0F2,10));control.addView(ui.icon(icons[index],INK),ui.size(19,19));ui.gap(control,4);TextView caption=ui.text(labels[index],10,false);caption.setSingleLine();caption.setGravity(Gravity.CENTER);control.addView(caption);control.setContentDescription(labels[index]);control.setClickable(true);control.setFocusable(true);control.setOnClickListener(v->clicks[index].run());
LinearLayout.LayoutParams p=new LinearLayout.LayoutParams(0,ui.dp(52),1);if(col>0)p.leftMargin=ui.dp(7);line.addView(control,p);
}body.addView(line);if((row+1)*menuColumns<labels.length)ui.gap(body,7);}
ui.gap(body,7);transferLabel=ui.text(transferStatus,11,false);transferLabel.setTextColor(SECONDARY);transferLabel.setAccessibilityLiveRegion(ACCESSIBILITY_LIVE_REGION_POLITE);body.addView(transferLabel);
saveFileButton=ui.action("保存收到的文件",BLUE,actions::saveFile);body.addView(saveFileButton);renderFileStatus();
}else if(page.equals("network")){
networkPage(body);
}else{
settingRows.add(new SettingRow(body,0,"画面质量",new String[]{"低","中","高"},new int[]{0,1,2}));ui.gap(body,12);
settingRows.add(new SettingRow(body,1,"画面采集帧率",new String[]{"30 fps","60 fps"},new int[]{30,60}));ui.gap(body,12);
settingRows.add(new SettingRow(body,2,"画面偏好",RemoteVideoSettings.PREFERENCES,new int[]{0,1,2}));renderVideoSettings();
}
ui.gap(menu,9);TextView disconnect=ui.action("断开连接",Color.WHITE,()->{closeMenu();closeKeyboard();actions.disconnect();});disconnect.setMinHeight(ui.dp(34));disconnect.setTextSize(14);disconnect.setBackground(ui.background(RED,8));menu.addView(disconnect,ui.size(-1,34));
addView(menu,new LayoutParams(panelWidth(getWidth()),panelHeight(getHeight())));orb.bringToFront();orb.setContentDescription("收起远程控制菜单");
positionMouse();
}
private final class SettingRow {
final int field;final int[] values;final SegmentedControl group;
SettingRow(LinearLayout body,int field,String title,String[] labels,int[] values){
this.field=field;this.values=values;
TextView label=ui.text(title,12,false);label.setTextColor(SECONDARY);body.addView(label);ui.gap(body,5);
group=new SegmentedControl(ui,labels,selectionIndex(),settings.supported,index->actions.videoSettings(field,values[index]));
group.setPadding(ui.dp(2),ui.dp(2),ui.dp(2),ui.dp(2));body.addView(group);
for(int i=0;i<labels.length;i++){
TextView button=(TextView)group.getChildAt(i);button.setTextSize(12);button.setMinHeight(ui.dp(28));button.setSingleLine();button.setContentDescription(title+","+labels[i]);
button.setLayoutParams(new LinearLayout.LayoutParams(0,ui.dp(28),1));
}
}
int selectionIndex(){int selected=field==0?settings.selection.quality:field==1?settings.selection.frameRate:settings.selection.preference;
for(int i=0;i<values.length;i++)if(values[i]==selected)return i;return 0;
}
void render(){group.setSelection(selectionIndex());group.setOptionsEnabled(settings.supported);}
}
private void renderVideoSettings(){
if(videoFeedback!=null){String feedback=settings.feedback();videoFeedback.setText(feedback);videoFeedback.setVisibility(feedback.isEmpty()?GONE:VISIBLE);}
for(SettingRow row:settingRows)row.render();
}
private void networkPage(LinearLayout body){
trafficCells=new TextView[4][3];trafficRows=new LinearLayout[4];String[] names={"视频","音频","数据","合计"};
LinearLayout heading=trafficRow(body,"",new TextView[3],false);((TextView)heading.getChildAt(1)).setText("接收");((TextView)heading.getChildAt(2)).setText("发送");((TextView)heading.getChildAt(3)).setText("丢包率");
for(int i=0;i<heading.getChildCount();i++)((TextView)heading.getChildAt(i)).setTextColor(SECONDARY);
for(int i=0;i<4;i++)trafficRows[i]=trafficRow(body,names[i],trafficCells[i],i==3);
ui.gap(body,10);ui.divider(body);ui.gap(body,10);
String[] titles={"帧率","分辨率","画面延时","连接延时(RTT)","连接方式","媒体加密"};networkDetails=new TextView[titles.length];
for(int i=0;i<titles.length;i++){LinearLayout row=ui.row();TextView title=ui.text(titles[i],12,false);title.setTextColor(SECONDARY);row.addView(title,new LinearLayout.LayoutParams(0,-2,1));
if(i==5){encryptionLock=ui.icon("lock",GREEN);encryptionOpen=ui.icon("unlock",SECONDARY);for(View icon:new View[]{encryptionLock,encryptionOpen}){LinearLayout.LayoutParams p=ui.size(14,14);p.rightMargin=ui.dp(4);row.addView(icon,p);}}
TextView value=ui.text("—",12,false);value.setFontFeatureSettings("tnum");row.addView(value);networkDetails[i]=value;body.addView(row);if(i<titles.length-1)ui.gap(body,7);}
renderNetwork();
}
private LinearLayout trafficRow(LinearLayout body,String title,TextView[] cells,boolean total){
LinearLayout row=ui.row();row.setPadding(ui.dp(4),ui.dp(5),ui.dp(4),ui.dp(5));body.addView(row);if(total)row.setBackground(ui.background(0x122E7ADB,5));
TextView label=ui.text(title,11,total);row.addView(label,ui.size(28,-2));
for(int i=0;i<3;i++){TextView cell=ui.text("—",11,total);cell.setGravity(Gravity.END);cell.setSingleLine();cell.setFontFeatureSettings("tnum");cell.setAutoSizeTextTypeUniformWithConfiguration(8,11,1,android.util.TypedValue.COMPLEX_UNIT_SP);
LinearLayout.LayoutParams p=i==2?ui.size(46,16):new LinearLayout.LayoutParams(0,ui.dp(16),1);p.leftMargin=ui.dp(4);row.addView(cell,p);cells[i]=cell;}
return row;
}
private void renderNetwork(){
if(networkLabel!=null)networkLabel.setText(network.summary());
if(trafficCells==null)return;
String[] names={"视频","音频","数据","合计"};
for(int i=0;i<4;i++){
RemoteNetworkStatistics.Traffic traffic=network.report==null?null:network.report.traffic[i];
String in=RemoteNetworkStatistics.bitrate(traffic==null?-1:traffic.inbound),out=RemoteNetworkStatistics.bitrate(traffic==null?-1:traffic.outbound),loss=RemoteNetworkStatistics.loss(traffic==null?Double.NaN:traffic.loss);
trafficCells[i][0].setText(in);trafficCells[i][1].setText(out);trafficCells[i][2].setText(loss);trafficRows[i].setContentDescription(names[i]+",接收 "+in+",发送 "+out+",丢包率 "+loss);
}
String[] values={network.fps+" FPS",network.resolution(),RemoteNetworkStatistics.latency(network.latency),RemoteNetworkStatistics.latency(network.rtt),network.mode(),network.report==null?"—":network.report.srtp?"SRTP 已启用":"未启用"};
for(int i=0;i<values.length;i++)networkDetails[i].setText(values[i]);networkDetails[5].setTextColor(network.report!=null&&network.report.srtp?GREEN:SECONDARY);
encryptionLock.setVisibility(network.report!=null&&network.report.srtp?VISIBLE:GONE);encryptionOpen.setVisibility(network.report!=null&&!network.report.srtp?VISIBLE:GONE);
}
private int controlColumns(){return getMeasuredHeight()<ui.dp(400)&&getMeasuredWidth()>=ui.dp(400)?4:3;}
private int panelWidth(int width){return Math.max(1,Math.min(width-ui.dp(16),controlColumns()==4?ui.dp(380):Math.max(ui.dp(280),Math.min(ui.dp(340),width-ui.dp(160)))));}
private int panelHeight(int height){
// First measure every row at its natural height, then cap only to the
// safe viewport. The weighted ScrollView takes any remaining space.
LinearLayout.LayoutParams scrollParams=(LinearLayout.LayoutParams)menuScroll.getLayoutParams();
scrollParams.height=LayoutParams.WRAP_CONTENT;scrollParams.weight=0;
menu.measure(MeasureSpec.makeMeasureSpec(panelWidth(getMeasuredWidth()),MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(0,MeasureSpec.UNSPECIFIED));
int contentHeight=menu.getMeasuredHeight();
scrollParams.height=0;scrollParams.weight=1;
menu.forceLayout();menuScroll.forceLayout();
return Math.min(contentHeight,Math.max(1,height-ui.dp(16)));
}
private void positionMenu(){if(menu==null)return;float ox=orb.getX()+orb.getWidth()/2f;float x=ox>getWidth()/2f?orb.getX()-ui.dp(12)-menu.getWidth():orb.getX()+orb.getWidth()+ui.dp(12);menu.setX(bound(x,ui.dp(8),getWidth()-menu.getWidth()-ui.dp(8)));menu.setY(bound(orb.getY(),ui.dp(8),getHeight()-menu.getHeight()-ui.dp(8)));}
private int keyboardWidth(int width){return Math.min(ui.dp(computerKeyboard?520:440),Math.max(1,width-ui.dp(16)));}
private int keyboardHeight(int height){return Math.min(keyboardPreferredHeight,Math.max(1,height-ui.dp(16)));}
private void positionKeyboard(){if(keyboard!=null){keyboard.setX(bound(keyboard.getX(),ui.dp(8),getWidth()-keyboard.getWidth()-ui.dp(8)));keyboard.setY(bound(keyboard.getY(),ui.dp(8),getHeight()-keyboard.getHeight()-ui.dp(8)));}positionMouse();}
private void closeKeyboard(){if(keyboard!=null){removeView(keyboard);keyboard=null;keyboardKeys=null;}}
private void toggleKeyboard(){if(keyboard!=null){closeKeyboard();modifiers.clear();return;}modifiers.clear();showKeyboard();}
private void showKeyboard(){
float oldX=keyboard==null?-1:keyboard.getX(),oldY=keyboard==null?-1:keyboard.getY();int oldScroll=keyboardKeys==null?0:keyboardKeys.getScrollY();closeKeyboard();keyboard=ui.column();keyboard.setPadding(ui.dp(5),ui.dp(5),ui.dp(5),ui.dp(5));keyboard.setBackground(ui.background(0xFFD1D6DE,12));keyboard.setElevation(ui.dp(10));
LinearLayout top=ui.row();TextView handle=ui.text("━",19,true);handle.setGravity(Gravity.CENTER);handle.setTextColor(SECONDARY);handle.setContentDescription("拖动键盘");top.addView(handle,new LinearLayout.LayoutParams(0,ui.dp(28),1));top.addView(ui.iconButton("close","收起键盘",this::closeKeyboard),ui.size(30,28));keyboard.addView(top);drag(handle,keyboard,()->{});
// Keep the drag/close row fixed while short split windows can scroll every key into view.
keyboardKeys=new ScrollView(getContext());keyboard.addView(keyboardKeys,new LinearLayout.LayoutParams(-1,0,1));LinearLayout keys=ui.column();keyboardKeys.addView(keys);
String[][] rows=computerKeyboard?new String[][]{{"Esc","F1","F2","F3","F4","F5","F6"},{"Tab","Ctrl","Alt","Win","↑","⌫"},{"复制","粘贴","全选","←","↓","→"},{"ABC","空格","Enter"}}:new String[][]{{"1","2","3","4","5","6","7","8","9","0"},{"q","w","e","r","t","y","u","i","o","p"},{"a","s","d","f","g","h","j","k","l"},{"⇧","z","x","c","v","b","n","m","⌫"},{"电脑","剪贴板","空格",".","Enter"}};
for(String[] values:rows){LinearLayout line=ui.row();for(String value:values){String shown=shift&&value.length()==1?value.toUpperCase(java.util.Locale.ROOT):value;TextView key=ui.action(shown,INK,()->keyboardKey(value));key.setTextSize(value.length()>2?11:14);key.setMinHeight(ui.dp(31));int modifier=value.equals("Ctrl")?17:value.equals("Alt")?18:value.equals("Win")?91:0;key.setBackground(ui.background(modifiers.contains(modifier)?0xFF9BC7F7:value.length()>1||value.equals("⇧")?0xFFAFB8C5:Color.WHITE,5));LinearLayout.LayoutParams p=new LinearLayout.LayoutParams(0,ui.dp(31),value.equals("空格")?3:1);p.setMargins(ui.dp(1.5f),0,ui.dp(1.5f),0);line.addView(key,p);}keys.addView(line);ui.gap(keys,3);}
keyboardPreferredHeight=ui.dp(5)*2+ui.dp(28)+rows.length*(ui.dp(31)+ui.dp(3));
addView(keyboard,new LayoutParams(keyboardWidth(getWidth()),keyboardHeight(getHeight())));LinearLayout shownKeyboard=keyboard;ScrollView shownKeys=keyboardKeys;
keyboard.post(()->{if(keyboard==shownKeyboard){keyboard.setX(oldX<0?(getWidth()-keyboard.getWidth())/2f:oldX);keyboard.setY(oldY<0?getHeight()-keyboard.getHeight()-ui.dp(20):oldY);shownKeys.scrollTo(0,oldScroll);constrainPanels();}});
}
private void keyboardKey(String value){
switch(value){
case "⇧":shift=!shift;showKeyboard();return;
case "电脑":computerKeyboard=true;showKeyboard();return;
case "ABC":computerKeyboard=false;showKeyboard();return;
case "剪贴板":actions.clipboard();return;
case "复制":actions.shortcut(0x43);return;case "粘贴":actions.shortcut(0x56);return;case "全选":actions.shortcut(0x41);return;
case "空格":sendKey(32);return;case "⌫":sendKey(8);return;case "Enter":sendKey(13);return;case "Esc":sendKey(27);return;case "Tab":sendKey(9);return;
case "↑":sendKey(38);return;case "↓":sendKey(40);return;case "←":sendKey(37);return;case "→":sendKey(39);return;
// Latch locally; the next key sends a complete chord without leaving remote modifiers down.
case "Ctrl":toggleModifier(17);return;case "Alt":toggleModifier(18);return;case "Win":toggleModifier(91);return;
default:if(value.matches("F[1-6]")){sendKey(111+Integer.parseInt(value.substring(1)));return;}if(!modifiers.isEmpty())sendKey(KeyMap.ascii(value.charAt(0))&255);else actions.text(shift?value.toUpperCase(java.util.Locale.ROOT):value);
}
}
private void toggleModifier(int code){if(!modifiers.add(code))modifiers.remove(code);showKeyboard();}
private void sendKey(int code){if(modifiers.isEmpty())actions.key(code);else{actions.chord(code,modifiers.stream().mapToInt(Integer::intValue).toArray());modifiers.clear();showKeyboard();}}
@android.annotation.SuppressLint("ClickableViewAccessibility") // Tap dispatches performClick; dragging is an additional action.
private void drag(View handle,View target,Runnable tap){
handle.setOnClickListener(v->tap.run());handle.setOnTouchListener(new View.OnTouchListener(){float startX,startY,originX,originY;boolean moved;
public boolean onTouch(View v,MotionEvent event){
switch(event.getActionMasked()){
case MotionEvent.ACTION_DOWN:if(target==orb)cancelMouseInput();startX=event.getRawX();startY=event.getRawY();originX=target.getX();originY=target.getY();moved=false;return true;
case MotionEvent.ACTION_MOVE:float dx=event.getRawX()-startX,dy=event.getRawY()-startY;if(Math.hypot(dx,dy)>ui.dp(4))moved=true;if(moved){if(target==orb)closeMenu();target.setX(bound(originX+dx,ui.dp(8),getWidth()-target.getWidth()-ui.dp(8)));target.setY(bound(originY+dy,ui.dp(8),getHeight()-target.getHeight()-ui.dp(8)));positionMouse();}return true;
case MotionEvent.ACTION_UP:if(!moved)v.performClick();return true;
case MotionEvent.ACTION_CANCEL:return true;
default:return false;
}
}
});
}
void constrainPanels(){
cancelMouseInput();
if(menu!=null&&menuPage.equals("controls")&&menuColumns!=controlColumns())openMenu("controls");
orb.setX(bound(orb.getX(),ui.dp(8),getWidth()-orb.getWidth()-ui.dp(8)));orb.setY(bound(orb.getY(),ui.dp(8),getHeight()-orb.getHeight()-ui.dp(8)));
if(menu!=null||keyboard!=null)requestLayout();
positionKeyboard();
positionMouse();
}
@Override protected void onMeasure(int widthSpec,int heightSpec){
super.onMeasure(widthSpec,heightSpec);
boolean resized=false;
if(menu!=null){
// Use this traversal's viewport, including rotation/inset changes, before drawing.
ViewGroup.LayoutParams p=menu.getLayoutParams();int width=panelWidth(getMeasuredWidth()),height=panelHeight(getMeasuredHeight());
// panelHeight performed an unconstrained measurement; always
// measure again with the final cap, even when it did not change.
p.width=width;p.height=height;resized=true;
}
if(keyboard!=null){
ViewGroup.LayoutParams p=keyboard.getLayoutParams();int width=keyboardWidth(getMeasuredWidth()),height=keyboardHeight(getMeasuredHeight());
if(p.width!=width||p.height!=height){p.width=width;p.height=height;resized=true;}
}
if(resized)super.onMeasure(widthSpec,heightSpec);
}
@Override protected void onLayout(boolean changed,int left,int top,int right,int bottom){
super.onLayout(changed,left,top,right,bottom);
if(!orbPositioned){orb.setX(Math.max(ui.dp(12),getWidth()-ui.dp(66)));orb.setY(ui.dp(17));orbPositioned=true;}
orb.setX(bound(orb.getX(),ui.dp(8),getWidth()-orb.getWidth()-ui.dp(8)));orb.setY(bound(orb.getY(),ui.dp(8),getHeight()-orb.getHeight()-ui.dp(8)));
// New/rebuilt menus have real dimensions now; position them in the same frame.
positionMenu();
positionKeyboard();
positionMouse();
}
@Override protected void onDetachedFromWindow(){cancelMouseInput();super.onDetachedFromWindow();}
@Override protected void onSizeChanged(int width,int height,int oldWidth,int oldHeight){super.onSizeChanged(width,height,oldWidth,oldHeight);post(this::constrainPanels);}
private static float bound(float value,float min,float max){return Math.max(min,Math.min(value,Math.max(min,max)));}
}
@@ -0,0 +1,75 @@
package cn.crossdesk.mobile;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.OpenableColumns;
import java.io.*;
import java.nio.file.Files;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/** Private session files; document-provider reads/writes never run on UI/RTC threads. */
final class SessionDocuments {
interface Prepared { void ready(File file,String name); void failed(); }
private final Context context;
private final ExecutorService io=Executors.newSingleThreadExecutor(r->new Thread(r,"CrossDesk documents"));
final File directory;
private volatile boolean closed;
SessionDocuments(Context context){
this.context=context.getApplicationContext();
directory=new File(context.getCacheDir(),"transfers/"+UUID.randomUUID());
}
void prepare(Uri uri,Prepared callback){
io.execute(()->{
File staged=null;
try{
if(closed)return;
String name="file";
try(Cursor cursor=context.getContentResolver().query(uri,new String[]{OpenableColumns.DISPLAY_NAME},null,null,null)){
if(cursor!=null&&cursor.moveToFirst())name=cursor.getString(0);
}
name=safeName(name);
Files.createDirectories(directory.toPath());
staged=File.createTempFile("sending-",".part",directory);
try(InputStream input=context.getContentResolver().openInputStream(uri);OutputStream output=new FileOutputStream(staged)){
if(input==null)throw new IOException("No input");
copy(input,output);
}
if(closed){Files.deleteIfExists(staged.toPath());return;}
callback.ready(staged,name);
}catch(Exception error){
if(staged!=null)staged.delete();
if(!closed)callback.failed();
}
});
}
void save(File file,Uri uri,java.util.function.Consumer<Boolean> completion){
io.execute(()->{
boolean success=false;
try{
if(closed)return;
try(InputStream input=new FileInputStream(file);OutputStream output=context.getContentResolver().openOutputStream(uri,"wt")){
if(output==null)throw new IOException("No output");
copy(input,output);
}
success=true;
}catch(Exception ignored){ }
if(!closed)completion.accept(success);
});
}
private void copy(InputStream input,OutputStream output)throws IOException{
byte[] bytes=new byte[64*1024];int count;
while((count=input.read(bytes))!=-1){if(closed)throw new IOException("Session closed");output.write(bytes,0,count);}
}
static String safeName(String value){
if(value==null)return "file";
value=value.replace('\\','/');value=value.substring(value.lastIndexOf('/')+1).replaceAll("[\\p{Cntrl}:]","_");
return value.isEmpty()||value.equals(".")||value.equals("..")||value.getBytes(StandardCharsets.UTF_8).length>240?"file":value;
}
// Called after native file handles have closed. Queue cleanup behind any provider I/O.
void close(){closed=true;io.execute(()->remove(directory));io.shutdown();}
private static void remove(File file){File[] children=file.listFiles();if(children!=null)for(File child:children)remove(child);file.delete();}
}
@@ -0,0 +1,153 @@
package cn.crossdesk.mobile;
import android.annotation.SuppressLint;
import android.graphics.Color;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.InsetDrawable;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
/** A 140 × 48 dp bar. Touch ownership continues outside the original key bounds. */
@SuppressLint("ViewConstructor")
final class VirtualMouseBar extends LinearLayout {
private final RemoteMouseInput input;
private final MobileUi ui;
private final TextView[] keys = new TextView[3];
private int generation;
VirtualMouseBar(MobileUi ui, RemoteMouseInput input) {
super(ui.context); this.ui = ui; this.input = input;
setOrientation(HORIZONTAL);
setPadding(ui.dp(4), ui.dp(2), ui.dp(4), ui.dp(2));
GradientDrawable shell = ui.background(Color.WHITE, 18);
shell.setStroke(ui.dp(.5f), 0xFFD4DAE2);
setBackground(shell);
setMotionEventSplittingEnabled(true);
keys[0] = key("鼠标左键,按住并拖动,松开结束拖拽", 0);
keys[1] = key("鼠标滚轮,上下滑动,可滑出按键范围", 1);
keys[2] = key("鼠标右键,按住并拖动,松开结束拖拽", 2);
input.didCancel = this::resetTouches;
setContentDescription("虚拟鼠标");
}
@SuppressLint("ClickableViewAccessibility") // Touch sends real down/up; performClick serves accessibility only.
private TextView key(String description, int index) {
TextView key = index == 1 ? new WheelKey(ui) : new TextView(ui.context);
key.setGravity(android.view.Gravity.CENTER);
key.setContentDescription(description);
key.setClickable(true); key.setFocusable(true);
highlight(key, index, false);
addView(key, new LayoutParams(0, ui.dp(44), 1));
key.setOnClickListener(v -> {
if (index == 1) { ((WheelKey)key).advance(ui.dp(10)); input.scroll(-1); }
else { input.virtualButton(index == 0, true); input.virtualButton(index == 0, false); }
});
if (index == 1) {
key.setAccessibilityDelegate(new View.AccessibilityDelegate() {
@Override public void onInitializeAccessibilityNodeInfo(View host, android.view.accessibility.AccessibilityNodeInfo info) {
super.onInitializeAccessibilityNodeInfo(host, info);
info.setScrollable(true);
info.addAction(android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction.ACTION_SCROLL_FORWARD);
info.addAction(android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction.ACTION_SCROLL_BACKWARD);
}
@Override public boolean performAccessibilityAction(View host, int action, android.os.Bundle args) {
if (action == android.view.accessibility.AccessibilityNodeInfo.ACTION_SCROLL_FORWARD || action == android.view.accessibility.AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD) {
int direction = action == android.view.accessibility.AccessibilityNodeInfo.ACTION_SCROLL_FORWARD ? -1 : 1;
((WheelKey)key).advance(-direction * ui.dp(10));
input.scroll(direction); return true;
}
return super.performAccessibilityAction(host, action, args);
}
});
}
key.setOnTouchListener(new View.OnTouchListener() {
int pointer = -1, startedGeneration;
float lastX, lastY, remainder;
@Override public boolean onTouch(View v, MotionEvent event) {
int action = event.getActionMasked();
if (action == MotionEvent.ACTION_DOWN) {
pointer = event.getPointerId(0); startedGeneration = generation;
lastX = event.getX(); lastY = event.getY(); remainder = 0;
highlight(key, index, true);
if (index != 1) input.virtualButton(index == 0, true);
return true;
}
if (startedGeneration != generation || pointer == -1) return true;
if (action == MotionEvent.ACTION_MOVE) {
int p = event.findPointerIndex(pointer);
if (p < 0) return true;
float dx = event.getX(p) - lastX, dy = event.getY(p) - lastY;
lastX = event.getX(p); lastY = event.getY(p);
if (index != 1) { input.drag(dx, dy); return true; }
((WheelKey)key).advance(dy);
remainder += dy;
float step = ui.dp(10);
int ticks = (int)(remainder / step);
// Positive protocol wheel values scroll up; finger-down scrolls down.
for (int i = 0; i < Math.min(Math.abs(ticks), 32); i++) input.scroll(ticks > 0 ? -1 : 1);
remainder -= ticks * step;
}
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL ||
(action == MotionEvent.ACTION_POINTER_UP && event.getPointerId(event.getActionIndex()) == pointer)) {
if (index != 1) input.virtualButton(index == 0, false);
pointer = -1; remainder = 0; highlight(key, index, false);
}
return true;
}
});
return key;
}
private void highlight(TextView key, int index, boolean pressed) {
key.setPressed(pressed);
key.setTextColor(pressed ? Color.WHITE : 0xB8303640);
// Narrow only the wheel's visible face; its 44 × 44 dp target remains.
GradientDrawable face = ui.background(pressed ? MobileUi.BLUE : 0xFFEDF0F4, 6);
float left = ui.dp(index == 0 ? 14 : 6), right = ui.dp(index == 2 ? 14 : 6);
face.setCornerRadii(new float[]{left,left,right,right,right,right,left,left});
int horizontal = ui.dp(index == 1 ? 13 : 1), vertical = ui.dp(index == 1 ? 7 : 2);
key.setBackground(new InsetDrawable(face, horizontal, vertical, horizontal, vertical));
}
void cancelInput() {
input.releaseAll();
}
private void resetTouches() {
generation++;
for (int i=0;i<keys.length;i++) if (keys[i] != null) highlight(keys[i], i, false);
}
/** Flat, uniformly colored treads follow the finger, wrapping every 5 dp. */
private static final class WheelKey extends TextView {
private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
private final Path clip = new Path();
private final float density;
private float phase = 2;
WheelKey(MobileUi ui) {
super(ui.context); density = getResources().getDisplayMetrics().density;
clip.addRoundRect(new RectF(0,0,12,24),2,2,Path.Direction.CW);
}
void advance(float distance) {
phase = (phase + distance / density * .65f) % 5;
invalidate();
}
@Override protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.save();
canvas.translate((getWidth()-12*density)/2f, (getHeight()-24*density)/2f);
canvas.scale(density,density);
canvas.clipPath(clip);
paint.setColor(getCurrentTextColor());
for (int i=-1;i<=6;i++) {
float y=i*5+phase;
canvas.drawRect(0,y,12,y+1.5f,paint);
}
canvas.restore();
}
}
@Override protected void onDetachedFromWindow() { cancelInput(); super.onDetachedFromWindow(); }
@Override public void onWindowFocusChanged(boolean focused) { super.onWindowFocusChanged(focused); if (!focused) cancelInput(); }
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 217 KiB

@@ -0,0 +1,10 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="14dp"
android:height="14dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FF248A3D"
android:fillType="evenOdd"
android:pathData="M12,2A10,10 0,1 0,12 22A10,10 0,1 0,12 2Z M6.5,11.5L10.3,15.3L17.5,8.1L16.1,6.7L10.3,12.5L7.9,10.1Z" />
</vector>
@@ -0,0 +1,4 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
<path android:fillColor="#FFFFFFFF" android:pathData="M3,3h18v14h-8v3h4v2H7v-2h4v-3H3zM5,5v10h14V5z" />
</vector>
@@ -0,0 +1,6 @@
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@android:color/white" />
<foreground>
<inset android:drawable="@drawable/mobile_brand" android:inset="16%" />
</foreground>
</adaptive-icon>
@@ -0,0 +1,9 @@
<resources>
<style name="AppTheme" parent="android:style/Theme.Material.Light.NoActionBar">
<item name="android:fontFamily">sans</item>
<item name="android:colorAccent">#2E7ADB</item>
<item name="android:windowLightStatusBar">true</item>
<item name="android:windowActionModeOverlay">true</item>
<item name="android:windowBackground">#F2F2F7</item>
</style>
</resources>
@@ -0,0 +1,14 @@
<data-extraction-rules>
<cloud-backup>
<exclude domain="root" path="." />
<exclude domain="sharedpref" path="." />
<exclude domain="database" path="." />
<exclude domain="file" path="." />
</cloud-backup>
<device-transfer>
<exclude domain="root" path="." />
<exclude domain="sharedpref" path="." />
<exclude domain="database" path="." />
<exclude domain="file" path="." />
</device-transfer>
</data-extraction-rules>
+1
View File
@@ -0,0 +1 @@
plugins { id 'com.android.application' version '9.1.0' apply false }
+4
View File
@@ -0,0 +1,4 @@
org.gradle.jvmargs=-Xmx3g -Dfile.encoding=UTF-8
android.useAndroidX=true
crossdeskVersionName=1.6.1
crossdeskVersionCode=3
Binary file not shown.
+8
View File
@@ -0,0 +1,8 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.1-all.zip
distributionSha256Sum=17f277867f6914d61b1aa02efab1ba7bb439ad652ca485cd8ca6842fccec6e43
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+248
View File
@@ -0,0 +1,248 @@
#!/bin/sh
#
# Copyright © 2015 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
+93
View File
@@ -0,0 +1,93 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
@@ -0,0 +1,24 @@
CrossDesk 开源软件权利说明 / Open-source software rights
CrossDesk 按 GNU GPL 第 3 版发布,MiniRTC 按 GNU LGPL 第 3 版发布。
其他组件适用各自列明的许可证。使用、复制、修改及再分发这些组件的权利,
以相应许可证为准;本应用的普通使用条款不限制开源许可证授予你的权利。
许可证中的保证、责任限制及其他条件仍然适用。
“本版本源码与构建说明”提供与发行版本对应的源码入口、子模块信息、
依赖配方、补丁及构建说明。可以修改相关库后重新构建和链接应用。
在自己的 Android 设备上运行修改版时,可以使用自己的 Android 签名密钥,
并按构建文档生成和安装 APK。
CrossDesk is distributed under GNU GPL version 3; MiniRTC is distributed
under GNU LGPL version 3. Other components are governed by their listed
licenses. Your rights to use, copy, modify and redistribute those components
are governed by the applicable licenses. The application's ordinary terms
of use do not restrict rights granted by those open-source licenses.
The licenses' warranty, liability and other provisions continue to apply.
The version-specific source and build links identify the application source,
submodules, dependency recipes, patches and build instructions. You can
modify the libraries and rebuild and relink the application. Running a
modified build on your own Android device can use your own Android signing
key. Build and install the APK as described in the build guide.
File diff suppressed because one or more lines are too long
+41
View File
@@ -0,0 +1,41 @@
/*
* @Author: DI JUNKUN
* @Date: 2026-10-02
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
*/
#ifndef _CONTROLLER_PROTOCOL_H_
#define _CONTROLLER_PROTOCOL_H_
#include <minirtc.h>
#include <nlohmann/json.hpp>
#include <remote_action.h>
namespace crossdesk::android_controller {
inline std::string SecureAttentionMessage() {
RemoteAction action{};
action.type = service_command;
action.c.flag = send_sas;
return action.to_json();
}
inline std::string VideoSettingsMessage(int quality, int frame_rate, int preference,
uint32_t request_id) {
RemoteAction action{};
action.type = video_settings;
action.vs = {quality, frame_rate, preference, request_id, false};
return action.to_json();
}
inline nlohmann::json NetworkReport(const MiniRtcNetTrafficStats& stats, TraversalMode mode) {
const auto traffic = [](const MiniRtcInboundStats& in, const MiniRtcOutboundStats& out) {
return nlohmann::json{{"inbound", in.bitrate}, {"outbound", out.bitrate}, {"loss", in.loss_rate}};
};
return {{"rtt", stats.rtt_ms}, {"mode", mode}, {"srtp", stats.srtp_active},
{"video", traffic(stats.video_inbound_stats, stats.video_outbound_stats)},
{"audio", traffic(stats.audio_inbound_stats, stats.audio_outbound_stats)},
{"data", traffic(stats.data_inbound_stats, stats.data_outbound_stats)},
{"total", traffic(stats.total_inbound_stats, stats.total_outbound_stats)}};
}
} // namespace crossdesk::android_controller
#endif
+271
View File
@@ -0,0 +1,271 @@
/*
* @Author: DI JUNKUN
* @Date: 2026-10-09
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
*/
#ifndef _FILE_TRANSFER_SESSION_H_
#define _FILE_TRANSFER_SESSION_H_
#include <file_transfer_format.h>
#include <stream_names.h>
#include <algorithm>
#include <array>
#include <chrono>
#include <filesystem>
#include <fstream>
#include <functional>
#include <map>
#include <mutex>
#include <optional>
namespace crossdesk::android_controller {
// File I/O is bounded to one chunk per pump. Feedback is delivered by MiniRTC
// callback threads; no callback waits for the RTC executor or for a remote ACK.
class FileTransferSession {
public:
using Clock = std::chrono::steady_clock;
using Send = std::function<int(const char*, const char*, size_t)>;
using Progress = std::function<void(const std::string&, double, bool,
const std::string&)>;
FileTransferSession(Send send, Progress progress)
: send_(std::move(send)), progress_(std::move(progress)) {}
~FileTransferSession() {
if (outgoing_) {
outgoing_->input.close();
std::error_code ec;
std::filesystem::remove(outgoing_->path, ec);
}
for (auto& entry : incoming_) Remove(entry.second);
}
void SetDirectory(std::filesystem::path directory) {
std::lock_guard<std::mutex> lock(mutex_);
directory_ = std::move(directory);
}
bool Start(const std::filesystem::path& path, const std::string& name,
Clock::time_point now = Clock::now()) {
std::lock_guard<std::mutex> lock(mutex_);
if (outgoing_ || name.empty() || name.size() > UINT16_MAX) return false;
std::error_code ec;
if (!std::filesystem::is_regular_file(path, ec)) return false;
const auto size = std::filesystem::file_size(path, ec);
if (ec) return false;
Outgoing file;
file.input.open(path, std::ios::binary);
if (!file.input) return false;
file.id = ++next_id_;
file.name = name;
file.path = path;
file.total = size;
file.updated = now;
outgoing_ = std::move(file);
progress_(name, 0, true, "");
return true;
}
void Pump(Clock::time_point now = Clock::now()) {
std::lock_guard<std::mutex> lock(mutex_);
for (auto it = incoming_.begin(); it != incoming_.end();) {
if (now - it->second.updated < timeout_) { ++it; continue; }
Reject(it->first, it->second.total, it->second.received);
progress_(it->second.name, -1, false, "");
Remove(it->second);
it = incoming_.erase(it);
}
if (!outgoing_) return;
auto& file = *outgoing_;
if (now - file.updated >= timeout_) { FinishSend(false); return; }
if (file.last || file.sent - file.acked >= 1024 * 1024) return;
std::array<char, kFileChunkSize> payload{};
const auto size = static_cast<uint32_t>(std::min<uint64_t>(payload.size(), file.total - file.sent));
if (size) {
file.input.read(payload.data(), size);
if (file.input.gcount() != size) { FinishSend(false); return; }
}
const bool first = file.sent == 0;
const bool last = file.sent + size == file.total;
const auto chunk = EncodeFileChunk(file.id, file.sent, file.total,
payload.data(), size, first ? &file.name : nullptr, first, last);
if (chunk.empty() || send_(kFileStream, chunk.data(), chunk.size()) != 0) {
FinishSend(false); return;
}
file.sent += size;
file.last = last;
}
void Ack(const char* data, size_t size, Clock::time_point now = Clock::now()) {
FileTransferAck ack{};
if (!DecodeFileTransferAck(data, size, &ack)) return;
std::lock_guard<std::mutex> lock(mutex_);
if (!outgoing_ || ack.file_id != outgoing_->id) return;
auto& file = *outgoing_;
if (ack.total_size != file.total || ack.acked_offset > file.sent ||
(ack.flags & ~3u)) return;
if (ack.flags & 2) { FinishSend(false); return; }
if (ack.flags & 1) {
if (file.last && ack.acked_offset == file.total) FinishSend(true);
return;
}
if (ack.acked_offset <= file.acked) return;
file.acked = ack.acked_offset;
file.updated = now;
Report(file.name, file.acked, file.total, true, file.percent);
}
void Receive(const char* data, size_t size, Clock::time_point now = Clock::now()) {
FileChunkView chunk;
if (!DecodeFileChunk(data, size, &chunk)) return;
const auto& h = chunk.header;
std::lock_guard<std::mutex> lock(mutex_);
auto it = incoming_.find(h.file_id);
const bool first = h.flags & 1, last = h.flags & 2;
const bool invalid = (h.flags & ~3u) || h.total_size > INT64_MAX ||
(first && h.offset != 0) || chunk.payload_size > kFileChunkSize ||
size != sizeof(FileChunkHeader) + h.name_len + chunk.payload_size ||
(!first && h.name_len) || (!chunk.payload_size && !last) ||
last != (h.offset + chunk.payload_size == h.total_size);
if (invalid || (it == incoming_.end() && incoming_.size() >= 4)) {
Reject(h.file_id, h.total_size, h.offset);
if (it != incoming_.end()) { progress_(it->second.name, -1, false, ""); Remove(it->second); incoming_.erase(it); }
return;
}
if (it == incoming_.end()) {
Incoming file;
file.name = SafeName(chunk.file_name);
file.total = h.total_size;
std::error_code ec;
if (!directory_.empty()) std::filesystem::create_directories(directory_, ec);
// A per-transfer directory avoids overwrites, even for duplicate names.
auto folder = directory_ / (std::to_string(h.file_id) + "-" + std::to_string(++receive_id_));
if (directory_.empty() || ec || !std::filesystem::create_directory(folder, ec)) {
Reject(h.file_id, h.total_size, 0); progress_(file.name, -1, false, ""); return;
}
file.path = folder / file.name;
file.partial = folder / ".partial";
file.output.open(file.partial, std::ios::binary | std::ios::trunc);
if (!file.output) {
Reject(h.file_id, h.total_size, 0); progress_(file.name, -1, false, ""); Remove(file); return;
}
it = incoming_.emplace(h.file_id, std::move(file)).first;
}
auto& file = it->second;
if (h.total_size != file.total || (first && file.first) ||
!AddRange(file, h.offset, h.offset + chunk.payload_size)) {
Reject(h.file_id, h.total_size, h.offset);
progress_(file.name, -1, false, ""); Remove(file); incoming_.erase(it); return;
}
if (first) {
file.first = true;
file.name = SafeName(chunk.file_name);
file.path = file.path.parent_path() / file.name;
}
file.last |= last;
// KCP removes messages in order, but delivers batches outside its lock on
// both RTP and timer threads. Track coverage instead of assuming callbacks
// arrive in order; ACK only the contiguous prefix and never expose holes.
file.received = !file.ranges.empty() && file.ranges.begin()->first == 0
? file.ranges.begin()->second : 0;
const bool complete = file.first && file.last && file.received == file.total;
file.output.seekp(static_cast<std::streamoff>(h.offset));
file.output.write(chunk.payload, chunk.payload_size);
if (complete) { file.output.flush(); file.output.close(); }
std::error_code ec;
if (complete && !file.output.fail()) std::filesystem::rename(file.partial, file.path, ec);
if (file.output.fail() || ec) {
Reject(h.file_id, h.total_size, h.offset);
progress_(file.name, -1, false, ""); Remove(file); incoming_.erase(it); return;
}
file.updated = now;
const FileTransferAck ack{kFileAckMagic, h.file_id, file.received, file.total, complete ? 1u : 0u};
const auto packet = EncodeFileTransferAck(ack);
send_(kFileFeedbackStream, packet.data(), packet.size());
if (complete) {
progress_(file.name, 1, false, file.path.string());
incoming_.erase(it);
} else Report(file.name, file.received, file.total, false, file.percent);
}
bool Sending() {
std::lock_guard<std::mutex> lock(mutex_);
return outgoing_.has_value();
}
private:
struct Outgoing {
uint32_t id = 0;
std::string name;
std::filesystem::path path;
std::ifstream input;
uint64_t total = 0, sent = 0, acked = 0;
bool last = false;
int percent = -1;
Clock::time_point updated;
};
struct Incoming {
std::string name;
std::filesystem::path path, partial;
std::ofstream output;
uint64_t total = 0, received = 0;
bool first = false, last = false;
std::map<uint64_t, uint64_t> ranges;
int percent = -1;
Clock::time_point updated;
};
static bool AddRange(Incoming& file, uint64_t start, uint64_t end) {
if (start == end) return true;
auto next = file.ranges.lower_bound(start);
if (next != file.ranges.end() && next->first < end) return false;
if (next != file.ranges.begin()) {
auto previous = std::prev(next);
if (previous->second > start) return false;
if (previous->second == start) { start = previous->first; file.ranges.erase(previous); }
}
if (next != file.ranges.end() && next->first == end) { end = next->second; file.ranges.erase(next); }
file.ranges.emplace(start, end);
return file.ranges.size() <= 1024;
}
static std::string SafeName(std::string name) {
const auto slash = name.find_last_of("/\\");
if (slash != std::string::npos) name.erase(0, slash + 1);
for (auto& ch : name) if (static_cast<unsigned char>(ch) < 32 || ch == ':') ch = '_';
if (name.empty() || name == "." || name == ".." || name == ".partial" || name.size() > 240) return "received_file";
return name;
}
static void Remove(Incoming& file) {
file.output.close();
std::error_code ec;
std::filesystem::remove(file.partial, ec);
std::filesystem::remove(file.path.parent_path(), ec);
}
void Reject(uint32_t id, uint64_t total, uint64_t offset) {
const auto packet = EncodeFileTransferAck({kFileAckMagic, id, offset, total, 2});
send_(kFileFeedbackStream, packet.data(), packet.size());
}
void Report(const std::string& name, uint64_t offset, uint64_t total, bool sending, int& previous) {
const double progress = total ? static_cast<double>(offset) / total : 0;
const int percent = static_cast<int>(progress * 100);
if (percent != previous) { previous = percent; progress_(name, std::min(progress, .99), sending, ""); }
}
void FinishSend(bool success) {
progress_(outgoing_->name, success ? 1 : -1, true, "");
outgoing_->input.close();
std::error_code ec;
std::filesystem::remove(outgoing_->path, ec);
outgoing_.reset();
}
const std::chrono::seconds timeout_{30};
std::mutex mutex_;
Send send_;
Progress progress_;
std::filesystem::path directory_;
std::optional<Outgoing> outgoing_;
std::map<uint32_t, Incoming> incoming_;
uint32_t next_id_ = 0;
uint64_t receive_id_ = 0;
};
} // namespace crossdesk::android_controller
#endif
+72
View File
@@ -0,0 +1,72 @@
/*
* @Author: DI JUNKUN
* @Date: 2026-10-02
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
*/
#ifndef _LATEST_FRAME_WORKER_H_
#define _LATEST_FRAME_WORKER_H_
#include <condition_variable>
#include <functional>
#include <mutex>
#include <optional>
#include <thread>
#include <utility>
namespace crossdesk::android_controller {
// Rendering may wait for Surface buffers. Never hold up the decoder or build
// a FIFO of obsolete pictures: keep at most one pending decoded frame.
template <typename Frame>
class LatestFrameWorker {
public:
explicit LatestFrameWorker(std::function<void(Frame)> render)
: render_(std::move(render)), thread_([this] { Run(); }) {}
~LatestFrameWorker() { Stop(); }
LatestFrameWorker(const LatestFrameWorker&) = delete;
LatestFrameWorker& operator=(const LatestFrameWorker&) = delete;
bool Submit(Frame frame) {
std::lock_guard lock(mutex_);
if (stopped_) return false;
pending_ = std::move(frame);
changed_.notify_one();
return true;
}
void Clear() {
std::lock_guard lock(mutex_);
pending_.reset();
}
// Called by the session owner, before destroying the peer or Surface.
void Stop() {
{
std::lock_guard lock(mutex_);
stopped_ = true;
pending_.reset();
}
changed_.notify_one();
if (thread_.joinable()) thread_.join();
}
private:
void Run() {
for (;;) {
std::unique_lock lock(mutex_);
changed_.wait(lock, [this] { return stopped_ || pending_.has_value(); });
if (stopped_) return;
Frame frame = std::move(*pending_);
pending_.reset();
lock.unlock();
render_(std::move(frame));
}
}
const std::function<void(Frame)> render_;
std::mutex mutex_;
std::condition_variable changed_;
std::optional<Frame> pending_;
bool stopped_ = false;
std::thread thread_;
};
} // namespace crossdesk::android_controller
#endif
+486
View File
@@ -0,0 +1,486 @@
#include <jni.h>
#include <android/native_window_jni.h>
#include <libyuv.h>
#include <minirtc.h>
#include <log.h>
#include <remote_action.h>
#include <app_version.h>
#include <stream_names.h>
#include <display_stream_id.h>
#include <nlohmann/json.hpp>
#include <atomic>
#include <algorithm>
#include <cstring>
#include <memory>
#include <mutex>
#include <set>
#include <string>
#include <stdexcept>
#include <vector>
#include "controller_protocol.h"
#include "file_transfer_session.h"
#include "android_codec_support.h"
#include "latest_frame_worker.h"
#include "video_picture.h"
#include "video_timing.h"
namespace {
using namespace crossdesk;
using nlohmann::json;
JavaVM* vm = nullptr;
struct Environment {
JNIEnv* env = nullptr;
bool attached = false;
Environment() {
if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
attached = vm->AttachCurrentThread(&env, nullptr) == JNI_OK;
}
}
~Environment() { if (attached) vm->DetachCurrentThread(); }
};
std::string String(JNIEnv* env, jstring value) {
if (!value) return {};
const char* bytes = env->GetStringUTFChars(value, nullptr);
std::string result = bytes ? bytes : "";
if (bytes) env->ReleaseStringUTFChars(value, bytes);
return result;
}
struct Session;
using android_controller::VideoPicture;
void RenderVideo(Session* s, VideoPicture picture);
struct CallbackContext { Session* owner; bool controller; };
struct Session {
jobject owner = nullptr;
jmethodID event_method, audio_method, frame_method;
PeerPtr* identity = nullptr;
PeerPtr* controller = nullptr;
CallbackContext identity_context{this, false}, controller_context{this, true};
std::string host, log_path, identity_login, controller_login, remote;
int port;
std::atomic<bool> stopping{false};
std::atomic<uint64_t> signal_generation{0};
std::atomic<int> signal_status{-1};
std::atomic<int> display{0};
std::atomic<bool> surface_ready{false};
std::atomic<uint64_t> video_generation{0};
std::mutex render_mutex;
ANativeWindow* window = nullptr;
uint32_t width = 0, height = 0;
uint64_t frame_id = 0;
std::optional<VideoPicture> surface_picture;
void DetachDecoderSurface() {
if (surface_picture) surface_picture->RenderSurface(nullptr);
surface_picture.reset();
}
std::set<int> pressed_keys;
unsigned pressed_buttons = 0;
float pointer_x = .5f, pointer_y = .5f;
android_controller::LatestFrameWorker<VideoPicture> renderer{
[this](VideoPicture picture) { RenderVideo(this, std::move(picture)); }};
android_controller::FileTransferSession files{
[this](const char* stream, const char* data, size_t size) {
return controller && !stopping
? SendReliableDataFrame(controller, data, size, stream) : -1;
},
[this](const std::string& name, double progress, bool sending, const std::string& path) {
Event(10, {{"name", name}, {"progress", progress}, {"sending", sending}, {"path", path}});
}};
void Event(int type, const char* data, size_t size) {
if (stopping || size > 1024 * 1024) return;
Environment scope;
if (!scope.env) return;
jbyteArray bytes = scope.env->NewByteArray(static_cast<jsize>(size));
if (!bytes) return;
scope.env->SetByteArrayRegion(bytes, 0, size, reinterpret_cast<const jbyte*>(data));
scope.env->CallVoidMethod(owner, event_method, type, bytes);
scope.env->DeleteLocalRef(bytes);
if (scope.env->ExceptionCheck()) scope.env->ExceptionClear();
}
void Event(int type, const json& value) {
const std::string data = value.dump(-1, ' ', false, json::error_handler_t::replace); Event(type, data.data(), data.size());
}
void Send(const char* stream, const std::string& data) {
if (controller && !stopping && !data.empty())
SendReliableDataFrame(controller, data.data(), data.size(), stream);
}
void Surface(JNIEnv* env, jobject surface) {
std::lock_guard<std::mutex> lock(render_mutex);
++video_generation;
renderer.Clear();
DetachDecoderSurface();
if (window) ANativeWindow_release(window);
window = surface ? ANativeWindow_fromSurface(env, surface) : nullptr;
surface_ready = window != nullptr;
width = height = 0;
}
~Session() {
// API calls and destruction share the Java RTC executor. Release any
// delivered input even when queued Java key-up events were cancelled.
if (controller) {
for (int key : pressed_keys) {
RemoteAction action{}; action.type = keyboard;
action.k = {static_cast<size_t>(key), 0, false, key_up};
Send(kKeyboardStream, action.to_json());
}
for (int button = 0; button < 3; ++button) {
if (!(pressed_buttons & (1u << button))) continue;
RemoteAction action{}; action.type = mouse;
action.m = {pointer_x, pointer_y, 0, static_cast<MouseFlag>(2 + button * 2)};
Send(kMouseStream, action.to_json());
}
}
stopping = true;
renderer.Stop();
if (controller) {
LeaveConnection(controller, remote.c_str());
DestroyPeer(&controller);
}
if (identity) DestroyPeer(&identity);
Environment scope;
Surface(scope.env, nullptr);
if (scope.env) scope.env->DeleteGlobalRef(owner);
}
};
void Signal(SignalStatus status, const char*, size_t, void* user) {
auto* ctx = static_cast<CallbackContext*>(user);
if (!ctx->controller && status == SignalStatus::SignalConnected &&
!ctx->owner->stopping && ctx->owner->identity) {
// Report after every identity login, including reconnects. The server
// ignores client_info sent through the temporary C- controller peer.
constexpr char info[] =
R"({"type":"client_info","version":"android-native","platform":"android"})";
SendSignalMessage(ctx->owner->identity, info, sizeof(info) - 1);
}
if (!ctx->controller && ctx->owner->signal_status.exchange(status) != status)
++ctx->owner->signal_generation;
const auto generation = ctx->owner->signal_generation.load();
ctx->owner->Event(1, {{"controller", ctx->controller}, {"status", status}, {"generation", generation}});
}
void SignalMessage(const char* data, size_t size, void* user) {
auto* ctx = static_cast<CallbackContext*>(user);
if (ctx->controller || !data || !size || size > 1024 * 1024) return;
const auto generation = ctx->owner->signal_generation.load();
auto message = json::parse(data, data + size, nullptr, false);
if (!message.is_object() || !message.contains("type") || !message["type"].is_string()) return;
const auto type = message["type"].get<std::string>();
if (type == "announcements" || type == "announcements_changed") ctx->owner->Event(8, data, size);
else if (type == "presence" || type == "presence_update") {
message["generation"] = generation;
ctx->owner->Event(9, message);
}
}
void Connection(ConnectionStatus status, const char*, size_t, void* user) {
auto* ctx = static_cast<CallbackContext*>(user);
if (ctx->controller) ctx->owner->Event(2, {{"status", status}});
}
void Network(const char* id, size_t size, TraversalMode mode,
const MiniRtcNetTrafficStats* stats, const char*, size_t, void* user) {
auto* ctx = static_cast<CallbackContext*>(user);
if (!ctx->controller && mode == UnknownMode && id && size) {
ctx->owner->Event(3, id, size);
} else if (ctx->controller && stats) {
ctx->owner->Event(7, android_controller::NetworkReport(*stats, mode));
}
}
void Data(const char* data, size_t size, const char*, size_t,
const char* stream, size_t stream_size, void* user) {
auto* ctx = static_cast<CallbackContext*>(user);
if (!ctx->controller || !data || !stream || size > kMaxClipboardBytes) return;
const std::string name(stream, stream_size);
if (name == kFileStream) { ctx->owner->files.Receive(data, size); return; }
if (name == kFileFeedbackStream) { ctx->owner->files.Ack(data, size); return; }
if (name == kControlStream) {
RemoteAction action{};
if (action.from_json(std::string(data, size))) {
const auto message = action.to_json();
ctx->owner->Event(4, message.data(), message.size());
FreeRemoteAction(action);
}
}
if (name == kClipboardStream) ctx->owner->Event(6, data, size);
}
void Audio(const char* data, size_t size, const char*, size_t,
const char*, size_t, void* user) {
auto* ctx = static_cast<CallbackContext*>(user);
auto* s = ctx->owner;
if (!ctx->controller || s->stopping || !data || !size || size > 23040) return;
Environment scope;
if (!scope.env) return;
auto bytes = scope.env->NewByteArray(size);
if (!bytes) return;
scope.env->SetByteArrayRegion(bytes, 0, size, reinterpret_cast<const jbyte*>(data));
scope.env->CallVoidMethod(s->owner, s->audio_method, bytes);
scope.env->DeleteLocalRef(bytes);
if (scope.env->ExceptionCheck()) scope.env->ExceptionClear();
}
void Video(const MiniRtcVideoFrame* frame, const char*, size_t,
const char* stream, size_t stream_size, void* user) {
auto* ctx = static_cast<CallbackContext*>(user);
auto* s = ctx->owner;
const auto generation = s->video_generation.load();
if (!ctx->controller || s->stopping || !s->surface_ready || !frame || !stream ||
std::string(stream, stream_size) != MakeDisplayStreamId(s->display.load())) return;
auto picture = VideoPicture::RetainOrCopy(*frame, generation);
if (picture) s->renderer.Submit(std::move(*picture));
}
void RenderVideo(Session* s, VideoPicture picture) {
const auto w = picture.width, h = picture.height;
std::lock_guard<std::mutex> lock(s->render_mutex);
if (s->stopping || !s->window || picture.generation != s->video_generation) return;
const bool size_changed = s->width != w || s->height != h;
if (picture.IsSurface()) {
if (picture.RenderSurface(s->window) != 0) return;
// Keep a consumed token to detach the codec before Surface destruction,
// monitor switching, or CPU rendering after a software fallback.
s->surface_picture = picture;
} else {
const bool was_surface = s->surface_picture.has_value();
s->DetachDecoderSurface();
if ((size_changed || was_surface) &&
ANativeWindow_setBuffersGeometry(s->window, w, h, WINDOW_FORMAT_RGBA_8888) != 0) return;
ANativeWindow_Buffer buffer{};
if (ANativeWindow_lock(s->window, &buffer, nullptr) != 0) return;
const bool rendered = buffer.width == static_cast<int>(w) && buffer.height == static_cast<int>(h) &&
libyuv::NV12ToABGR(picture.Y(), picture.YStride(), picture.UV(), picture.UVStride(),
static_cast<uint8_t*>(buffer.bits), buffer.stride * 4, w, h) == 0;
if (ANativeWindow_unlockAndPost(s->window) != 0 || !rendered) return;
}
if (size_changed) {
s->width = w; s->height = h;
s->Event(5, {{"width", w}, {"height", h}});
}
// Measure through display submission, using MiniRTC's calibrated capture clock.
const auto now = GetSystemTimeMicros(s->controller);
const double latency = android_controller::VideoLatencyMilliseconds(
picture.captured_us, picture.received_us, now);
Environment scope;
if (scope.env) {
scope.env->CallVoidMethod(s->owner, s->frame_method, static_cast<jlong>(++s->frame_id), latency, static_cast<jint>(w), static_cast<jint>(h));
if (scope.env->ExceptionCheck()) scope.env->ExceptionClear();
}
}
Params Parameters(Session* s, bool controller) {
Params p{};
std::snprintf(p.signal_server_ip, sizeof(p.signal_server_ip), "%s", s->host.c_str());
std::snprintf(p.log_path, sizeof(p.log_path), "%s", s->log_path.c_str());
p.signal_server_port = s->port;
p.hardware_acceleration = true;
// MediaCodec returns retained Surface buffers; software fallback returns
// pooled CPU NV12 with the same ownership contract.
p.native_video_output = controller;
p.turn_mode = TurnAutoUdpTcp;
p.enable_srtp = true;
p.video_content_type = VideoContentType::ScreenContent;
p.video_quality = QualityMedium;
p.video_frame_rate = 30;
p.video_degradation_preference = VideoDegradationPreference::Balanced;
p.on_signal_status = Signal; p.on_connection_status = Connection;
p.on_signal_message = SignalMessage;
p.on_net_status_report = Network; p.on_receive_data_buffer = Data;
p.on_receive_video_frame = Video; p.on_receive_audio_buffer = Audio;
p.user_id = (controller ? s->controller_login : s->identity_login).c_str();
p.user_data = controller ? &s->controller_context : &s->identity_context;
return p;
}
Session* From(jlong handle) { return reinterpret_cast<Session*>(handle); }
} // namespace
extern "C" JNIEXPORT jint JNI_OnLoad(JavaVM* java_vm, void*) {
vm = java_vm;
minirtc::android::SetJavaVm(java_vm);
return JNI_VERSION_1_6;
}
#define JNI_METHOD(name) Java_cn_crossdesk_mobile_NativeSession_##name
extern "C" JNIEXPORT jboolean JNICALL JNI_METHOD(nValidAppVersion)(
JNIEnv* env, jclass, jstring version) {
return version && env->GetStringUTFLength(version) < 64 &&
crossdesk::IsValidAppVersion(String(env, version));
}
extern "C" JNIEXPORT jboolean JNICALL JNI_METHOD(nHasAppUpdate)(
JNIEnv* env, jclass, jstring version, jbyteArray release_json) {
if (!release_json) return false;
const auto size = env->GetArrayLength(release_json);
if (size <= 0 || size > 256 * 1024) return false;
std::string data(size, '\0');
env->GetByteArrayRegion(release_json, 0, size, reinterpret_cast<jbyte*>(data.data()));
if (env->ExceptionCheck()) return false;
const auto latest = crossdesk::ParseVersionInfoJSON(data);
return latest && crossdesk::AvailableAppUpdate(String(env, version), *latest).has_value();
}
extern "C" JNIEXPORT jstring JNICALL JNI_METHOD(nCheckMobileUpdate)(
JNIEnv* env, jclass, jstring version, jbyteArray release_json) {
if (!version || !release_json) return nullptr;
const auto size = env->GetArrayLength(release_json);
if (size <= 0 || size > 256 * 1024) return nullptr;
std::string data(size, '\0');
env->GetByteArrayRegion(release_json, 0, size, reinterpret_cast<jbyte*>(data.data()));
if (env->ExceptionCheck()) return nullptr;
const auto result = crossdesk::CheckPlatformAppUpdate(
String(env, version), data, "android-arm64");
return result ? env->NewStringUTF(result->c_str()) : nullptr;
}
extern "C" JNIEXPORT jlong JNICALL JNI_METHOD(nCreate)(
JNIEnv* env, jclass, jobject owner, jstring host, jint port, jstring identity,
jstring log_path, jstring certificates) {
try {
auto s = std::make_unique<Session>();
s->owner = env->NewGlobalRef(owner);
auto cls = env->GetObjectClass(owner);
s->event_method = env->GetMethodID(cls, "onNativeEvent", "(I[B)V");
s->audio_method = env->GetMethodID(cls, "onNativeAudio", "([B)V");
s->frame_method = env->GetMethodID(cls, "onNativeVideoFrame", "(JDII)V");
env->DeleteLocalRef(cls);
s->host = String(env, host); s->port = port;
s->identity_login = String(env, identity); s->log_path = String(env, log_path);
// The bundle is exported from Android's default TrustManager, never the
// build machine's certificate store. MiniRTC on Android explicitly
// loads this path: OpenSSL's default loader ignores SSL_CERT_FILE in an
// Android app process (AT_SECURE=1). Chain and hostname checks stay enabled.
const auto bundle = String(env, certificates);
if (bundle.empty() || setenv("SSL_CERT_FILE", bundle.c_str(), 1) != 0)
throw std::runtime_error("Unable to configure Android trust bundle");
// MiniRTC's diagnostic log includes login identities. Keep credentials
// solely in Keystore-backed storage; do not persist its session logging.
minirtc::InitLogger(s->log_path);
minirtc::get_logger()->set_level(spdlog::level::off);
auto params = Parameters(s.get(), false);
s->identity = CreatePeer(&params);
if (!s->identity || Init(s->identity) != 0) return 0;
return reinterpret_cast<jlong>(s.release());
} catch (const std::exception&) { return 0; }
}
extern "C" JNIEXPORT jboolean JNICALL JNI_METHOD(nConnect)(
JNIEnv* env, jclass, jlong handle, jstring identity, jstring remote, jstring password) {
auto* s = From(handle);
if (!s || s->controller) return false;
s->controller_login = "C-" + String(env, identity);
s->remote = String(env, remote);
auto params = Parameters(s, true);
s->controller = CreatePeer(&params);
if (!s->controller) return false;
AddAudioStream(s->controller, kAudioStream);
AddDataStream(s->controller, kDataStream, false);
for (const char* name : {kMouseStream, kKeyboardStream, kControlStream,
kClipboardStream, kFileStream, kFileFeedbackStream}) AddDataStream(s->controller, name, true);
if (Init(s->controller) != 0) return false;
const auto join = s->remote + "@" + String(env, password);
return JoinConnection(s->controller, join.c_str()) == 0;
}
extern "C" JNIEXPORT void JNICALL JNI_METHOD(nReady)(JNIEnv*, jclass, jlong handle) {
auto* s = From(handle); if (!s || !s->controller) return;
auto action = MakeHostInformation("CrossDesk Android", {}, false, "1.6.0", HostPlatform::Android);
s->Send(kControlStream, action.to_json()); FreeRemoteAction(action);
}
extern "C" JNIEXPORT void JNICALL JNI_METHOD(nPointer)(
JNIEnv*, jclass, jlong handle, jfloat x, jfloat y, jint flag, jint wheel) {
auto* s = From(handle); if (!s || flag < 0 || flag > 8) return;
RemoteAction action{}; action.type = mouse;
action.m = {std::clamp(x, 0.f, 1.f), std::clamp(y, 0.f, 1.f), wheel, static_cast<MouseFlag>(flag)};
s->pointer_x = action.m.x; s->pointer_y = action.m.y;
if (flag >= 1 && flag <= 6) {
const unsigned bit = 1u << ((flag - 1) / 2);
if (flag & 1) s->pressed_buttons |= bit; else s->pressed_buttons &= ~bit;
}
s->Send(kMouseStream, action.to_json());
}
extern "C" JNIEXPORT void JNICALL JNI_METHOD(nKey)(JNIEnv*, jclass, jlong handle, jint key, jboolean down) {
auto* s = From(handle); if (!s) return;
RemoteAction action{}; action.type = keyboard;
action.k = {static_cast<size_t>(key), 0, false, down ? key_down : key_up};
if (down) s->pressed_keys.insert(key); else s->pressed_keys.erase(key);
s->Send(kKeyboardStream, action.to_json());
}
extern "C" JNIEXPORT void JNICALL JNI_METHOD(nControl)(
JNIEnv*, jclass, jlong handle, jint type, jint value) {
auto* s = From(handle); if (!s) return;
RemoteAction action{};
if (type == display_id && value >= 0 && value < 8) {
{ std::lock_guard<std::mutex> lock(s->render_mutex); s->display = value; ++s->video_generation; s->renderer.Clear(); s->DetachDecoderSurface(); s->width = s->height = 0; }
action.type = display_id; action.d = value;
} else if (type == audio_capture) {
action.type = audio_capture; action.a = value != 0;
} else return;
s->Send(kControlStream, action.to_json());
}
extern "C" JNIEXPORT jboolean JNICALL JNI_METHOD(nVideoSettings)(
JNIEnv*, jclass, jlong handle, jint quality, jint rate, jint preference, jlong request_id) {
auto* s = From(handle);
if (!s || !s->controller || s->stopping || request_id < 0 || request_id > UINT32_MAX) return false;
const auto data = android_controller::VideoSettingsMessage(quality, rate, preference, static_cast<uint32_t>(request_id));
if (data.empty()) return false;
return SendReliableDataFrame(s->controller, data.data(), data.size(), kControlStream) == 0;
}
extern "C" JNIEXPORT jboolean JNICALL JNI_METHOD(nSecureAttention)(JNIEnv*, jclass, jlong handle) {
auto* s = From(handle);
if (!s || !s->controller || s->stopping) return false;
const auto data = android_controller::SecureAttentionMessage();
return SendReliableDataFrame(s->controller, data.data(), data.size(), kControlStream) == 0;
}
extern "C" JNIEXPORT void JNICALL JNI_METHOD(nFileDirectory)(JNIEnv* env, jclass, jlong handle, jstring directory) {
auto* s = From(handle); if (s) s->files.SetDirectory(String(env, directory));
}
extern "C" JNIEXPORT jboolean JNICALL JNI_METHOD(nSendFile)(JNIEnv* env, jclass, jlong handle, jstring path, jbyteArray name) {
auto* s = From(handle);
if (!s || !s->controller || s->stopping || !name) return false;
const auto size = env->GetArrayLength(name);
if (!size || size > UINT16_MAX) return false;
std::string label(size, '\0');
env->GetByteArrayRegion(name, 0, size, reinterpret_cast<jbyte*>(label.data()));
return !env->ExceptionCheck() && s->files.Start(String(env, path), label);
}
extern "C" JNIEXPORT jboolean JNICALL JNI_METHOD(nPumpFiles)(JNIEnv*, jclass, jlong handle) {
auto* s = From(handle);
if (!s || s->stopping) return false;
s->files.Pump();
return s->files.Sending();
}
extern "C" JNIEXPORT jboolean JNICALL JNI_METHOD(nAnnouncementRequest)(
JNIEnv* env, jclass, jlong handle, jbyteArray data) {
auto* s = From(handle);
if (!s || !s->identity || s->stopping || !data) return false;
const auto size = env->GetArrayLength(data);
if (size <= 0 || size > 4096) return false;
std::string bytes(size, '\0');
env->GetByteArrayRegion(data, 0, size, reinterpret_cast<jbyte*>(bytes.data()));
if (env->ExceptionCheck()) return false;
auto message = json::parse(bytes, nullptr, false);
if (!message.is_object() || !message.contains("type") ||
!message["type"].is_string() || message["type"] != "announcements_list") return false;
return SendSignalMessage(s->identity, bytes.data(), bytes.size()) == 0;
}
extern "C" JNIEXPORT jboolean JNICALL JNI_METHOD(nPresenceRequest)(
JNIEnv* env, jclass, jlong handle, jbyteArray data) {
auto* s = From(handle);
if (!s || !s->identity || s->stopping || !data) return false;
const auto size = env->GetArrayLength(data);
if (size <= 0 || size > 4096) return false;
std::string bytes(size, '\0');
env->GetByteArrayRegion(data, 0, size, reinterpret_cast<jbyte*>(bytes.data()));
if (env->ExceptionCheck()) return false;
auto message = json::parse(bytes, nullptr, false);
if (!message.is_object() || !message.contains("type") || !message["type"].is_string() ||
message["type"] != "recent_connections_presence" ||
!message.contains("user_id") || !message["user_id"].is_string() ||
!message.contains("devices") || !message["devices"].is_array() ||
!message.contains("subscribe") || message["subscribe"] != true) return false;
return SendSignalMessage(s->identity, bytes.data(), bytes.size()) == 0;
}
extern "C" JNIEXPORT void JNICALL JNI_METHOD(nClipboard)(
JNIEnv* env, jclass, jlong handle, jbyteArray data) {
auto* s = From(handle); if (!s || !data) return;
const auto size = env->GetArrayLength(data);
if (!size || size > static_cast<int>(kMaxClipboardBytes)) return;
std::string bytes(size, '\0');
env->GetByteArrayRegion(data, 0, size, reinterpret_cast<jbyte*>(bytes.data()));
s->Send(kClipboardStream, bytes);
}
extern "C" JNIEXPORT void JNICALL JNI_METHOD(nSurface)(JNIEnv* env, jclass, jlong handle, jobject surface) {
if (auto* s = From(handle)) {
s->Surface(env, surface);
if (surface && s->controller && !s->stopping)
RequestVideoKeyFrame(s->controller, MakeDisplayStreamId(s->display.load()).c_str());
}
}
extern "C" JNIEXPORT void JNICALL JNI_METHOD(nDestroy)(JNIEnv*, jclass, jlong handle) { delete From(handle); }
+80
View File
@@ -0,0 +1,80 @@
/*
* @Author: DI JUNKUN
* @Date: 2026-10-02
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
*/
#ifndef _VIDEO_PICTURE_H_
#define _VIDEO_PICTURE_H_
#include <minirtc.h>
#include <climits>
#include <cstring>
#include <memory>
#include <optional>
#include <vector>
namespace crossdesk::android_controller {
struct VideoPicture {
uint32_t width, height;
uint64_t captured_us, received_us, generation;
std::vector<uint8_t> pixels;
std::shared_ptr<void> native_owner;
MiniRtcCpuNv12Frame planes{};
MiniRtcAndroidMediaCodecFrame media_codec{};
bool IsSurface() const { return media_codec.render && native_owner; }
int RenderSurface(void* window) const {
return IsSurface() ? media_codec.render(native_owner.get(), window) : -1;
}
const uint8_t* Y() const { return native_owner ? planes.y_plane : pixels.data(); }
const uint8_t* UV() const { return native_owner ? planes.uv_plane : pixels.data() + size_t(width) * height; }
int YStride() const { return native_owner ? planes.y_stride : width; }
int UVStride() const { return native_owner ? planes.uv_stride : width; }
static std::optional<VideoPicture> RetainOrCopy(const MiniRtcVideoFrame& frame,
uint64_t generation) {
const auto w = frame.width, h = frame.height;
if (!w || !h || w > 8192 || h > 8192 || (w & 1) || (h & 1) ||
static_cast<uint64_t>(w) * h > 33554432) return std::nullopt;
VideoPicture result{w, h, frame.captured_timestamp, frame.received_timestamp,
generation, {}, {}, {}, {}};
const auto* native = frame.native_frame;
const bool valid_native = native && native->struct_size >= sizeof(*native) &&
native->width == w && native->height == h && native->owner;
if (valid_native && native->type == MiniRtcNativeVideoFrameAndroidMediaCodec &&
native->retain && native->release && native->payload.android_media_codec.render) {
native->retain(native->owner);
result.native_owner = std::shared_ptr<void>(native->owner, native->release);
result.media_codec = native->payload.android_media_codec;
return result;
}
if (valid_native && native->type == MiniRtcNativeVideoFrameCpuNv12 &&
native->retain && native->release) {
const auto& planes = native->payload.cpu_nv12;
if (planes.y_plane && planes.uv_plane && planes.y_stride >= w &&
planes.uv_stride >= w && planes.y_stride <= INT_MAX && planes.uv_stride <= INT_MAX) {
native->retain(native->owner);
result.native_owner = std::shared_ptr<void>(native->owner, native->release);
result.planes = planes;
return result;
}
}
const size_t size = size_t(w) * h * 3 / 2;
if (frame.data && frame.size >= size) {
result.pixels.resize(size);
std::memcpy(result.pixels.data(), frame.data, size);
} else if (valid_native && native->copy_to_nv12) {
result.pixels.resize(size);
if (native->copy_to_nv12(native->owner, result.pixels.data(), size) != 0)
return std::nullopt;
} else {
return std::nullopt;
}
return result;
}
};
} // namespace crossdesk::android_controller
#endif
+27
View File
@@ -0,0 +1,27 @@
/*
* @Author: DI JUNKUN
* @Date: 2026-10-02
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
*/
#ifndef _VIDEO_TIMING_H_
#define _VIDEO_TIMING_H_
#include <cstdint>
namespace crossdesk::android_controller {
inline double VideoLatencyMilliseconds(uint64_t captured_us,
uint64_t received_us,
int64_t submitted_us) {
// MiniRTC calibrates capture time when the frame is reassembled. Validate
// that mapping at reception, not after decoding/Surface waits: a real local
// backlog over five seconds must remain visible in the latency measurement.
if (!captured_us || received_us < captured_us || submitted_us <= 0 ||
received_us > static_cast<uint64_t>(submitted_us) ||
received_us - captured_us > 5'000'000)
return -1;
return (static_cast<uint64_t>(submitted_us) - captured_us) / 1000.0;
}
} // namespace crossdesk::android_controller
#endif
+19
View File
@@ -0,0 +1,19 @@
set_project("crossdesk_android")
set_xmakever("3.1.1")
set_languages("c++17")
add_rules("mode.release", "mode.debug")
set_policy("package.precompiled", false)
add_cxflags("-fPIC")
includes("../../../deps/submodules/minirtc")
target("crossdesk_android")
set_kind("shared")
add_deps("minirtc")
add_packages("nlohmann_json", "libyuv", "spdlog")
add_files("rtc_bridge.cpp", "../../../libs/wire/src/remote_action.cpp", "../../../libs/wire/src/app_version.cpp", "../../../libs/wire/src/file_transfer.cpp")
add_includedirs("../../../deps/submodules/minirtc/src/api", "../../../libs/wire/include")
-- This source-level JNI adapter is the only application layer using MiniRTC internals.
add_includedirs("../../../deps/submodules/minirtc/src/media/mediacodec")
add_syslinks("android", "log")
add_shflags("-Wl,-z,max-page-size=16384", "-Wl,-z,common-page-size=16384", {force = true})
set_targetdir("../app/build/native/arm64-v8a")
+64
View File
@@ -0,0 +1,64 @@
#!/usr/bin/env python3
"""Build the native controller in isolation from desktop and iOS caches."""
import fcntl
import os
from pathlib import Path
import shutil
import subprocess
import re
ANDROID = Path(__file__).resolve().parents[1]
ROOT = ANDROID.parents[1]
SOURCE = ROOT / 'deps/submodules/minirtc'
CACHE = ANDROID / '.native'
PACKAGE_REVISION = 'eda39de3fb99b420c168f1ab9ab2d1791e11b662'
XMAKE_MIN_VERSION = (3, 1, 1)
def find_xmake():
xmake = os.environ.get('XMAKE_BIN') or shutil.which('xmake')
minimum = '.'.join(map(str, XMAKE_MIN_VERSION))
if not xmake:
raise SystemExit(f'Xmake {minimum} or newer is required; install it or set XMAKE_BIN.')
output = subprocess.check_output([xmake, '--version'], text=True)
version = re.search(r'xmake v(\d+)\.(\d+)\.(\d+)(?:\+|[,\s]|$)', output)
if not version or tuple(map(int, version.groups())) < XMAKE_MIN_VERSION:
raise SystemExit(f'Use Xmake {minimum} or newer (set XMAKE_BIN to its executable).')
return xmake
def main():
sdk = Path(os.environ.get('ANDROID_HOME') or os.environ.get('ANDROID_SDK_ROOT')
or Path.home() / 'Library/Android/sdk')
ndk = sdk / 'ndk/28.2.13676358'
if not ndk.is_dir():
raise SystemExit('Install Android NDK 28.2.13676358 using SDK Manager.')
xmake = find_xmake()
if not (SOURCE / 'xmake.lua').is_file():
raise SystemExit('Initialize the MiniRTC submodule before building.')
env = os.environ.copy()
env['XMAKE_PKG_INSTALLDIR'] = str(CACHE / 'packages')
env['XMAKE_GLOBALDIR'] = str(CACHE / 'global')
env['ANDROID_NDK_HOME'] = str(ndk)
env['ANDROID_NDK_ROOT'] = str(ndk)
env['NO_COLOR'] = '1'
work = ANDROID / 'native'
repository = CACHE / 'global/.xmake/repositories/xmake-repo'
if not (repository / '.git').is_dir():
subprocess.run([xmake, 'repo', '--update'], cwd=work, env=env, check=True)
revision = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repository, text=True).strip()
if revision != PACKAGE_REVISION:
subprocess.run(['git', 'fetch', 'origin', PACKAGE_REVISION], cwd=repository, check=True)
subprocess.run(['git', 'checkout', '--detach', PACKAGE_REVISION], cwd=repository, check=True)
subprocess.run([xmake, 'f', '-P', str(work), '-y', '-p', 'android', '-a', 'arm64-v8a',
'-m', 'release', '--ndk=' + str(ndk), '--ndk_sdkver=26',
'--runtimes=c++_static', '--policies=package.precompiled:n',
'-o', str(CACHE / 'build')], cwd=work, env=env, check=True)
subprocess.run([xmake, '-P', str(work), '-y', 'crossdesk_android'], cwd=work, env=env, check=True)
if __name__ == '__main__':
CACHE.mkdir(parents=True, exist_ok=True)
with (CACHE / 'build.lock').open('w') as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
main()
+132
View File
@@ -0,0 +1,132 @@
#!/usr/bin/env python3
"""Package existing reviewed notices for the Android runtime dependency set."""
import json
import hashlib
import os
from pathlib import Path
import subprocess
from urllib.parse import quote
ANDROID = Path(__file__).resolve().parents[1]
ROOT = ANDROID.parents[1]
COMPONENTS = {
'asio', 'concurrentqueue', 'dav1d', 'glib', 'inih', 'nlohmann_json',
'kcp', 'libdatachannel', 'libffi', 'libnice', 'libsrtp', 'libyuv',
'minirtc', 'openfec', 'openssl3', 'libopus', 'pcre2', 'plog',
'proxy-libintl', 'spdlog', 'svt-av1', 'usrsctp', 'webrtc', 'websocketpp', 'zlib',
}
def git(*args, cwd=ROOT):
return subprocess.check_output(['git', *args], cwd=cwd, text=True).strip()
def write_pages(output, catalog, additional, revision, minirtc):
"""Small navigation catalog and separate, offline-selectable license documents."""
source = f'https://github.com/kunkundi/crossdesk/tree/{revision}'
mini_source = f'https://github.com/kunkundi/minirtc/tree/{minirtc}'
components = []
for entry in catalog['components']:
if entry['id'] not in COMPONENTS | {'crossdesk'}:
continue
component = dict(entry)
if component['id'] == 'crossdesk':
component['sourceURL'] = source
component['documents'] = [
{'title': 'LICENSE', 'text': (ROOT / 'LICENSE').read_text()},
{'title': 'apps/android/licenses/OPEN_SOURCE_NOTICE.txt',
'text': (ANDROID / 'licenses/OPEN_SOURCE_NOTICE.txt').read_text()},
]
if component['id'] in {'minirtc', 'inih', 'webrtc'}:
component.update(version=minirtc, sourceURL=mini_source)
if '/thirdparty/' in component.get('buildSourceURL', ''):
recipe = component['buildSourceURL'].split('/thirdparty/', 1)[1]
component['buildSourceURL'] = f'{mini_source}/thirdparty/{recipe}'
components.append(component)
components += additional
# Ship the actual build instructions and recipes used by this local build. The Android
# directory may not exist at the public base commit of an unpublished checkout.
bundled = [
('构建说明', ANDROID / 'README.md'),
('原生构建配方', ANDROID / 'native/xmake.lua'),
('OpenSSL 构建配方', ROOT / 'deps/submodules/minirtc/thirdparty/openssl/xmake.lua'),
('MiniRTC 构建配方', ROOT / 'deps/submodules/minirtc/xmake.lua'),
('原生构建脚本', ANDROID / 'scripts/build_native.py'),
('SVT-AV1 构建配方', ROOT / 'deps/submodules/minirtc/thirdparty/svt-av1/xmake.lua'),
]
build_documents = []
for index, (title, path) in enumerate(bundled):
asset = f'about/build/{index}.txt'
target = output / asset
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(path.read_text(), encoding='utf-8')
build_documents.append({'title': title, 'asset': asset})
for component in components:
if component['id'] in {'minirtc', 'glib', 'libnice', 'openfec', 'openh264', 'openssl3', 'svt-av1'}:
component['buildDocuments'] = build_documents[1:]
documents = []
for index, document in enumerate(component['documents']):
asset = f"about/licenses/{component['id']}/{index}.txt"
target = output / asset
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(document['text'], encoding='utf-8')
documents.append({'title': document['title'], 'asset': asset,
'sha256': hashlib.sha256(document['text'].encode('utf-8')).hexdigest()})
component['documents'] = documents
(output / 'ThirdPartyLicenses.json').write_text(json.dumps(
{'schemaVersion': 1, 'components': components}, ensure_ascii=False, indent=2)+'\n', encoding='utf-8')
tags = git('tag', '--points-at', 'HEAD').splitlines()
tag = os.environ.get('CROSSDESK_SOURCE_TAG')
if tag and tag not in tags:
raise ValueError(f'Source tag {tag!r} does not point to the build commit')
if not tag:
versions = sorted(value for value in tags if value.startswith(('v', 'android-v')))
tag = versions[0] if versions else None
dirty = bool(git('status', '--porcelain', '--untracked-files=normal', '--ignore-submodules=none'))
if os.environ.get('CROSSDESK_RELEASE_BUILD') == 'YES' and (dirty or not tag or not tag.startswith(('v', 'android-v'))):
raise ValueError('Release source must be a clean checkout of a version tag, with matching submodules')
metadata = {
'schemaVersion': 1, 'revision': revision, 'tag': tag,
'isModified': dirty,
'sourceURL': source,
'buildInstructionsURL': f'https://github.com/kunkundi/crossdesk/blob/{quote(revision, safe="")}/apps/android/README.md',
'buildDocuments': build_documents, 'miniRTCRevision': minirtc,
}
(output / 'SourceMetadata.json').write_text(json.dumps(metadata, ensure_ascii=False, indent=2)+'\n', encoding='utf-8')
def main():
output = ANDROID / 'app/build/generated/notices'
output.mkdir(parents=True, exist_ok=True)
(output / 'PRIVACY.md').write_text((ROOT / 'PRIVACY.md').read_text(encoding='utf-8'), encoding='utf-8')
catalog = json.loads((ROOT / 'apps/ios/CrossDeskMobile/Resources/ThirdPartyLicenses.json').read_text())
revision = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip()
minirtc = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT / 'deps/submodules/minirtc', text=True).strip()
parts = [
'CrossDesk Android — open-source notices\n',
'CrossDesk: GPL-3.0-only; MiniRTC: LGPL-3.0-only. Other components retain their own licenses.\n'
'Open-source licenses govern use, modification and redistribution; their warranty limitations apply.\n'
'You can rebuild/relink modified libraries and install an APK signed with your own key.\n',
f'Application base revision: {revision}\nMiniRTC base revision: {minirtc}\n'
'This development build may contain local changes in CrossDesk and the MiniRTC submodule.\n'
'Source: https://github.com/kunkundi/crossdesk\n'
'Build: apps/android/README.md; native source: deps/submodules/minirtc\n',
(ROOT / 'LICENSE').read_text(),
]
for component in catalog['components']:
if component['id'] not in COMPONENTS:
continue
parts.append(f"\n{component['name']} — {component['license']}\n{component['sourceURL']}\n")
for document in component['documents']:
parts.extend([document['title'], document['text']])
additional = json.loads((ANDROID / 'licenses/additional-notices.json').read_text())
for component in additional:
parts.append(component['name']+' '+component['version'])
for document in component['documents']:
parts.extend([document['title'], document['text']])
(output / 'THIRD_PARTY_NOTICES.txt').write_text('\n\n'.join(parts), encoding='utf-8')
write_pages(output, catalog, additional, revision, minirtc)
if __name__ == '__main__':
main()
+67
View File
@@ -0,0 +1,67 @@
#!/usr/bin/env python3
"""Resolve Android package and artifact versions before building the APKs."""
import datetime
import os
from pathlib import Path
import re
from zoneinfo import ZoneInfo
def resolve_version(version_name, version_code, tag="", patch="0", today=None):
build_date = today or datetime.datetime.now(ZoneInfo("Asia/Shanghai")).strftime("%Y%m%d")
patch = patch if re.fullmatch(r"[0-9]+", patch) else "0"
if tag:
independent = tag.startswith("android-v")
source_version = tag.removeprefix("android-")
base = r"(?P<base>[0-9]+\.[0-9]+\.[0-9]+)"
for pattern in (
rf"v{base}-(?P<patch>[0-9]+)-(?P<date>[0-9]{{8}})",
rf"v{base}-(?P<date>[0-9]{{8}})(?:-(?P<patch>[0-9]+))?",
rf"v{base}(?:-(?P<patch>[0-9]+))?",
):
match = re.fullmatch(pattern, source_version)
if match:
fields = match.groupdict()
if independent and fields["base"] != version_name:
raise ValueError(f"Android source tag does not match the app version: {tag} vs {version_name}")
version_name = fields["base"]
build_date = fields.get("date") or build_date
patch = fields.get("patch") or patch
break
else:
raise ValueError(f"Invalid Android release tag: {tag!r}")
if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", version_name):
raise ValueError(f"Invalid Android versionName: {version_name!r}")
if not re.fullmatch(r"[0-9]+", version_code) or not 0 < int(version_code) <= 2100000000:
raise ValueError(f"Invalid Android versionCode: {version_code!r}")
datetime.datetime.strptime(build_date, "%Y%m%d")
suffix = f"-{patch}" if patch != "0" else ""
artifact_version = f"v{version_name}{suffix}-{build_date}"
if tag.startswith("android-v") and tag.removeprefix("android-") != artifact_version:
raise ValueError(f"Android source tag does not match the artifact version: {tag} vs {artifact_version}")
return {"ANDROID_VERSION_NAME": version_name, "ANDROID_VERSION_CODE": str(int(version_code)),
"ANDROID_ARTIFACT_VERSION": artifact_version}
def main():
properties = dict(line.split("=", 1) for line in
(Path(__file__).resolve().parents[1] / "gradle.properties").read_text().splitlines()
if "=" in line and not line.lstrip().startswith("#"))
tag = os.environ.get("CROSSDESK_SOURCE_TAG", "")
if not tag and os.environ.get("GITHUB_REF_TYPE") == "tag":
ref_name = os.environ["GITHUB_REF_NAME"]
# Moving aliases such as "latest" are builds, not versioned releases.
if ref_name.startswith(("v", "android-v")):
tag = ref_name
values = resolve_version(properties["crossdeskVersionName"], properties["crossdeskVersionCode"],
tag, os.environ.get("PATCH_NUMBER", "0"))
text = "".join(f"{key}={value}\n" for key, value in values.items())
if os.environ.get("GITHUB_ENV"):
with open(os.environ["GITHUB_ENV"], "a") as stream:
stream.write(text)
print(text, end="")
if __name__ == "__main__":
main()
+7
View File
@@ -0,0 +1,7 @@
pluginManagement { repositories { google(); mavenCentral(); gradlePluginPortal() } }
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories { google(); mavenCentral() }
}
rootProject.name = 'CrossDeskAndroid'
include ':app'
@@ -0,0 +1,20 @@
-----BEGIN CERTIFICATE-----
MIIDLTCCAhWgAwIBAgIUAl+BaiMSPm1zRwBr0qnyzpufOaIwDQYJKoZIhvcNAQEL
BQAwJjEkMCIGA1UEAwwbQ3Jvc3NEZXNrIGxvY2FsIFRMUyB0ZXN0IENBMB4XDTI2
MTAwMTA4MjYyMVoXDTM2MDkyODA4MjYyMVowJjEkMCIGA1UEAwwbQ3Jvc3NEZXNr
IGxvY2FsIFRMUyB0ZXN0IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC
AQEAmEAURCIgoeNOGiXcII2v/0SEN8UJ3ItdQrU4A5jOQe2fD12mjOJsQAUQrq/j
Bpz3cglAafJlOusgHqYyhFjHn58yZ1I+Z1jPa2CKeyWFYnmFUoL2yyNFmr3YMdkh
3caTehZ0+dit6bDYwTvhUwI9CFXLacAZ60tzvnPn+IHmszNNH89mgfr/aJcuXZb/
kSiJ/gUiiwp/PJznO9b0kjoJK6eZNoNNcqUyiVsBb0nL2+950GCbwvAA0px3PF/R
/qtNstkMPFB6WuMvw/DsxKFDZ8/XbfjJBXi0Rpr+DEW+BOadlTH6Q+CcKxC/YG6q
x2oxDGGr1Glz4SYE/OowCS7SaQIDAQABo1MwUTAdBgNVHQ4EFgQU9lut5DDz8k4A
MUDIioygb+l+z64wHwYDVR0jBBgwFoAU9lut5DDz8k4AMUDIioygb+l+z64wDwYD
VR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAJauLQRg5mnORh3fjenif
nGmHMOlvuBtOFdHGcUYyzkfPuRBp2rCd2mL2rdnJfcyZJAaWQhP9ZZtThbioczTj
Kf8UUTv2WYLKIWcZ1jyEEmukBhYxRpUfn4FqQG1yCqmF112coSCCY+7aGjl/Tcnx
E5SKS/FhARnXwObBaiG4sZoOQ4fbC70I94xfY8uSu6h9uVnnZS05tVbUD2gATn57
1snZUoJYTHi15QPZM3H/UViSYq2Inkw9yOcV3FRs6f8klePGVmUUDvT+I48jGjSz
cg2zgNErBYvLEJ8FxHX5oxJZzVZAuVxugYu1Ru5kEl1XO1GRHRf4/8JIl1nyat0a
hQ==
-----END CERTIFICATE-----
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,71 @@
package cn.crossdesk.mobile;
import androidx.test.platform.app.InstrumentationRegistry;
import org.json.*;
import org.junit.*;
import java.io.File;
import java.nio.file.Files;
import java.util.*;
import java.util.concurrent.FutureTask;
import static org.junit.Assert.*;
public class AnnouncementInboxTest {
private AnnouncementInbox inbox;
private File directory;
private final ArrayDeque<JSONObject> sent=new ArrayDeque<>();
private interface Checked { void run() throws Exception; }
private void main(Checked action)throws Exception {
FutureTask<Void> task=new FutureTask<>(()->{action.run();return null;});
InstrumentationRegistry.getInstrumentation().runOnMainSync(task);task.get();
}
@Before public void setup()throws Exception {
directory=Files.createTempDirectory(InstrumentationRegistry.getInstrumentation().getTargetContext().getCacheDir().toPath(),"announcements-").toFile();
main(()->{inbox=new AnnouncementInbox(directory);inbox.sender=(message,id)->sent.add(message);inbox.configure("Example.test.",9099,"123456789");inbox.setConnected(true);});
}
@After public void cleanup()throws Exception {
main(()->inbox.close());
try(var paths=Files.walk(directory.toPath())){for(var path:paths.sorted(Comparator.reverseOrder()).toList())Files.delete(path);}
}
private static JSONObject answer(JSONObject request,int count,long revision)throws Exception {
int offset=request.getInt("offset");boolean summary=request.getBoolean("summary_only");JSONArray items=new JSONArray();
for(int i=offset;i<Math.min(count,offset+(summary?200:20));i++){
JSONObject item=new JSONObject().put("id",i+1).put("revision",revision);
if(!summary)item.put("title",i==0?"欢迎使用 CrossDesk":"公告 "+(i+1)).put("body","安卓公告与 iOS 保持一致。\n\n访问 [CrossDesk 官网](https://crossdesk.cn) 了解更多。\n支持中文、换行与网页链接。").put("updated_at",1790812800L);
items.put(item);
}
return new JSONObject().put("type","announcements").put("request_id",request.getString("request_id"))
.put("summary_only",summary).put("offset",offset).put("total",count).put("catalog_revision",revision).put("items",items);
}
private void drain(int count,long revision)throws Exception {
int limit=100;while(!sent.isEmpty()){assertTrue("Request loop",limit-->0);inbox.receive(answer(sent.remove(),count,revision));}
}
@Test public void summariesCountAllUnreadAndBodiesPageInTwenties()throws Exception {main(()->{
JSONObject first=sent.remove();inbox.receive(answer(first,203,1));assertEquals(200,sent.peek().getInt("offset"));assertEquals(0,inbox.items.size());
inbox.receive(answer(sent.remove(),203,1));assertEquals(203,inbox.unread);assertFalse(sent.peek().getBoolean("summary_only"));
drain(203,1);assertEquals(20,inbox.items.size());assertEquals(203,inbox.total);assertFalse(inbox.loading);assertTrue(inbox.loaded);
inbox.loadMore();assertEquals(20,sent.peek().getInt("offset"));drain(203,1);assertEquals(40,inbox.items.size());
});}
@Test public void readAndDeletePersistPerRevisionAndScope()throws Exception {main(()->{
drain(3,1);inbox.markRead(inbox.items.get(0));inbox.dismiss(inbox.items.get(1));assertEquals(1,inbox.unread);assertEquals(2,inbox.total);
inbox.close();inbox=new AnnouncementInbox(directory);inbox.sender=(message,id)->sent.add(message);
inbox.configure("example.TEST",9099,"123456789");inbox.setConnected(true);drain(3,1);
assertEquals(2,inbox.items.size());assertTrue(inbox.items.get(0).read);assertEquals(1,inbox.unread);
inbox.refresh();drain(3,2);assertEquals(3,inbox.total);assertEquals(3,inbox.unread);assertEquals(3,inbox.items.size());
inbox.configure("other.test",9099,"123456789");drain(3,1);assertEquals(3,inbox.unread);
inbox.configure("example.test",9099,"different-device");drain(3,1);assertEquals(3,inbox.unread);
inbox.configure("example.test",9999,"123456789");drain(3,1);assertEquals(3,inbox.unread);
inbox.configure("example.test",9099,"123456789");drain(3,1);assertEquals(1,inbox.unread);
});}
@Test public void malformedResponseFailsWithoutLosingVisibleRowsAndCanRetry()throws Exception {main(()->{
drain(2,1);inbox.refresh();JSONObject invalid=answer(sent.remove(),2,1);invalid.put("total","2");inbox.receive(invalid);
assertTrue(inbox.failed);assertFalse(inbox.loading);assertEquals(2,inbox.items.size());
inbox.refresh();drain(2,2);assertFalse(inbox.failed);
inbox.refresh();JSONObject summary=answer(sent.remove(),2,3);summary.getJSONArray("items").getJSONObject(1).put("id",1);inbox.receive(summary);
assertTrue(inbox.failed);inbox.refresh();drain(2,3);assertFalse(inbox.failed);
inbox.refresh();inbox.receive(answer(sent.remove(),2,4));JSONObject body=answer(sent.remove(),2,4);
body.getJSONArray("items").getJSONObject(0).put("body","中".repeat(2667));inbox.receive(body);assertTrue(inbox.failed);assertEquals(0,inbox.items.size());
inbox.refresh();drain(2,4);assertFalse(inbox.failed);
});}
}
@@ -0,0 +1,180 @@
package cn.crossdesk.mobile;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.core.app.ActivityScenario;
import androidx.lifecycle.Lifecycle;
import androidx.test.platform.app.InstrumentationRegistry;
import android.app.Dialog;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import static org.junit.Assert.*;
@RunWith(AndroidJUnit4.class)
public class AppUpdateCheckerTest {
private static final class Fixture implements RemoteVersionCheck.Fetcher {
int cancelled;
final List<Consumer<byte[]>> replies = new ArrayList<>();
final AppUpdateChecker checker = new AppUpdateChecker("1.6.0", this,
(version, data) -> new String(data, StandardCharsets.UTF_8), () -> {});
public RemoteVersionCheck.Cancellation fetch(Consumer<byte[]> reply) {
replies.add(reply); return () -> cancelled++;
}
void reply(String result) { replies.get(replies.size()-1).accept(result == null ? null : result.getBytes(StandardCharsets.UTF_8)); }
}
@Test public void everyVisitChecksOnceAndConcurrentTriggersDeduplicate() {
Fixture f = new Fixture();
f.checker.checkNow(); assertTrue(f.replies.isEmpty());
f.checker.setEnabled(true); f.checker.checkNow(); f.checker.setEnabled(true);
assertEquals(1, f.replies.size());
f.reply("1.7.0"); assertTrue(f.checker.updateAvailable());
f.checker.setEnabled(true); assertEquals(1, f.replies.size());
f.checker.setEnabled(false); f.checker.setEnabled(true);
assertEquals(2, f.replies.size());
f.reply(""); assertFalse(f.checker.updateAvailable());
assertEquals(AppUpdateChecker.Status.UP_TO_DATE, f.checker.status);
f.checker.checkNow(); assertEquals(3, f.replies.size());
}
@Test public void failedChecksRetainBadgeUntilAnotherExplicitCheck() {
Fixture f = new Fixture(); f.checker.setEnabled(true); f.reply("1.7.0");
f.checker.checkNow(); f.reply(null);
assertEquals(AppUpdateChecker.Status.FAILED, f.checker.status);
assertTrue(f.checker.updateAvailable());
f.checker.setEnabled(true); assertEquals(2, f.replies.size());
f.checker.checkNow(); assertEquals(3, f.replies.size());
f.reply(""); assertFalse(f.checker.updateAvailable());
}
@Test public void backgroundAndRevocationCancelAndIgnoreStaleReplies() {
Fixture f = new Fixture(); f.checker.setEnabled(true); f.checker.setEnabled(false);
assertEquals(1, f.cancelled);
f.reply("9.0.0"); assertFalse(f.checker.updateAvailable());
f.checker.setEnabled(true); assertEquals(2, f.replies.size());
f.replies.get(0).accept("9.0.0".getBytes(StandardCharsets.UTF_8));
assertEquals(AppUpdateChecker.Status.CHECKING, f.checker.status);
f.reply("1.7.0"); f.checker.setEnabled(false); f.checker.checkNow();
assertEquals(2, f.replies.size()); f.checker.setEnabled(true);
assertEquals(3, f.replies.size()); assertTrue(f.checker.updateAvailable());
}
@Test public void nativeParserSeparatesMobileFromDesktopAndInvalidMetadata() {
byte[] manifest = "{\"latest_version\":\"99.0.0\",\"patch\":99,\"downloads\":{\"ios-arm64\":{\"version\":\"0.0.2\"},\"android-arm64\":{\"version\":\"1.6.0-2-20261002\"}}}".getBytes(StandardCharsets.UTF_8);
assertEquals("1.6.0-2", NativeSession.nCheckMobileUpdate("1.6.0", manifest));
assertEquals("", NativeSession.nCheckMobileUpdate("1.6.0-2", manifest));
assertEquals("", NativeSession.nCheckMobileUpdate("1.7.0", manifest));
assertNull(NativeSession.nCheckMobileUpdate("", manifest));
assertNull(NativeSession.nCheckMobileUpdate("1.6.0", "{\"version\":\"99.0.0\"}".getBytes(StandardCharsets.UTF_8)));
}
@Test public void settingsAndAboutReflectUpdatesWithoutReopeningThePage() {
Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
var preferences = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
boolean hadConsent = preferences.contains("networkConsent");
boolean consent = preferences.getBoolean("networkConsent", false);
preferences.edit().putBoolean("networkConsent", false).commit();
try (ActivityScenario<MainActivity> scenario = ActivityScenario.launch(MainActivity.class)) {
scenario.onActivity(activity -> {
((Dialog)field(activity, "privacyDialog")).dismiss();
List<Consumer<byte[]>> replies = new ArrayList<>();
AppUpdateChecker checker = new AppUpdateChecker("1.6.0",
reply -> { replies.add(reply); return () -> {}; },
(version, data) -> new String(data, StandardCharsets.UTF_8),
() -> invoke(activity, "renderAppUpdates"));
try {
var field = MainActivity.class.getDeclaredField("appUpdates");
field.setAccessible(true); field.set(activity, checker);
} catch (Exception error) { throw new AssertionError(error); }
assertEquals(View.GONE, ((View)field(activity, "settingsUpdateDot")).getVisibility());
checker.setEnabled(true);
replies.get(0).accept("1.7.0".getBytes(StandardCharsets.UTF_8));
assertEquals(View.VISIBLE, ((View)field(activity, "settingsUpdateDot")).getVisibility());
assertEquals("设置,有新版本", ((View)field(activity, "settingsUpdateButton")).getContentDescription());
((View)field(activity, "settingsUpdateButton")).performClick();
assertEquals(View.VISIBLE, ((View)field(activity, "aboutUpdateDot")).getVisibility());
((View)field(activity, "aboutUpdateRow")).performClick();
assertNotNull(findText(activity.getWindow().getDecorView(), "新版本可用:v1.7.0"));
checker.checkNow(); replies.get(1).accept(null);
assertNotNull(findText(activity.getWindow().getDecorView(), "新版本可用:v1.7.0"));
checker.checkNow(); replies.get(2).accept(new byte[0]);
invoke(activity, "settings");
assertEquals(View.GONE, ((View)field(activity, "aboutUpdateDot")).getVisibility());
checker.setEnabled(false);
});
} finally {
if (hadConsent) preferences.edit().putBoolean("networkConsent", consent).commit();
else preferences.edit().remove("networkConsent").commit();
}
}
@Test public void activityVisitsAndConnectionTeardownTriggerChecks() {
Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
var preferences = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
boolean hadConsent = preferences.contains("networkConsent");
boolean consent = preferences.getBoolean("networkConsent", false);
preferences.edit().putBoolean("networkConsent", false).commit();
Fixture f = new Fixture();
try (ActivityScenario<MainActivity> scenario = ActivityScenario.launch(MainActivity.class)) {
scenario.onActivity(activity -> {
((Dialog)field(activity, "privacyDialog")).dismiss();
try {
var field = MainActivity.class.getDeclaredField("appUpdates");
field.setAccessible(true); field.set(activity, f.checker);
} catch (Exception error) { throw new AssertionError(error); }
});
scenario.moveToState(Lifecycle.State.CREATED);
preferences.edit().putBoolean("networkConsent", true).commit();
scenario.moveToState(Lifecycle.State.RESUMED);
scenario.onActivity(activity -> {
assertEquals(1, f.replies.size()); f.reply("1.7.0");
endConnection(activity);
assertEquals(2, f.replies.size()); f.reply(null);
assertTrue(f.checker.updateAvailable());
endConnection(activity);
assertEquals(3, f.replies.size()); f.reply("");
assertFalse(f.checker.updateAvailable());
});
scenario.moveToState(Lifecycle.State.CREATED);
scenario.onActivity(activity -> {
endConnection(activity); assertEquals(3, f.replies.size());
});
scenario.moveToState(Lifecycle.State.RESUMED);
scenario.onActivity(activity -> assertEquals(4, f.replies.size()));
} finally {
if (hadConsent) preferences.edit().putBoolean("networkConsent", consent).commit();
else preferences.edit().remove("networkConsent").commit();
}
}
private static void endConnection(MainActivity activity) {
try {
var method = MainActivity.class.getDeclaredMethod("end", String.class);
method.setAccessible(true); method.invoke(activity, "");
} catch (Exception error) { throw new AssertionError(error); }
}
private static Object field(MainActivity activity, String name) {
try { var field = MainActivity.class.getDeclaredField(name); field.setAccessible(true); return field.get(activity); }
catch (Exception error) { throw new AssertionError(error); }
}
private static void invoke(MainActivity activity, String name) {
try { var method = MainActivity.class.getDeclaredMethod(name); method.setAccessible(true); method.invoke(activity); }
catch (Exception error) { throw new AssertionError(error); }
}
private static TextView findText(View view, String text) {
if (view instanceof TextView && ((TextView)view).getText().toString().equals(text)) return (TextView)view;
if (view instanceof ViewGroup) for (int i = 0; i < ((ViewGroup)view).getChildCount(); i++) {
TextView found = findText(((ViewGroup)view).getChildAt(i), text);
if (found != null) return found;
}
return null;
}
}
@@ -0,0 +1,120 @@
package cn.crossdesk.mobile;
import android.content.Context;
import android.view.KeyEvent;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.platform.app.InstrumentationRegistry;
import org.json.JSONObject;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.lang.reflect.Field;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.*;
@RunWith(AndroidJUnit4.class)
public class ControllerTest {
@Test public void presenceCallbacksRejectDisconnectedAndPreviousSignalingGeneration()throws Exception{
var instrumentation=InstrumentationRegistry.getInstrumentation();
var delivered=new java.util.concurrent.atomic.AtomicInteger();
NativeSession.Listener listener=new NativeSession.Listener(){
public void status(String value){}public void connected(){}public void ended(String reason){}
public void data(JSONObject value){}public void videoSize(int width,int height){}public void clipboard(String value){}public void statistics(RemoteNetworkStatistics.Snapshot value){}
public void presence(JSONObject value){delivered.incrementAndGet();}
};
NativeSession session=new NativeSession(instrumentation.getTargetContext(),"127.0.0.1",1,"","",listener);
Field workerField=NativeSession.class.getDeclaredField("RTC"),requestedField=NativeSession.class.getDeclaredField("presenceRequested");workerField.setAccessible(true);requestedField.setAccessible(true);
ExecutorService worker=(ExecutorService)workerField.get(null);
var event=NativeSession.class.getDeclaredMethod("onNativeEvent",int.class,byte[].class);event.setAccessible(true);
java.util.function.BiConsumer<Integer,String> send=(type,json)->{
try{event.invoke(session,type,json.getBytes(java.nio.charset.StandardCharsets.UTF_8));}catch(Exception error){throw new RuntimeException(error);}
};
try{
send.accept(1,"{\"controller\":false,\"status\":1,\"generation\":1}");
worker.submit(()->{requestedField.setBoolean(session,true);return null;}).get(5,TimeUnit.SECONDS);
send.accept(9,"{\"type\":\"presence\",\"devices\":[],\"generation\":1}");
worker.submit(()->{}).get(5,TimeUnit.SECONDS);instrumentation.waitForIdleSync();assertEquals(1,delivered.get());
send.accept(1,"{\"controller\":false,\"status\":4,\"generation\":2}");
send.accept(9,"{\"type\":\"presence\",\"devices\":[],\"generation\":1}");
send.accept(1,"{\"controller\":false,\"status\":1,\"generation\":3}");
worker.submit(()->{requestedField.setBoolean(session,true);return null;}).get(5,TimeUnit.SECONDS);
send.accept(9,"{\"type\":\"presence\",\"devices\":[],\"generation\":1}");
worker.submit(()->{}).get(5,TimeUnit.SECONDS);instrumentation.waitForIdleSync();assertEquals(1,delivered.get());
send.accept(1,"{\"controller\":false,\"status\":1,\"generation\":3}");
send.accept(9,"{\"type\":\"presence_update\",\"id\":\"123456789\",\"online\":true,\"generation\":3}");
worker.submit(()->{}).get(5,TimeUnit.SECONDS);instrumentation.waitForIdleSync();assertEquals("Repeated login readiness keeps the current subscription",2,delivered.get());
}finally{session.close();worker.submit(()->{}).get(5,TimeUnit.SECONDS);}
}
@Test public void repeatedNativeConnectedEventsNotifyAndInitializeOnlyOnce()throws Exception{
var instrumentation=InstrumentationRegistry.getInstrumentation();
var notifications=new java.util.concurrent.atomic.AtomicInteger();
NativeSession.Listener listener=new NativeSession.Listener(){
public void status(String value){}public void connected(){notifications.incrementAndGet();}public void ended(String reason){}
public void data(JSONObject value){}public void videoSize(int width,int height){}public void clipboard(String value){}public void statistics(RemoteNetworkStatistics.Snapshot value){}
};
NativeSession session=new NativeSession(instrumentation.getTargetContext(),"127.0.0.1",1,"123456789","test",listener);
Field workerField=NativeSession.class.getDeclaredField("RTC"),audioField=NativeSession.class.getDeclaredField("audio");workerField.setAccessible(true);audioField.setAccessible(true);
ExecutorService worker=(ExecutorService)workerField.get(null);
var event=NativeSession.class.getDeclaredMethod("onNativeEvent",int.class,byte[].class);event.setAccessible(true);
byte[] connected="{\"status\":1}".getBytes(java.nio.charset.StandardCharsets.UTF_8);
try{
// Exercise the Java native-callback path without starting a network peer.
event.invoke(session,2,connected);Object audio=worker.submit(()->audioField.get(session)).get(5,TimeUnit.SECONDS);
instrumentation.waitForIdleSync();assertEquals(1,notifications.get());assertNotNull(audio);
event.invoke(session,2,connected);event.invoke(session,2,connected);
assertSame("Duplicate readiness must not replace the audio player",audio,worker.submit(()->audioField.get(session)).get(5,TimeUnit.SECONDS));
instrumentation.waitForIdleSync();assertEquals("One desktop connection must notify the UI only once",1,notifications.get());
}finally{session.close();worker.submit(()->{}).get(5,TimeUnit.SECONDS);}
}
@Test public void keyboardSupportsDesktopVirtualKeys() {
assertEquals(0x41, KeyMap.windowsCode(KeyEvent.KEYCODE_A));
assertEquals(0x2E, KeyMap.windowsCode(KeyEvent.KEYCODE_FORWARD_DEL));
assertEquals(0x11, KeyMap.windowsCode(KeyEvent.KEYCODE_CTRL_LEFT));
assertEquals(0x5B, KeyMap.windowsCode(KeyEvent.KEYCODE_META_LEFT));
assertEquals(0xDB | 0x100, KeyMap.ascii('{'));
assertEquals(0x31 | 0x100, KeyMap.ascii('!'));
assertEquals(0, KeyMap.ascii('中'));
}
@Test public void credentialsRemainEncryptedAndServerScoped() throws Exception {
Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
SecretStore store = new SecretStore(context);
String scope = "instrumentation.invalid:9099";
try {
store.put(scope, "test-id@temporary-test-password");
assertEquals("test-id@temporary-test-password", store.get(scope));
assertEquals("", store.get("instrumentation.invalid:9100"));
String persisted = context.getSharedPreferences("identities", Context.MODE_PRIVATE).getString(scope, "");
assertFalse(persisted.contains("temporary-test-password"));
} finally {
context.getSharedPreferences("identities", Context.MODE_PRIVATE).edit().remove(scope).commit();
}
}
@Test public void nativePeerCanStartAndCancelRepeatedly() throws Exception {
Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
Field workerField = NativeSession.class.getDeclaredField("RTC"); workerField.setAccessible(true);
ExecutorService worker = (ExecutorService) workerField.get(null);
Field handleField = NativeSession.class.getDeclaredField("handle"); handleField.setAccessible(true);
NativeSession.Listener listener = new NativeSession.Listener() {
public void status(String value) { }
public void connected() { fail("Loopback port 1 must not establish a session"); }
public void ended(String reason) { }
public void data(JSONObject data) { }
public void videoSize(int width, int height) { }
public void clipboard(String value) { }
public void statistics(RemoteNetworkStatistics.Snapshot value) { }
};
for (int i = 0; i < 3; i++) {
NativeSession session = new NativeSession(context, "127.0.0.1", 1, "invalid", "test", listener);
session.start();
assertTrue(worker.submit(() -> handleField.getLong(session)).get(15, TimeUnit.SECONDS) != 0);
session.surface(null);
session.close(); session.close();
assertEquals(0L, (long) worker.submit(() -> handleField.getLong(session)).get(15, TimeUnit.SECONDS));
}
}
}
@@ -0,0 +1,24 @@
package cn.crossdesk.mobile;
import org.json.JSONObject;
import org.junit.Test;
import static org.junit.Assert.*;
public class NetworkStatisticsTest {
static JSONObject report(int mode,boolean srtp,double rtt)throws Exception{
return new JSONObject().put("mode",mode).put("srtp",srtp).put("rtt",rtt).put("video",traffic(8000000,0,.02)).put("audio",traffic(64000,0,.01)).put("data",traffic(2000,3000,.03)).put("total",traffic(8066000,3000,.06));
}
private static JSONObject traffic(long in,long out,double loss)throws Exception{return new JSONObject().put("inbound",in).put("outbound",out).put("loss",loss);}
@Test public void staleReportsAndRttExpireIndependently()throws Exception{
RemoteNetworkStatistics state=new RemoteNetworkStatistics();state.receive(new RemoteNetworkStatistics.Report(report(0,true,20)),10);state.receive(new RemoteNetworkStatistics.Report(report(0,true,100)),11);assertEquals(40,state.snapshot(11).rtt,.0001);
for(double invalid:new double[]{-1,2001})state.receive(new RemoteNetworkStatistics.Report(report(0,true,invalid)),12);
assertEquals(40,state.snapshot(13.99).rtt,.0001);assertTrue(Double.isNaN(state.snapshot(14).rtt));assertNotNull(state.snapshot(14).report);assertNull(state.snapshot(15).report);
state.receive(new RemoteNetworkStatistics.Report(report(0,true,0)),16);assertEquals(0,state.snapshot(16).rtt,0);
}
@Test public void submittedFramesAreCountedOnceAndIdleVideoExpires(){
RemoteNetworkStatistics state=new RemoteNetworkStatistics();state.frame(1,100,1920,1080,10);state.frame(1,100,1920,1080,10.1);state.frame(2,200,1920,1080,10.2);
assertEquals(2,state.snapshot(10.3).fps);assertEquals(150,state.snapshot(10.3).latency,.0001);assertEquals("1920 × 1080",state.snapshot(10.3).resolution());assertEquals(1,state.snapshot(11).fps);assertEquals(0,state.snapshot(11.3).fps);assertTrue(Double.isNaN(state.snapshot(11.3).latency));
}
}
@@ -0,0 +1,145 @@
package cn.crossdesk.mobile;
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
import androidx.lifecycle.Lifecycle;
import androidx.test.core.app.ActivityScenario;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.platform.app.InstrumentationRegistry;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.Map;
import static org.junit.Assert.*;
@RunWith(AndroidJUnit4.class)
public class PrivacyConsentTest {
private SharedPreferences preferences;
private Map<String,?> saved;
@Before public void prepare(){
Context context=InstrumentationRegistry.getInstrumentation().getTargetContext();
preferences=context.getSharedPreferences("settings",Context.MODE_PRIVATE);saved=preferences.getAll();
preferences.edit().remove("networkConsent").putString("host","127.0.0.1").putInt("port",1).commit();
}
@After public void restore(){
SharedPreferences.Editor edit=preferences.edit();
for(String key:new String[]{"networkConsent","host","port"}){
edit.remove(key);Object value=saved.get(key);
if(value instanceof Boolean)edit.putBoolean(key,(Boolean)value);
else if(value instanceof String)edit.putString(key,(String)value);
else if(value instanceof Integer)edit.putInt(key,(Integer)value);
}
edit.commit();
}
private static Object field(MainActivity activity,String name){
try{var field=MainActivity.class.getDeclaredField(name);field.setAccessible(true);return field.get(activity);}
catch(Exception error){throw new AssertionError(error);}
}
private static Dialog notice(MainActivity activity){
Dialog dialog=(Dialog)field(activity,"privacyDialog");assertNotNull("An unconsented visit must prompt",dialog);assertTrue(dialog.isShowing());return dialog;
}
private static TextView findText(View view,String text){
if(view instanceof TextView&&((TextView)view).getText().toString().equals(text))return (TextView)view;
if(view instanceof ViewGroup){ViewGroup parent=(ViewGroup)view;for(int i=0;i<parent.getChildCount();i++){TextView found=findText(parent.getChildAt(i),text);if(found!=null)return found;}}
return null;
}
private static TextView action(Dialog dialog,String text){
TextView view=findText(dialog.getWindow().getDecorView(),text);assertNotNull(text,view);return view;
}
private static void decline(MainActivity activity){action(notice(activity),"暂不同意").performClick();}
private static void agree(MainActivity activity){
Dialog dialog=notice(activity);action(dialog,"我已阅读并同意《隐私政策》").performClick();action(dialog,"同意并继续").performClick();
}
@Test public void coldLaunchRequiresExplicitAgreementBeforeNetworking(){
try(ActivityScenario<MainActivity> scenario=ActivityScenario.launch(MainActivity.class)){
scenario.onActivity(activity->{
Dialog dialog=notice(activity);
assertFalse(((CheckBox)action(dialog,"我已阅读并同意《隐私政策》")).isChecked());
assertFalse(action(dialog,"同意并继续").isEnabled());
action(dialog,"同意并继续").performClick();
assertTrue(dialog.isShowing());assertFalse(preferences.getBoolean("networkConsent",false));
assertNull(field(activity,"signaling"));
decline(activity);assertFalse(dialog.isShowing());assertNull(field(activity,"signaling"));
assertNotNull(findText(activity.getWindow().getDecorView(),"等待隐私授权"));
});
scenario.onActivity(activity->assertNull(field(activity,"privacyDialog")));
}
}
@Test public void refusalPromptsOnBackgroundReturnButNotTransientInactivity(){
try(ActivityScenario<MainActivity> scenario=ActivityScenario.launch(MainActivity.class)){
scenario.onActivity(PrivacyConsentTest::decline);
scenario.moveToState(Lifecycle.State.STARTED).moveToState(Lifecycle.State.RESUMED);
scenario.onActivity(activity->{assertNull(field(activity,"privacyDialog"));assertNull(field(activity,"signaling"));});
for(int visit=0;visit<3;visit++){
scenario.moveToState(Lifecycle.State.CREATED).moveToState(Lifecycle.State.RESUMED);
scenario.onActivity(activity->{notice(activity);assertNull(field(activity,"signaling"));decline(activity);});
}
}
try(ActivityScenario<MainActivity> scenario=ActivityScenario.launch(MainActivity.class)){
scenario.onActivity(activity->{notice(activity);assertNull(field(activity,"signaling"));});
}
}
@Test public void backgroundDismissesOldDialogAndClearsTheCheckbox(){
Dialog[] original={null};
try(ActivityScenario<MainActivity> scenario=ActivityScenario.launch(MainActivity.class)){
scenario.onActivity(activity->{original[0]=notice(activity);action(original[0],"我已阅读并同意《隐私政策》").performClick();assertTrue(action(original[0],"同意并继续").isEnabled());});
scenario.moveToState(Lifecycle.State.CREATED);
assertFalse(original[0].isShowing());
scenario.moveToState(Lifecycle.State.RESUMED);
scenario.onActivity(activity->{Dialog next=notice(activity);assertNotSame(original[0],next);assertFalse(action(next,"同意并继续").isEnabled());assertNull(field(activity,"signaling"));});
}
}
@Test public void agreementPersistsAndStopsAutomaticPrompts(){
try(ActivityScenario<MainActivity> scenario=ActivityScenario.launch(MainActivity.class)){
scenario.onActivity(activity->{Dialog dialog=notice(activity);agree(activity);assertTrue(preferences.getBoolean("networkConsent",false));assertFalse(dialog.isShowing());assertNotNull(field(activity,"signaling"));});
scenario.onActivity(activity->assertNull(field(activity,"privacyDialog")));
scenario.moveToState(Lifecycle.State.CREATED).moveToState(Lifecycle.State.RESUMED);
scenario.onActivity(activity->assertNull(field(activity,"privacyDialog")));
}
try(ActivityScenario<MainActivity> scenario=ActivityScenario.launch(MainActivity.class)){
scenario.onActivity(activity->assertNull(field(activity,"privacyDialog")));
scenario.moveToState(Lifecycle.State.CREATED);
preferences.edit().putBoolean("networkConsent",false).commit();
scenario.moveToState(Lifecycle.State.RESUMED);
scenario.onActivity(activity->{notice(activity);assertNull(field(activity,"signaling"));});
}
}
@Test public void existingLocalRecordsDoNotImplyConsent(){
Context context=InstrumentationRegistry.getInstrumentation().getTargetContext();
SharedPreferences identities=context.getSharedPreferences("identities",Context.MODE_PRIVATE);
String key="privacy-upgrade.invalid:1";
try{
identities.edit().putString(key,"existing-device-identity").commit();
try(ActivityScenario<MainActivity> scenario=ActivityScenario.launch(MainActivity.class)){
scenario.onActivity(activity->{notice(activity);assertNull(field(activity,"signaling"));});
}
}finally{identities.edit().remove(key).commit();}
}
@Test public void bundledChinesePolicyIsOfflineAndMissingPolicyCannotAuthorize(){
Context context=InstrumentationRegistry.getInstrumentation().getTargetContext();
PrivacyPolicyDocument policy=new PrivacyPolicyDocument(context);
assertTrue(policy.available);assertTrue(policy.text.contains("更新日期:"));assertTrue(policy.text.contains("查询与删除请求"));assertFalse(policy.text.contains("## English"));
assertFalse(new PrivacyPolicyDocument(" \n").available);
try(ActivityScenario<MainActivity> scenario=ActivityScenario.launch(MainActivity.class)){
scenario.onActivity(activity->{
decline(activity);int[] accepted={0};
Dialog missing=new PrivacyConsentDialog(activity,new MobileUi(activity),new PrivacyPolicyDocument((String)null),()->accepted[0]++);
try{
missing.show();action(missing,"我已阅读并同意《隐私政策》").performClick();
assertFalse(action(missing,"同意并继续").isEnabled());action(missing,"同意并继续").performClick();
assertEquals(0,accepted[0]);assertFalse(preferences.getBoolean("networkConsent",false));assertNull(field(activity,"signaling"));
action(missing,"暂不同意").performClick();assertFalse(missing.isShowing());
}finally{missing.dismiss();}
});
}
}
}
@@ -0,0 +1,51 @@
package cn.crossdesk.mobile;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
import java.util.ArrayList;
import static org.junit.Assert.*;
public class RecentConnectionPresenceTest {
private static JSONArray records(String... ids)throws Exception{
JSONArray result=new JSONArray();for(String id:ids)result.put(new JSONObject().put("id",id));return result;
}
private static JSONObject device(String id,boolean online)throws Exception{return new JSONObject().put("id",id).put("online",online);}
private static JSONObject snapshot(JSONObject... devices)throws Exception{
JSONArray values=new JSONArray();for(JSONObject device:devices)values.put(device);return new JSONObject().put("type","presence").put("devices",values);
}
private static JSONObject update(String id,boolean online)throws Exception{return device(id,online).put("type","presence_update");}
@Test public void snapshotAndUpdatesOnlyAffectWatchedDevicesAndSortStably()throws Exception{
RecentConnectionPresence presence=new RecentConnectionPresence();JSONArray history=records("111111111","222222222","333333333");
presence.watch(history,0);presence.setConnected(true,0);
presence.receive(update("111111111",true),1);assertFalse(presence.isOnline("111111111",1));
presence.receive(snapshot(device("222222222",true),device("333333333",true),device("999999999",true)),2);
assertFalse(presence.isOnline("999999999",2));assertTrue(presence.isOnline("222222222",2));
JSONArray ordered=presence.ordered(history,2);assertEquals("222222222",ordered.getJSONObject(0).getString("id"));assertEquals("333333333",ordered.getJSONObject(1).getString("id"));
presence.receive(update("222222222",false),3);assertFalse(presence.isOnline("222222222",3));
assertEquals("333333333",presence.ordered(history,3).getJSONObject(0).getString("id"));
presence.receive(snapshot(device("111111111",true)),4);assertFalse("A full snapshot replaces missing devices",presence.isOnline("333333333",4));
}
@Test public void refreshExpiryAndReconnectRequireFreshSnapshot()throws Exception{
RecentConnectionPresence presence=new RecentConnectionPresence();ArrayList<JSONArray> requests=new ArrayList<>();presence.sender=requests::add;
presence.watch(records("111111111"),0);assertTrue(requests.isEmpty());presence.setConnected(true,0);assertEquals(1,requests.size());
presence.receive(snapshot(device("111111111",true)),0);presence.maintain(29_999);assertEquals(1,requests.size());
presence.maintain(30_000);assertEquals(2,requests.size());assertTrue(presence.isOnline("111111111",59_999));
presence.maintain(60_000);assertEquals(3,requests.size());assertFalse(presence.isOnline("111111111",60_000));
presence.receive(update("111111111",true),60_001);assertTrue(presence.isOnline("111111111",60_001));
presence.setConnected(false,60_002);presence.receive(snapshot(device("111111111",true)),60_003);presence.maintain(120_000);assertEquals(3,requests.size());assertFalse(presence.isOnline("111111111",120_000));
presence.setConnected(true,120_001);assertEquals(4,requests.size());presence.receive(update("111111111",true),120_002);assertFalse(presence.isOnline("111111111",120_002));
presence.receive(snapshot(device("111111111",true)),120_003);assertTrue(presence.isOnline("111111111",120_003));
}
@Test public void changedHistoryResubscribesAndMalformedStatesDoNotBecomeOnline()throws Exception{
RecentConnectionPresence presence=new RecentConnectionPresence();ArrayList<JSONArray> requests=new ArrayList<>();presence.sender=requests::add;
presence.watch(records("111111111","111111111"),0);presence.setConnected(true,0);assertEquals(1,requests.get(0).length());
presence.receive(snapshot(device("111111111",true)),1);presence.watch(records("222222222"),2);assertEquals(2,requests.size());assertFalse(presence.isOnline("111111111",2));
presence.receive(snapshot(new JSONObject().put("id","222222222").put("online","true")),3);assertFalse(presence.isOnline("222222222",3));
presence.receive(snapshot(device("222222222",true)),4);presence.receive(new JSONObject().put("type","presence").put("devices","invalid"),5);assertTrue(presence.isOnline("222222222",5));
presence.watch(records(),6);assertEquals(0,requests.get(2).length());assertFalse(presence.isOnline("222222222",6));
}
}
@@ -0,0 +1,59 @@
package cn.crossdesk.mobile;
import android.content.*;
import android.graphics.*;
import androidx.test.platform.app.InstrumentationRegistry;
import org.junit.*;
import java.io.*;
import java.nio.file.Files;
import java.util.*;
import java.util.concurrent.*;
import static org.junit.Assert.*;
public class RemotePreviewStoreTest {
private Context context;
private File root;
private SharedPreferences options,index;
private String prefix;
private RemotePreviewStore store;
@Before public void setup()throws Exception{
context=InstrumentationRegistry.getInstrumentation().getTargetContext();prefix="preview-test-"+UUID.randomUUID();
options=context.getSharedPreferences(prefix,0);index=context.getSharedPreferences(prefix+"-index",0);
root=Files.createTempDirectory(context.getCacheDir().toPath(),"previews-").toFile();
store=new RemotePreviewStore(new File(root,"images"),options,index);
}
@After public void cleanup()throws Exception{
store.clear();flush();store.io.shutdown();
try(var paths=Files.walk(root.toPath())){for(var path:paths.sorted(Comparator.reverseOrder()).toList())Files.delete(path);}
context.deleteSharedPreferences(prefix);context.deleteSharedPreferences(prefix+"-index");
}
private void flush()throws Exception{store.io.submit(()->{}).get(5,TimeUnit.SECONDS);InstrumentationRegistry.getInstrumentation().waitForIdleSync();}
private void enable(){options.edit().putBoolean("networkConsent",true).commit();store.setEnabled(true);}
private static Bitmap solid(int color){Bitmap image=Bitmap.createBitmap(640,360,Bitmap.Config.ARGB_8888);image.eraseColor(color);return image;}
private Bitmap load(String server,String id)throws Exception{
var result=new java.util.concurrent.atomic.AtomicReference<Bitmap>();var done=new CountDownLatch(1);
store.load(server,id,image->{result.set(image);done.countDown();});assertTrue(done.await(5,TimeUnit.SECONDS));return result.get();
}
@Test public void offByDefaultAndConsentCannotBeBypassed()throws Exception{
assertFalse(store.enabled());assertNull(store.begin("server","1"));store.setEnabled(true);flush();assertFalse(store.enabled());
options.edit().putBoolean("networkConsent",true).commit();assertFalse(store.enabled());
enable();assertNotNull(store.begin("server","1"));
options.edit().putBoolean("networkConsent",false).commit();store.enforceConsent();flush();
assertFalse(options.getBoolean(RemotePreviewStore.OPTION,true));assertNull(store.begin("server","1"));
}
@Test public void jpegPersistsAcrossStoreRecreationAndRemainsServerScoped()throws Exception{
enable();var capture=store.begin("server:1","123456789");store.save(capture,solid(Color.GREEN));flush();
assertTrue(new File(store.directory,capture.key+".jpg").isFile());
assertNull(load("server:2","123456789"));assertNull(load("server:1","other"));
store.io.shutdown();store=new RemotePreviewStore(store.directory,options,index);
Bitmap loaded=load("server:1","123456789");assertNotNull(loaded);assertEquals(640,loaded.getWidth());assertEquals(360,loaded.getHeight());assertTrue(Color.green(loaded.getPixel(320,180))>240);loaded.recycle();
}
@Test public void disablingDeletesFilesAndInvalidatesInFlightCapture()throws Exception{
enable();var capture=store.begin("server","1");store.save(capture,solid(Color.BLUE));flush();
store.setEnabled(false);store.save(capture,solid(Color.RED));flush();
assertFalse(store.enabled());assertFalse(store.directory.exists());assertTrue(index.getAll().isEmpty());assertNull(load("server","1"));
store.setEnabled(true);assertNull(load("server","1"));
}
}
@@ -0,0 +1,64 @@
package cn.crossdesk.mobile;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.json.JSONObject;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import static org.junit.Assert.*;
@RunWith(AndroidJUnit4.class)
public class RemoteVersionCheckTest {
private static byte[] json(String value) { return value.getBytes(StandardCharsets.UTF_8); }
private static JSONObject host(Object version) {
try { return new JSONObject().put("app_version", version); }
catch (Exception error) { throw new AssertionError(error); }
}
private static final class Fetches implements RemoteVersionCheck.Fetcher {
final List<Consumer<byte[]>> replies = new ArrayList<>();
int cancellations;
public RemoteVersionCheck.Cancellation fetch(Consumer<byte[]> reply) {
replies.add(reply);
return () -> cancellations++;
}
}
@Test public void sharedNativeComparisonMatchesIosReleaseOrdering() {
byte[] release = json("{\"latest_version\":\"v1.5.3-20260928\",\"patch\":2}");
for (String version : new String[]{"1.5.2", "v1.5.3-20260928", "1.5.3-1-20260929", "1.5.3-20260928-1"}) {
assertTrue(NativeSession.nValidAppVersion(version));
assertTrue(version, NativeSession.nHasAppUpdate(version, release));
}
for (String version : new String[]{"1.5.3-2-20260927", "1.5.3-3-20260928", "1.6.0"})
assertFalse(version, NativeSession.nHasAppUpdate(version, release));
assertFalse(NativeSession.nHasAppUpdate("1.5.3-20260927", json("{\"version\":\"1.5.3-20261001\"}")));
assertTrue(NativeSession.nHasAppUpdate("1.5.3-9", json("{\"version\":\"1.5.3\",\"patch\":\"10\"}")));
}
@Test public void legacyVersionWaitsForConnectionAndNeverFetches() {
for (Object version : new Object[]{null, JSONObject.NULL, 123, "", " ", "unknown", "ios-native", "1..5", "1.5-"}) {
Fetches fetches = new Fetches(); int[] notices = {0};
RemoteVersionCheck check = new RemoteVersionCheck(fetches, () -> notices[0]++);
check.hostInfo(host(version)); assertEquals(0, notices[0]);
check.connected(); assertEquals(1, notices[0]);
check.hostInfo(host(version)); check.connected(); assertEquals(1, notices[0]);
assertTrue(fetches.replies.isEmpty()); check.reset();
}
}
@Test public void disconnectCancelsAndOldReplyCannotAffectANewPeer() {
Fetches fetches = new Fetches(); int[] notices = {0};
RemoteVersionCheck check = new RemoteVersionCheck(fetches, () -> notices[0]++);
check.hostInfo(host("1.0.0")); check.connected(); check.reset();
assertEquals(1, fetches.cancellations);
fetches.replies.get(0).accept(json("{\"version\":\"2.0.0\"}")); assertEquals(0, notices[0]);
check.connected(); check.hostInfo(host("3.0.0"));
fetches.replies.get(0).accept(json("{\"version\":\"2.0.0\"}"));
fetches.replies.get(1).accept(json("{\"version\":\"2.0.0\"}")); assertEquals(0, notices[0]);
check.reset(); assertEquals(1, fetches.cancellations);
}
}
@@ -0,0 +1,129 @@
package cn.crossdesk.mobile;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/** Non-UI regression checks for zoom and remote input geometry. */
@RunWith(AndroidJUnit4.class)
public class RemoteViewportTest {
private static final float EPSILON = .0001f;
@Test public void fittedVideoRejectsLetterboxingAndMapsItsEdges() {
RemoteViewport viewport = new RemoteViewport();
viewport.fit(1080,1920,1920,1080);
assertEquals(1080,viewport.baseWidth());
assertEquals(607,viewport.baseHeight());
assertEquals(656,viewport.top(),EPSILON);
assertFalse(viewport.contains(540,200));
assertTrue(viewport.contains(0,656));
assertFalse(viewport.contains(1080,1263));
assertEquals(.5f,viewport.normalizedX(540),EPSILON);
assertEquals(.5f,viewport.normalizedY(959.5f),EPSILON);
}
@Test public void pinchKeepsTheRemotePointUnderAnOffCenterFocus() {
RemoteViewport viewport = new RemoteViewport();
viewport.fit(1000,600,1000,600);
viewport.zoomBy(2,750,350);
assertEquals(2,viewport.scale(),EPSILON);
assertEquals(-250,viewport.offsetX(),EPSILON);
assertEquals(-50,viewport.offsetY(),EPSILON);
assertEquals(.75f,viewport.normalizedX(750),EPSILON);
assertEquals(350f/600,viewport.normalizedY(350),EPSILON);
viewport.zoomBy(.5f,750,350);
assertEquals(1,viewport.scale(),EPSILON);
assertEquals(0,viewport.offsetX(),EPSILON);
assertEquals(0,viewport.offsetY(),EPSILON);
}
@Test public void zoomAndPanUseTheSameInverseTransformForRemoteInput() {
RemoteViewport viewport = new RemoteViewport();
viewport.fit(1200,800,1920,1080);
viewport.zoomBy(3,600,399.5f);
viewport.panBy(200,100);
assertEquals(-1000,viewport.left(),EPSILON);
assertEquals(-513,viewport.top(),EPSILON);
assertEquals(1380f/3600,viewport.normalizedX(380),EPSILON);
assertEquals(.28f,viewport.normalizedY(54),EPSILON);
// Trackpad deltas use the zoomed dimensions, too.
assertEquals(.01f,36/viewport.width(),EPSILON);
assertEquals(.01f,20.25f/viewport.height(),EPSILON);
}
@Test public void panCannotMoveTheImagePastTheOriginalFittedArea() {
RemoteViewport viewport = new RemoteViewport();
viewport.fit(1000,800,1600,900);
viewport.zoomBy(2,500,400);
viewport.panBy(10000,-10000);
assertEquals(500,viewport.offsetX(),EPSILON);
assertEquals(-281,viewport.offsetY(),EPSILON);
assertEquals(0,viewport.left(),EPSILON);
assertEquals(119,viewport.top()+viewport.height()-viewport.baseHeight(),EPSILON);
viewport.panBy(-20000,20000);
assertEquals(-500,viewport.offsetX(),EPSILON);
assertEquals(281,viewport.offsetY(),EPSILON);
}
@Test public void scaleMatchesIosLimitsAndFinishingNearOneRestoresFit() {
RemoteViewport viewport = new RemoteViewport();
viewport.fit(1000,600,1000,600);
viewport.zoomBy(100,500,300);
assertEquals(10,viewport.scale(),EPSILON);
viewport.zoomBy(.10005f,500,300);
viewport.panBy(.1f,.1f);
viewport.finishGesture();
assertEquals(1,viewport.scale(),EPSILON);
assertEquals(0,viewport.offsetX(),EPSILON);
assertEquals(0,viewport.offsetY(),EPSILON);
assertFalse(viewport.isZoomed());
viewport.zoomBy(.01f,500,300);
assertEquals(1,viewport.scale(),EPSILON);
}
@Test public void rotationAndResolutionChangesConstrainExistingPan() {
RemoteViewport viewport = new RemoteViewport();
viewport.fit(1000,600,1000,600);
viewport.zoomBy(2,500,300);
viewport.panBy(500,300);
viewport.fit(600,1000,1000,600);
assertEquals(2,viewport.scale(),EPSILON);
assertEquals(300,viewport.offsetX(),EPSILON);
assertEquals(180,viewport.offsetY(),EPSILON);
viewport.fit(600,1000,600,1000);
assertEquals(2,viewport.scale(),EPSILON);
assertEquals(1000,viewport.baseHeight());
viewport.reset();
assertEquals(1,viewport.scale(),EPSILON);
assertEquals(0,viewport.offsetX(),EPSILON);
assertEquals(0,viewport.offsetY(),EPSILON);
}
@Test public void oddMarginsShareTheActualSurfaceCenterAtMaximumZoom() {
RemoteViewport viewport = new RemoteViewport();
viewport.fit(801,603,800,600);
assertEquals(801,viewport.baseWidth());
assertEquals(600,viewport.baseHeight());
assertEquals(1,viewport.top(),EPSILON);
viewport.zoomBy(10,400.5f,301);
assertEquals(-3604.5f,viewport.left(),EPSILON);
assertEquals(-2699,viewport.top(),EPSILON);
assertEquals(.5f,viewport.normalizedX(400.5f),EPSILON);
assertEquals(.5f,viewport.normalizedY(301),EPSILON);
}
@Test public void invalidGeometryAndScaleDoNotCorruptViewport() {
RemoteViewport viewport = new RemoteViewport();
viewport.fit(0,0,1920,1080);
assertFalse(viewport.contains(0,0));
viewport.zoomBy(2,0,0);
assertEquals(1,viewport.scale(),EPSILON);
viewport.fit(1000,600,1000,600);
viewport.zoomBy(Float.NaN,500,300);
viewport.zoomBy(Float.POSITIVE_INFINITY,500,300);
viewport.zoomBy(-1,500,300);
assertEquals(1,viewport.scale(),EPSILON);
assertEquals(0,viewport.offsetX(),EPSILON);
}
}
@@ -0,0 +1,63 @@
package cn.crossdesk.mobile;
import android.content.Context;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.platform.app.InstrumentationRegistry;
import org.json.JSONObject;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.*;
import java.lang.reflect.*;
import java.net.InetAddress;
import java.nio.file.Files;
import java.security.KeyStore;
import java.util.concurrent.*;
import javax.net.ssl.*;
import static org.junit.Assert.*;
/** Exercises the actual MiniRTC TLS path inside an Android app process (AT_SECURE=1).
* The bundled PKCS12 keys are public test fixtures, only served on loopback. No
* websocket upgrade/login or external server is involved in these tests. */
@RunWith(AndroidJUnit4.class)
public class TlsTrustTest {
@Test public void explicitlyTrustedCertificateCompletesHandshake() throws Exception {
assertTrue("The app must load the supplied trust bundle despite AT_SECURE", handshake("valid",true));
}
@Test public void untrustedCertificateIsRejected() throws Exception {
assertFalse("A test CA absent from the system store must not be trusted",handshake("valid",false));
}
@Test public void certificateForAnotherHostIsRejected() throws Exception {
assertFalse("Trusting the CA must not bypass hostname verification",handshake("wrong-host",true));
}
private boolean handshake(String certificate,boolean trustFixture) throws Exception {
var instrumentation=InstrumentationRegistry.getInstrumentation();Context context=instrumentation.getTargetContext();
KeyStore keyStore=KeyStore.getInstance("PKCS12");char[] password="local-test-only".toCharArray();
try(InputStream input=instrumentation.getContext().getAssets().open("tls/"+certificate+".p12")){keyStore.load(input,password);}
KeyManagerFactory keys=KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());keys.init(keyStore,password);
SSLContext tls=SSLContext.getInstance("TLS");tls.init(keys.getKeyManagers(),null,null);
ExecutorService serverWorker=Executors.newSingleThreadExecutor();
NativeSession session=new NativeSession(context,"127.0.0.1",1,"unused","unused",new NativeSession.Listener(){
public void status(String value){} public void connected(){fail("Test server never opens a desktop session");}
public void ended(String value){} public void data(JSONObject value){}public void videoSize(int w,int h){}
public void clipboard(String value){}public void statistics(RemoteNetworkStatistics.Snapshot value){}
});
File roots=new File(context.getCacheDir(),"tls-test-roots.pem");
Field rtcField=NativeSession.class.getDeclaredField("RTC");rtcField.setAccessible(true);ExecutorService rtc=(ExecutorService)rtcField.get(null);
try(SSLServerSocket server=(SSLServerSocket)tls.getServerSocketFactory().createServerSocket(0,1,InetAddress.getByName("127.0.0.1"))){
server.setSoTimeout(10000);
if(trustFixture){try(InputStream input=instrumentation.getContext().getAssets().open("tls/root.pem")){Files.copy(input,roots.toPath(),java.nio.file.StandardCopyOption.REPLACE_EXISTING);}}
else{Method export=NativeSession.class.getDeclaredMethod("exportTrust");export.setAccessible(true);File systemRoots=(File)export.invoke(session);Files.copy(systemRoots.toPath(),roots.toPath(),java.nio.file.StandardCopyOption.REPLACE_EXISTING);}
Future<Boolean> request=serverWorker.submit(()->{
try(SSLSocket socket=(SSLSocket)server.accept()){
socket.setSoTimeout(10000);socket.startHandshake();
String first=new BufferedReader(new InputStreamReader(socket.getInputStream(),java.nio.charset.StandardCharsets.US_ASCII)).readLine();
return first!=null&&first.startsWith("GET ");
}catch(SSLException expected){return false;}
});
Method create=NativeSession.class.getDeclaredMethod("nCreate",NativeSession.class,String.class,int.class,String.class,String.class,String.class);create.setAccessible(true);
Field handle=NativeSession.class.getDeclaredField("handle");handle.setAccessible(true);
rtc.submit(()->{try{long value=(long)create.invoke(null,session,"127.0.0.1",server.getLocalPort(),"",context.getCacheDir().getAbsolutePath(),roots.getAbsolutePath());handle.setLong(session,value);assertNotEquals(0L,value);}catch(ReflectiveOperationException error){throw new RuntimeException(error);}}).get(10,TimeUnit.SECONDS);
return request.get(15,TimeUnit.SECONDS);
}finally{session.close();rtc.submit(()->{}).get(10,TimeUnit.SECONDS);serverWorker.shutdownNow();roots.delete();}
}
}
@@ -0,0 +1,22 @@
package cn.crossdesk.mobile;
import org.junit.Test;
import static org.junit.Assert.*;
public class VideoSettingsTest {
private final RemoteVideoSettings.Values first=new RemoteVideoSettings.Values(1,30,2),second=new RemoteVideoSettings.Values(0,60,1);
private void same(RemoteVideoSettings.Values expected,RemoteVideoSettings.Values actual){assertEquals(expected.quality,actual.quality);assertEquals(expected.frameRate,actual.frameRate);assertEquals(expected.preference,actual.preference);}
@Test public void acknowledgementCommitsAndRejectionRollsBack(){
RemoteVideoSettings state=new RemoteVideoSettings(1);state.setSupported(true);long id=state.begin(first);assertTrue(state.pending);same(new RemoteVideoSettings.Values(1,30,1),state.applied);
state.receive(first,id,true);same(first,state.selection);assertFalse(state.pending);assertFalse(state.failed);state.expire(id);assertFalse(state.failed);
id=state.begin(second);state.receive(second,id,false);same(first,state.selection);assertTrue(state.failed);state.begin(second);assertFalse(state.failed);
}
@Test public void timeoutLateReplyAndCapabilityLoss(){
RemoteVideoSettings state=new RemoteVideoSettings(1);state.setSupported(true);long id=state.begin(first);state.expire(id);assertTrue(state.failed);same(new RemoteVideoSettings.Values(1,30,1),state.selection);
state.receive(first,id,true);same(first,state.selection);assertFalse(state.failed);
id=state.begin(second);state.setSupported(false);state.receive(second,id,true);state.expire(id);same(first,state.selection);assertFalse(state.failed);assertFalse(state.pending);
}
}
+57
View File
@@ -0,0 +1,57 @@
"""Check Xmake discovery and the minimum supported version before native builds."""
import importlib.util
import os
from pathlib import Path
import unittest
from unittest.mock import patch
source = Path(__file__).resolve().parents[1] / "scripts/build_native.py"
spec = importlib.util.spec_from_file_location("build_native", source)
build_native = importlib.util.module_from_spec(spec)
spec.loader.exec_module(build_native)
class XmakeSelectionTest(unittest.TestCase):
def setUp(self):
for patcher in (
patch.dict(os.environ, {}, clear=True),
patch.object(build_native.shutil, "which", return_value="/tools/xmake"),
patch.object(build_native.subprocess, "check_output", return_value="xmake v3.1.1\n"),
):
patcher.start()
self.addCleanup(patcher.stop)
def test_path_tool_accepts_minimum_and_newer_versions(self):
for output in ("xmake v3.1.1", "xmake v3.1.2\n", "xmake v3.1.10, A build utility\n",
"xmake v3.2.0\n", "xmake v3.10.0\n", "xmake v4.0.0\n",
"\x1b[1mxmake v3.1.1+HEAD.3ba37a0d4, A build utility\x1b[0m\n"):
with self.subTest(output=output):
build_native.subprocess.check_output.return_value = output
self.assertEqual(build_native.find_xmake(), "/tools/xmake")
def test_explicit_tool_takes_precedence_over_path(self):
os.environ["XMAKE_BIN"] = "/custom/xmake"
self.assertEqual(build_native.find_xmake(), "/custom/xmake")
build_native.shutil.which.assert_not_called()
build_native.subprocess.check_output.assert_called_once_with(
["/custom/xmake", "--version"], text=True)
def test_missing_tool_reports_minimum_requirement(self):
build_native.shutil.which.return_value = None
with self.assertRaisesRegex(SystemExit, "Xmake 3.1.1 or newer is required"):
build_native.find_xmake()
build_native.subprocess.check_output.assert_not_called()
def test_older_or_unrecognized_versions_are_rejected(self):
for output in ("xmake v3.1.0\n", "xmake v3.0.99\n", "xmake v2.99.99\n",
"xmake version unknown\n", "xmake v3.1\n", "xmake v3.1.1invalid\n", ""):
with self.subTest(output=output):
build_native.subprocess.check_output.return_value = output
with self.assertRaisesRegex(SystemExit, "Use Xmake 3.1.1 or newer"):
build_native.find_xmake()
if __name__ == "__main__":
unittest.main()

Some files were not shown because too many files have changed in this diff Show More