@desklink/react-native 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,18 @@
1
+ desklink React Native client
2
+ Copyright the desklink authors. Licensed under the Apache License, Version 2.0.
3
+
4
+ react-native-webrtc MIT
5
+ The WebRTC binding the consuming application already ships. This package
6
+ compiles against its `org.webrtc` classes and never mutates its global
7
+ decoder factory, so a single native library serves both.
8
+
9
+ WebRTC (libwebrtc) BSD-3-Clause
10
+ Reached through the application's existing binding; not redistributed by
11
+ this package.
12
+
13
+ expo / expo-modules-core MIT
14
+ The native module and view plumbing.
15
+
16
+ The client package contains no code from Sunshine, Moonlight, Apollo or
17
+ RustDesk. Its decoder selection, session lifecycle and gesture model were written
18
+ from the documented WebRTC and platform APIs.
package/README.md ADDED
@@ -0,0 +1,131 @@
1
+ # @desklink/react-native
2
+
3
+ Show a live desktop in a React Native app, and drive it from the phone.
4
+
5
+ The package is a **view and a session**, not a screen: it renders the picture and
6
+ turns touch, the keyboard and the clipboard into that session's input. Where it
7
+ sits, how it starts, what the buttons look like and where "back" goes belong to
8
+ the application.
9
+
10
+ ## Install
11
+
12
+ The package contains native code and is not an Expo Go package. Inside this
13
+ repository it resolves through the workspace; anywhere else, install it from npm:
14
+
15
+ ```sh
16
+ npx expo install @desklink/react-native # or yarn add, then prebuild/rebuild
17
+ ```
18
+
19
+ Android as a native module, plus the browser, which brings its own WebRTC.
20
+ `expo-module.config.json` declares the native side honestly rather than
21
+ compiling an untested stub for other platforms; `ios/DEFERRED.md` lists exactly
22
+ what an iOS backend has to implement.
23
+
24
+ It compiles against the WebRTC binding the app already ships
25
+ (`react-native-webrtc`) so there is one `org.webrtc` copy in the binary, and it
26
+ never touches that binding's process-global decoder factory.
27
+
28
+ ## Use
29
+
30
+ ```tsx
31
+ import { DesktopView, useDesktopSession, CONTROL_PERMISSIONS } from '@desklink/react-native';
32
+
33
+ const desktop = useDesktopSession({
34
+ authorize: async () => ({
35
+ signaling, // your authenticated channel to the host
36
+ session: { permissions: CONTROL_PERMISSIONS },
37
+ }),
38
+ });
39
+
40
+ // Opening is a user action, so the app decides when it happens.
41
+ await desktop.connect();
42
+
43
+ <DesktopView sessionId={desktop.nativeId} style={{ flex: 1 }} keyboardClearance={96} />;
44
+ // On a deliberate control action, once the picture is live:
45
+ desktop.setInputEnabled(true);
46
+ desktop.showKeyboard();
47
+ desktop.setOrientation('landscape'); // Android: hold the screen on its side; 'auto' to follow the phone
48
+ await desktop.pasteLocalToRemote(await Clipboard.getStringAsync());
49
+ ```
50
+
51
+ A screen that only decides *whether* to offer a desktop does not need the
52
+ session: import the flag from its own entry, which is a constant on web and a
53
+ check for the platform module elsewhere, so the hook and the view stay out of
54
+ the first paint.
55
+
56
+ ```tsx
57
+ import { desktopAvailable } from '@desklink/react-native/availability';
58
+
59
+ {desktopAvailable && <ComputerAction onPress={openDesktop} />}
60
+ ```
61
+
62
+ ### What the package guarantees
63
+
64
+ - **Hardware-first decoding.** The session builds its own peer connection with
65
+ a hardware-first decoder factory for VP9, falling back to software on phones
66
+ without a VP9 hardware decoder. No other WebRTC user in the app is affected.
67
+ - **A sharp, zoomable picture.** The desktop fits the view by default; a pinch
68
+ zooms up to 2.5 view pixels per desktop pixel and one finger moves around the
69
+ zoomed desktop. On Android the decoded frame is copied once into the view's
70
+ own texture and drawn with a multi-tap filter when it is shown smaller than
71
+ its size, so a fitted 4K desktop does not alias and a pinch redraws at once.
72
+ `fitToView()` shows the whole desktop again.
73
+ - **A pointer a phone can see.** Once a touch has sent the desktop's pointer
74
+ somewhere, the view draws it there at a readable size, over a picture whose
75
+ own cursor is a few pixels tall or not captured at all. A mouse keeps its own.
76
+ - **The picture above the keyboard.** While the phone's keyboard is up, the
77
+ picture sits above it and above the room the app keeps for its own controls
78
+ (`keyboardClearance`), moving with the keyboard as it slides. A picture too
79
+ tall for what is left keeps the pointer, where a tap just put the caret, in
80
+ sight.
81
+ - **Contained geometry.** Touch maps through the picture's actual placement.
82
+ A one-finger drag starting in the letterbox does not move the pointer; a
83
+ second finger on the picture can still start a pinch or scroll. A drag that
84
+ leaves the picture is held to its edge rather than released somewhere unseen.
85
+ - **The gestures remote-desktop viewers settled on,** decided natively with a
86
+ slop threshold: tap to click, and a second tap close by is a double click on
87
+ the same point; hold and release for a right click where the finger rested
88
+ (every desktop app's context menu); hold then drag for the left button
89
+ (select text, move a window); on the whole desktop a finger that moves
90
+ carries the pointer with it, without a button, and the drawn pointer stays
91
+ under the finger while the picture catches up; two fingers scroll the desktop
92
+ under them, or pinch; a quick two-finger tap is a right click too. Scrolling
93
+ is fractional wheel steps, smooth where the desktop supports high-resolution
94
+ wheels. Under congestion, only the latest unsent pointer position is kept;
95
+ other input follows that position in order.
96
+ - **The keys a phone lacks.** `modifiers`, `tapModifier` and `pressKey` give
97
+ sticky Ctrl and Shift: tap arms one for the next key, tap again locks it.
98
+ While one is armed, the next key or character the phone's keyboard types is
99
+ sent as that key's chord, so Ctrl then v is Ctrl+V. The app draws the keys.
100
+ - **Readiness is a rendered frame.** `status: 'live'` is set by the first frame
101
+ actually presented, not by a track arriving or ICE connecting.
102
+ - **Control starts off.** `setInputEnabled(true)` enables pointer, keyboard and
103
+ clipboard input; `setInputEnabled(false)` blocks new input, releases held keys
104
+ and buttons, and resets pending gestures. The app decides when to enable it
105
+ after a deliberate action and must disable it on background or lost readiness;
106
+ a clipboard write already in flight may still finish.
107
+ - **Released state.** The app disables input on background and unmount;
108
+ session close and a lost control channel release what the desktop was holding.
109
+ - **Explicit clipboard.** Two methods, called on a user action while control is
110
+ enabled. The package never polls the clipboard or uses it as a way to type.
111
+
112
+ ### `Signaling`
113
+
114
+ The one thing the app must supply. It carries the engine's local protocol over
115
+ whatever authenticated channel the app already has:
116
+
117
+ ```ts
118
+ interface Signaling {
119
+ request<T>(method: string, params?: Record<string, unknown>): Promise<T>;
120
+ subscribe(handler: (event: SessionEvent) => void): () => void;
121
+ }
122
+ ```
123
+
124
+ `method` is one of `session.open`, `session.description`, `session.candidate`,
125
+ `session.close`; `SessionEvent` is the engine's offer, candidates, state and
126
+ revocation. Pixels and input do **not** use this channel — they are the
127
+ desktop's own WebRTC session.
128
+
129
+ ## Licence
130
+
131
+ Apache-2.0. See `NOTICE`.
@@ -0,0 +1,29 @@
1
+ apply plugin: 'com.android.library'
2
+ apply plugin: 'kotlin-android'
3
+
4
+ group = 'expo.modules.desklink'
5
+ version = '0.1.0'
6
+
7
+ android {
8
+ namespace 'expo.modules.desklink'
9
+ compileSdk rootProject.ext.has('compileSdkVersion') ? rootProject.ext.compileSdkVersion : 36
10
+ defaultConfig {
11
+ minSdk rootProject.ext.has('minSdkVersion') ? rootProject.ext.minSdkVersion : 24
12
+ }
13
+ kotlinOptions { jvmTarget = '17' }
14
+ compileOptions {
15
+ sourceCompatibility JavaVersion.VERSION_17
16
+ targetCompatibility JavaVersion.VERSION_17
17
+ }
18
+ }
19
+
20
+ dependencies {
21
+ implementation project(':expo-modules-core')
22
+ implementation 'androidx.core:core-ktx:1.17.0'
23
+ implementation "org.jetbrains.kotlin:kotlin-stdlib:${kotlinVersion}"
24
+ testImplementation 'junit:junit:4.13.2'
25
+ // The app's existing WebRTC binding, so the org.webrtc classes and the single
26
+ // native library are shared rather than a second copy being linked in. This
27
+ // package never mutates that binding's global decoder factory.
28
+ implementation project(':react-native-webrtc')
29
+ }
@@ -0,0 +1 @@
1
+ # Kept empty so the package does not impose build settings on its consumer.
@@ -0,0 +1 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android" />
@@ -0,0 +1,199 @@
1
+ package expo.modules.desklink
2
+
3
+ import android.app.Activity
4
+ import android.content.pm.ActivityInfo
5
+ import android.content.res.Configuration
6
+ import expo.modules.kotlin.modules.Module
7
+ import expo.modules.kotlin.modules.ModuleDefinition
8
+ import java.util.concurrent.ConcurrentHashMap
9
+
10
+ /**
11
+ * The client half of the desktop package.
12
+ *
13
+ * The module owns session objects; the view owns the pixels and the gestures.
14
+ * Everything an application does goes through this small surface:
15
+ * open → negotiate → show → drive → close.
16
+ */
17
+ class DesklinkModule : Module() {
18
+ private val sessions = ConcurrentHashMap<String, DesktopSession>()
19
+ private var nextId = 0
20
+
21
+ private val eglContext = lazy {
22
+ // One shared EGL context for every session's renderer: a second display
23
+ // connection would cost a GPU context per session for no benefit.
24
+ org.webrtc.EglBase.create().eglBaseContext
25
+ }
26
+
27
+ override fun definition() = ModuleDefinition {
28
+ Name("Desklink")
29
+
30
+ Events("onSessionEvent")
31
+
32
+ Function("createSession") { iceServersJson: String? ->
33
+ val context = appContext.reactContext ?: return@Function null
34
+ val id = "desklink-${++nextId}"
35
+ val session = DesktopSession(
36
+ context = context,
37
+ eglBase = eglContext.value,
38
+ onEvent = { name, payload -> emit(name, id, payload) },
39
+ )
40
+ sessions[id] = session
41
+ session.start(iceServersJson ?: "[]")
42
+ id
43
+ }
44
+
45
+ Function("setRemoteDescription") { id: String, type: String, sdp: String ->
46
+ sessions[id]?.setRemoteDescription(type, sdp)
47
+ true
48
+ }
49
+
50
+ Function("addRemoteCandidate") { id: String, candidate: String, sdpMid: String?, sdpMLineIndex: Int? ->
51
+ sessions[id]?.addRemoteCandidate(candidate, sdpMid, sdpMLineIndex ?: 0)
52
+ true
53
+ }
54
+
55
+ Function("sendControl") { id: String, message: String ->
56
+ sessions[id]?.sendStamped(message)
57
+ true
58
+ }
59
+
60
+ Function("setInputEnabled") { id: String, enabled: Boolean ->
61
+ sessions[id]?.setInputEnabled(enabled)
62
+ if (!enabled) postToView(id) { it.disarmInput() }
63
+ true
64
+ }
65
+
66
+ Function("showKeyboard") { id: String ->
67
+ postToView(id) { it.showKeyboard() }
68
+ true
69
+ }
70
+
71
+ Function("hideKeyboard") { id: String ->
72
+ postToView(id) { it.hideKeyboard() }
73
+ true
74
+ }
75
+
76
+ Function("captureKeyboard") { id: String, captured: Boolean ->
77
+ postToView(id) { it.captureKeyboard(captured) }
78
+ true
79
+ }
80
+
81
+ Function("setOrientation") { mode: String ->
82
+ val activity = appContext.currentActivity ?: return@Function false
83
+ activity.runOnUiThread {
84
+ landscapeWanted = mode == "landscape"
85
+ if (landscapeWanted) holdLandscape(activity) else releaseLandscape(activity)
86
+ }
87
+ true
88
+ }
89
+
90
+ // The hold is the desktop's, not the phone's: the home screen and other
91
+ // apps never inherit it, and it comes back with the app.
92
+ OnActivityEntersBackground { appContext.currentActivity?.let { releaseLandscape(it) } }
93
+
94
+ OnActivityEntersForeground {
95
+ if (landscapeWanted) appContext.currentActivity?.let { holdLandscape(it) }
96
+ }
97
+
98
+ Function("fitToView") { id: String ->
99
+ postToView(id) { it.fitToView() }
100
+ true
101
+ }
102
+
103
+ Function("setSurfaceSize") { id: String, width: Int, height: Int ->
104
+ postToView(id) { it.setSurfaceSize(width, height) }
105
+ true
106
+ }
107
+
108
+ Function("closeSession") { id: String ->
109
+ sessions.remove(id)?.shutdown()
110
+ views.remove(id)
111
+ true
112
+ }
113
+
114
+ Function("isAvailable") { true }
115
+
116
+ View(DesktopView::class) {
117
+ Name("DesklinkSurface")
118
+
119
+ Prop("sessionId") { view: DesktopView, id: String? ->
120
+ val session = id?.let { sessions[it] }
121
+ view.setSession(session)
122
+ if (id != null) views[id] = view
123
+ }
124
+
125
+ Prop("keyboardClearance") { view: DesktopView, clearance: Float? ->
126
+ view.setKeyboardClearance(clearance ?: 0f)
127
+ }
128
+
129
+ OnViewDestroys { view: DesktopView -> view.release() }
130
+
131
+ OnViewDidUpdateProps { view: DesktopView ->
132
+ // Props are applied before the view is measured; a session that arrived
133
+ // with the prop has to be told about the view it will render into.
134
+ view.requestGeometryRefresh()
135
+ }
136
+ }
137
+
138
+ OnDestroy {
139
+ for (session in sessions.values) session.shutdown()
140
+ sessions.clear()
141
+ views.clear()
142
+ }
143
+ }
144
+
145
+ private val views = ConcurrentHashMap<String, DesktopView>()
146
+
147
+ // Main thread only. `orientationBefore` is what the app asked for before the
148
+ // first hold; it outlives a release still on its way upright.
149
+ private var landscapeWanted = false
150
+ private var holding = false
151
+ private var orientationBefore: Int? = null
152
+ private var portraitBefore = false
153
+
154
+ private fun holdLandscape(activity: Activity) {
155
+ if (orientationBefore == null) {
156
+ orientationBefore = activity.requestedOrientation
157
+ portraitBefore = activity.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT
158
+ }
159
+ holding = true
160
+ activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
161
+ }
162
+
163
+ private fun releaseLandscape(activity: Activity) {
164
+ val before = orientationBefore
165
+ if (!holding || before == null) return
166
+ holding = false
167
+ val restore = {
168
+ if (!holding) {
169
+ activity.requestedOrientation = before
170
+ orientationBefore = null
171
+ }
172
+ }
173
+ if (!portraitBefore) return restore()
174
+ // With auto-rotate off, Android keeps whatever rotation is on screen when
175
+ // an app stops asking for one, and makes it the phone's locked rotation.
176
+ // Turn upright first, then hand back the orientation the app had.
177
+ activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
178
+ activity.window.decorView.post(restore)
179
+ }
180
+
181
+ // Synchronous module functions run on JS, not Android's UI thread. Ignore
182
+ // queued work if the session/view was closed or replaced in the meantime.
183
+ private fun postToView(id: String, action: (DesktopView) -> Unit) {
184
+ views[id]?.let { view ->
185
+ view.post { if (views[id] === view) action(view) }
186
+ }
187
+ }
188
+
189
+ private fun emit(name: String, id: String, payload: Map<String, Any?>) {
190
+ sendEvent(
191
+ "onSessionEvent",
192
+ mapOf(
193
+ "sessionId" to id,
194
+ "name" to name,
195
+ "payload" to payload,
196
+ ),
197
+ )
198
+ }
199
+ }