├── .github
├── ci-gradle.properties
└── workflows
│ └── build.yml
├── .gitignore
├── LICENSE
├── README.md
├── build.gradle.kts
├── example
├── .gitignore
├── build.gradle.kts
├── consumer-rules.pro
├── proguard-rules.pro
└── src
│ ├── androidMain
│ ├── AndroidManifest.xml
│ ├── kotlin
│ │ └── com
│ │ │ └── moriatsushi
│ │ │ └── insetsx
│ │ │ └── example
│ │ │ └── MainActivity.kt
│ └── res
│ │ └── values
│ │ └── strings.xml
│ ├── commonMain
│ └── kotlin
│ │ └── com.moriatsushi.insetsx.example
│ │ └── ExampleApp.kt
│ ├── desktopMain
│ └── kotlin
│ │ └── Main.desktop.kt
│ ├── macosMain
│ └── kotlin
│ │ └── Main.macos.kt
│ ├── uikitMain
│ └── kotlin
│ │ └── Main.uikit.kt
│ └── wasmMain
│ ├── kotlin
│ └── Main.wasm.kt
│ └── resources
│ ├── index.html
│ └── load.mjs
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── insetsx
├── build.gradle.kts
├── gradle.properties
└── src
│ ├── androidMain
│ └── kotlin
│ │ └── com
│ │ └── moriatsushi
│ │ └── insetsx
│ │ ├── SystemBarsBehavior.android.kt
│ │ ├── WindowInsets.android.kt
│ │ └── WindowInsetsController.android.kt
│ ├── commonMain
│ └── kotlin
│ │ └── com
│ │ └── moriatsushi
│ │ └── insetsx
│ │ ├── ExperimentalSoftwareKeyboardApi.kt
│ │ ├── SystemBarsBehavior.kt
│ │ ├── WindowInsets.kt
│ │ ├── WindowInsetsController.kt
│ │ └── WindowInsetsPadding.kt
│ ├── nativeInterop
│ └── cinterop
│ │ └── uikit.def
│ ├── noOpMain
│ └── kotlin
│ │ └── com
│ │ └── moriatsushi
│ │ └── insetsx
│ │ ├── SystemBarsBehavior.noop.kt
│ │ ├── WindowInsets.noop.kt
│ │ └── WindowInsetsController.noop.kt
│ └── uikitMain
│ └── kotlin
│ └── com
│ └── moriatsushi
│ └── insetsx
│ ├── NavigationBarsInsets.kt
│ ├── SafeAreaInsets.kt
│ ├── StatusBarsInsets.kt
│ ├── SystemBarsBehavior.uikit.kt
│ ├── UIKeyboardInsets.kt
│ ├── UIRectEdgeValue.kt
│ ├── WindowInsets.uikit.kt
│ ├── WindowInsetsController.ios.kt
│ ├── WindowInsetsHolder.uikit.kt
│ └── WindowInsetsUIViewController.kt
├── kotlin-js-store
└── yarn.lock
├── renovate.json
└── settings.gradle.kts
/.github/ci-gradle.properties:
--------------------------------------------------------------------------------
1 | org.gradle.daemon=false
2 | org.gradle.parallel=true
3 | org.gradle.workers.max=2
4 | org.gradle.jvmargs=-Xmx2g
5 |
6 | # kotlin
7 | kotlin.compiler.execution.strategy=in-process
8 | kotlin.native.ignoreDisabledTargets=true
9 |
10 | # other
11 | warningsAsErrors=true
12 |
--------------------------------------------------------------------------------
/.github/workflows/build.yml:
--------------------------------------------------------------------------------
1 | name: Build
2 |
3 | on:
4 | push:
5 | branches:
6 | - main
7 | pull_request:
8 |
9 | concurrency:
10 | group: build-${{ github.ref }}
11 | cancel-in-progress: true
12 |
13 | jobs:
14 | build:
15 | runs-on: ubuntu-latest
16 | timeout-minutes: 60
17 |
18 | steps:
19 | - name: Checkout
20 | uses: actions/checkout@v4
21 |
22 | - name: Validate Gradle Wrapper
23 | uses: gradle/wrapper-validation-action@v1
24 |
25 | - name: Copy CI gradle.properties
26 | run: mkdir -p ~/.gradle ; cp .github/ci-gradle.properties ~/.gradle/gradle.properties
27 |
28 | - name: Set up JDK 11
29 | uses: actions/setup-java@v3
30 | with:
31 | java-version: 17
32 | distribution: 'zulu'
33 |
34 | - name: Setup Gradle
35 | uses: gradle/gradle-build-action@v2
36 | with:
37 | gradle-home-cache-cleanup: true
38 | cache-read-only: ${{ github.ref != 'refs/heads/main' }}
39 |
40 | - name: Check spotless
41 | run: ./gradlew spotlessCheck --no-configuration-cache --stacktrace
42 |
43 | - name: Build all build type
44 | run: ./gradlew assemble --stacktrace
45 |
46 | - name: Run local tests
47 | run: ./gradlew testDebug --stacktrace
48 |
49 | - name: Upload test reports
50 | if: always()
51 | uses: actions/upload-artifact@v3
52 | with:
53 | name: test-reports
54 | path: '**/build/reports/tests'
55 |
56 | build-on-macos:
57 | runs-on: macos-latest
58 | timeout-minutes: 30
59 |
60 | steps:
61 | - name: Checkout
62 | uses: actions/checkout@v4
63 |
64 | - name: Validate Gradle Wrapper
65 | uses: gradle/wrapper-validation-action@v1
66 |
67 | - name: Copy CI gradle.properties
68 | run: mkdir -p ~/.gradle ; cp .github/ci-gradle.properties ~/.gradle/gradle.properties
69 |
70 | - name: Set up JDK 11
71 | uses: actions/setup-java@v3
72 | with:
73 | java-version: 17
74 | distribution: 'zulu'
75 |
76 | - name: Setup Gradle
77 | uses: gradle/gradle-build-action@v2
78 | with:
79 | gradle-home-cache-cleanup: true
80 | cache-read-only: ${{ github.ref != 'refs/heads/main' }}
81 |
82 | - name: Run local tests
83 | run: |
84 | ./gradlew uikitX64Test uikitSimArm64Test macosX64Test macosArm64Test
85 |
86 | - name: Upload test reports
87 | if: always()
88 | uses: actions/upload-artifact@v3
89 | with:
90 | name: test-reports
91 | path: '**/build/reports/tests'
92 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | .idea
4 | .DS_Store
5 | build
6 | captures
7 | .externalNativeBuild
8 | .cxx
9 | local.properties
10 | xcuserdata
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2022 Mori Atsushi.
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## InsetsX [🚧 Work in progress 🚧]
2 | [](https://kotlinlang.org/docs/multiplatform.html)
3 | [](https://mvnrepository.com/artifact/com.moriatsushi.insetsx/insetsx)
4 | [](https://github.com/mori-atsushi/insetsx/blob/main/LICENSE)
5 |
6 | 
7 |
8 | InsetsX provides a [WindowInsets](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/WindowInsets) utility for [Compose Multiplatform](https://www.jetbrains.com/lp/compose-multiplatform/).
9 |
10 | The goal is to have a unified interface for handling WindowInsets across iOS and Android.
11 |
12 | Once the official library supports WindowInsets, this library will be archived.
13 |
14 | ## Setup
15 | To use InsetsX, add the following dependency:
16 |
17 | ```kotlin
18 | kotlin {
19 | /* ... */
20 |
21 | sourceSets {
22 | val commonMain by getting {
23 | dependencies {
24 | implementation("com.moriatsushi.insetsx:insetsx:0.1.0-alpha10")
25 | }
26 | }
27 | }
28 | }
29 | ```
30 |
31 | ### Android
32 | 1. (option) If you are using insets for IME support, set the activity's `windowSoftInputMode` to `adjustResize` in your AndroidManifest.xml file.
33 |
34 | ```xml
35 |
38 |
39 | ```
40 |
41 | 2. Call `WindowCompat.setDecorFitsSystemWindows()` with `false` in the `onCreate` method of the activity .
42 |
43 | ```kotlin
44 | override fun onCreate(savedInstanceState: Bundle?) {
45 | super.onCreate(savedInstanceState)
46 |
47 | WindowCompat.setDecorFitsSystemWindows(window, false)
48 | }
49 | ```
50 |
51 | Detail: [Lay out your app within window insets](https://developer.android.com/develop/ui/views/layout/insets)
52 |
53 | ### iOS
54 |
55 | 1. (option) If you want to use the `WindowInsetsController`, use `WindowInsetsUIViewController` instead of `ComposeUIViewController`.
56 |
57 | ```kotlin
58 | fun MainUIViewController(): UIViewController {
59 | return WindowInsetsUIViewController {
60 | MyApp()
61 | }
62 | }
63 | ```
64 |
65 | ## How to use
66 | ### WindowInsets
67 | This works much like Android's WindowInsets.
68 | Please note that the package name is different.
69 |
70 | ```kotlin
71 | import androidx.compose.foundation.layout.windowInsetsPadding
72 | import androidx.compose.foundation.layout.WindowInsets
73 | import androidx.compose.runtime.Composable
74 | import androidx.compose.ui.Modifier
75 | import com.moriatsushi.insetsx.systemBars
76 | import com.moriatsushi.insetsx.systemBarsPadding
77 |
78 | @Composable
79 | fun Sample() {
80 | val modifier1 = Modifier
81 | .windowInsetsPadding(WindowInsets.safeDrawing)
82 |
83 | val modifier2 = Modifier
84 | .safeDrawingPadding()
85 | }
86 | ```
87 |
88 | API|android|ios
89 | :--|:--|:--
90 | WindowInsets.safeArea|system bars + display cutouts|SafeArea
91 | WindowInsets.systemBars|status bar + navigation bar|home indicator + status bar
92 | WindowInsets.navigationBars|navigation bar|home indicator
93 | WindowInsets.statusBars|status bar|status bar
94 | WindowInsets.ime *1|software keyboard|software keyboard
95 | WindowInsets.safeDrawing *1|system bars + software keyboard|SafeArea + software keyboard
96 | (Modifier)||
97 | Modifier.safeAreaPadding()|system bars + display cutouts|SafeArea
98 | Modifier.systemBarsPadding()|status bar + navigation bar|home indicator + status bar
99 | Modifier.navigationBarsPadding()|navigation bar|home indicator
100 | Modifier.statusBarsPadding()|status bar|status bar
101 | Modifier.imePadding() *1|software keyboard|software keyboard
102 | Modifier.safeDrawingPadding() *1|system bars + software keyboard|SafeArea + software keyboard
103 |
104 | *1 is experimental
105 |
106 | ### WindowInsetsController
107 | `WindowInsetsController` can be used to change colors of system bars.
108 |
109 | ```kotlin
110 | @Composable
111 | fun Sample() {
112 | val windowInsetsController = rememberWindowInsetsController()
113 | LaunchedEffect(Unit) {
114 | // The status bars icon + content will change to a light color
115 | windowInsetsController?.setStatusBarContentColor(dark = false)
116 | // The navigation bars icons will change to a light color (android only)
117 | windowInsetsController?.setNavigationBarsContentColor(dark = false)
118 | }
119 | }
120 | ```
121 |
122 | You can also hide WindowInsets.
123 |
124 | ```kotlin
125 | @Composable
126 | fun Sample() {
127 | val windowInsetsController = rememberWindowInsetsController()
128 | LaunchedEffect(Unit) {
129 | // Hide the status bars
130 | windowInsetsController?.setIsStatusBarsVisible(false)
131 | // Hide the navigation bars
132 | windowInsetsController?.setIsNavigationBarsVisible(false)
133 | // Change an options for behavior when system bars are hidden
134 | windowInsetsController?.setSystemBarsBehavior(SystemBarsBehavior.Immersive)
135 | }
136 | }
137 | ```
138 |
--------------------------------------------------------------------------------
/build.gradle.kts:
--------------------------------------------------------------------------------
1 | import com.diffplug.gradle.spotless.SpotlessExtension
2 | import com.diffplug.gradle.spotless.SpotlessPlugin
3 |
4 | plugins {
5 | val kotlinVersion = libs.versions.kotlin.get()
6 |
7 | kotlin("multiplatform").version(kotlinVersion) apply false
8 | alias(libs.plugins.android.library) apply false
9 | alias(libs.plugins.android.application) apply false
10 | alias(libs.plugins.jetbrains.compose) apply false
11 | alias(libs.plugins.spotless) apply false
12 | alias(libs.plugins.publish)
13 | }
14 |
15 | subprojects {
16 | apply()
17 |
18 | extensions.configure {
19 | kotlin {
20 | target("**/*.kt")
21 | val ktlintVersion = libs.versions.ktlint.get()
22 | targetExclude("**/build/**/*.kt")
23 | ktlint(ktlintVersion)
24 | .editorConfigOverride(
25 | mapOf(
26 | "ktlint_code_style" to "android",
27 | "ij_kotlin_allow_trailing_comma" to true,
28 | )
29 | )
30 | }
31 | }
32 |
33 | configurations.all {
34 | val conf = this
35 | conf.resolutionStrategy.eachDependency {
36 | val isWasm = conf.name.contains("wasm", true)
37 | val isJs = conf.name.contains("js", true)
38 | val isComposeGroup = requested.module.group.startsWith("org.jetbrains.compose")
39 | val isComposeCompiler = requested.module.group.startsWith("org.jetbrains.compose.compiler")
40 | if (isComposeGroup && !isComposeCompiler && !isWasm && !isJs) {
41 | useVersion("1.4.0")
42 | }
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/example/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/example/build.gradle.kts:
--------------------------------------------------------------------------------
1 | import org.jetbrains.kotlin.gradle.targets.js.webpack.KotlinWebpackConfig
2 | import org.jetbrains.compose.experimental.dsl.IOSDevices
3 |
4 | plugins {
5 | kotlin("multiplatform")
6 | alias(libs.plugins.android.application)
7 | alias(libs.plugins.jetbrains.compose)
8 | }
9 |
10 | kotlin {
11 | android()
12 | listOf(
13 | iosX64("uikitX64"),
14 | iosArm64("uikitArm64"),
15 | iosSimulatorArm64("uikitSimArm64")
16 | ).forEach {
17 | it.binaries {
18 | executable {
19 | entryPoint = "main"
20 | freeCompilerArgs += listOf(
21 | "-linker-option", "-framework", "-linker-option", "Metal",
22 | "-linker-option", "-framework", "-linker-option", "CoreText",
23 | "-linker-option", "-framework", "-linker-option", "CoreGraphics",
24 | "-Xverify-compiler=false", // Workaround for https://youtrack.jetbrains.com/issue/KT-53561
25 | )
26 | }
27 | }
28 | }
29 |
30 | jvm("desktop")
31 |
32 | macosX64 {
33 | binaries {
34 | executable {
35 | entryPoint = "main"
36 | }
37 | }
38 | }
39 | macosArm64 {
40 | binaries {
41 | executable {
42 | entryPoint = "main"
43 | }
44 | }
45 | }
46 |
47 | wasm {
48 | moduleName = "insetsx-example"
49 | browser {
50 | commonWebpackConfig {
51 | devServer = (devServer ?: KotlinWebpackConfig.DevServer()).copy(
52 | open = mapOf(
53 | "app" to mapOf("name" to "google chrome")
54 | ),
55 | )
56 | }
57 | }
58 | binaries.executable()
59 | }
60 |
61 | sourceSets {
62 | val commonMain by getting {
63 | dependencies {
64 | implementation(project(":insetsx"))
65 | implementation(compose.ui)
66 | implementation(compose.foundation)
67 | implementation(compose.material3)
68 | implementation(compose.materialIconsExtended)
69 | implementation(compose.runtime)
70 |
71 | // Workaround for https://youtrack.jetbrains.com/issue/KT-41821
72 | implementation(libs.kotlinx.atomicfu)
73 | }
74 | }
75 |
76 | val androidMain by getting {
77 | dependsOn(commonMain)
78 | dependencies {
79 | implementation(libs.androidx.appcompat)
80 | implementation(libs.androidx.activity.compose)
81 | }
82 | }
83 | val uikitMain by creating {
84 | dependsOn(commonMain)
85 | }
86 | val uikitX64Main by getting {
87 | dependsOn(uikitMain)
88 | }
89 | val uikitArm64Main by getting {
90 | dependsOn(uikitMain)
91 | }
92 | val uikitSimArm64Main by getting {
93 | dependsOn(uikitMain)
94 | }
95 | val macosMain by creating {
96 | dependsOn(commonMain)
97 | }
98 | val macosX64Main by getting {
99 | dependsOn(macosMain)
100 | }
101 | val macosArm64Main by getting {
102 | dependsOn(macosMain)
103 | }
104 | val desktopMain by getting {
105 | dependsOn(commonMain)
106 |
107 | dependencies {
108 | implementation(compose.desktop.currentOs)
109 | }
110 | }
111 | val wasmMain by getting {
112 | dependsOn(commonMain)
113 | }
114 | }
115 | }
116 |
117 | compose {
118 | experimental {
119 | uikit.application {
120 | bundleIdPrefix = "com.moriatsushi"
121 | projectName = "InsetsX"
122 | deployConfigurations {
123 | simulator("IPhone13") {
124 | //Usage: ./gradlew :example:iosDeployIPhone13Debug
125 | device = IOSDevices.IPHONE_13
126 | }
127 | simulator("iPhone8") {
128 | //Usage: ./gradlew :example:iosDeployIPhone13Debug
129 | device = IOSDevices.IPHONE_8
130 | }
131 | simulator("IPad") {
132 | //Usage: ./gradlew :example:iosDeployIPadDebug
133 | device = IOSDevices.IPAD_MINI_6th_Gen
134 | }
135 | connectedDevice("Device") {
136 | //First need specify your teamId here, or in local.properties (compose.ios.teamId=***)
137 | //teamId="***"
138 | //Usage: ./gradlew :example:iosDeployDeviceRelease
139 | }
140 | }
141 | }
142 |
143 | web.application {}
144 | }
145 |
146 | desktop.application {
147 | mainClass = "Main_desktopKt"
148 | }
149 | }
150 |
151 | android {
152 | namespace = "com.moriatsushi.insetsx.example"
153 | compileSdk = 33
154 | defaultConfig {
155 | minSdk = 21
156 | targetSdk = 33
157 | }
158 |
159 | buildTypes {
160 | release {
161 | isMinifyEnabled = true
162 | proguardFiles(
163 | getDefaultProguardFile("proguard-android-optimize.txt"),
164 | "proguard-rules.pro"
165 | )
166 | signingConfig = signingConfigs.getByName("debug")
167 | }
168 | }
169 |
170 | compileOptions {
171 | sourceCompatibility = JavaVersion.VERSION_17
172 | targetCompatibility = JavaVersion.VERSION_17
173 | }
174 |
175 | sourceSets {
176 | named("main") {
177 | manifest.srcFile("src/androidMain/AndroidManifest.xml")
178 | res.srcDirs("src/androidMain/res", "src/commonMain/resources")
179 | }
180 | }
181 | }
182 |
--------------------------------------------------------------------------------
/example/consumer-rules.pro:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mori-atsushi/insetsx/1be176bee608c2d30817e8e82a013bc653b36031/example/consumer-rules.pro
--------------------------------------------------------------------------------
/example/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/example/src/androidMain/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
9 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/example/src/androidMain/kotlin/com/moriatsushi/insetsx/example/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.moriatsushi.insetsx.example
2 |
3 | import android.graphics.Color
4 | import android.os.Bundle
5 | import androidx.activity.compose.setContent
6 | import androidx.appcompat.app.AppCompatActivity
7 | import androidx.core.view.WindowCompat
8 |
9 | class MainActivity : AppCompatActivity() {
10 | override fun onCreate(savedInstanceState: Bundle?) {
11 | super.onCreate(savedInstanceState)
12 |
13 | WindowCompat.setDecorFitsSystemWindows(window, false)
14 | window.statusBarColor = Color.TRANSPARENT
15 | window.navigationBarColor = Color.TRANSPARENT
16 |
17 | setContent {
18 | ExampleApp()
19 | }
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/example/src/androidMain/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | InsetsX
4 |
5 |
--------------------------------------------------------------------------------
/example/src/commonMain/kotlin/com.moriatsushi.insetsx.example/ExampleApp.kt:
--------------------------------------------------------------------------------
1 | package com.moriatsushi.insetsx.example
2 |
3 | import androidx.compose.foundation.isSystemInDarkTheme
4 | import androidx.compose.foundation.layout.Box
5 | import androidx.compose.foundation.layout.ExperimentalLayoutApi
6 | import androidx.compose.foundation.layout.WindowInsets
7 | import androidx.compose.foundation.layout.WindowInsetsSides
8 | import androidx.compose.foundation.layout.consumeWindowInsets
9 | import androidx.compose.foundation.layout.fillMaxSize
10 | import androidx.compose.foundation.layout.only
11 | import androidx.compose.foundation.layout.padding
12 | import androidx.compose.material.icons.Icons
13 | import androidx.compose.material.icons.filled.Menu
14 | import androidx.compose.material.icons.filled.Nightlight
15 | import androidx.compose.material3.BottomAppBar
16 | import androidx.compose.material3.ExperimentalMaterial3Api
17 | import androidx.compose.material3.Icon
18 | import androidx.compose.material3.IconButton
19 | import androidx.compose.material3.MaterialTheme
20 | import androidx.compose.material3.Scaffold
21 | import androidx.compose.material3.Text
22 | import androidx.compose.material3.TextField
23 | import androidx.compose.material3.TopAppBar
24 | import androidx.compose.material3.darkColorScheme
25 | import androidx.compose.material3.lightColorScheme
26 | import androidx.compose.runtime.Composable
27 | import androidx.compose.runtime.LaunchedEffect
28 | import androidx.compose.runtime.getValue
29 | import androidx.compose.runtime.key
30 | import androidx.compose.runtime.mutableStateOf
31 | import androidx.compose.runtime.remember
32 | import androidx.compose.runtime.saveable.rememberSaveable
33 | import androidx.compose.runtime.setValue
34 | import androidx.compose.ui.Alignment
35 | import androidx.compose.ui.Modifier
36 | import com.moriatsushi.insetsx.ExperimentalSoftwareKeyboardApi
37 | import com.moriatsushi.insetsx.imePadding
38 | import com.moriatsushi.insetsx.rememberWindowInsetsController
39 | import com.moriatsushi.insetsx.safeArea
40 | import com.moriatsushi.insetsx.systemBars
41 |
42 | @Composable
43 | fun ExampleApp() {
44 | val isSystemInDarkTheme = isSystemInDarkTheme()
45 | var useDarkMode by rememberSaveable { mutableStateOf(isSystemInDarkTheme) }
46 |
47 | val windowInsetsController = rememberWindowInsetsController()
48 | LaunchedEffect(useDarkMode) {
49 | windowInsetsController?.apply {
50 | setStatusBarContentColor(dark = !useDarkMode)
51 | setNavigationBarsContentColor(dark = !useDarkMode)
52 | }
53 | }
54 |
55 | MaterialTheme(
56 | colorScheme = if (useDarkMode) darkColorScheme() else lightColorScheme()
57 | ) {
58 | key(useDarkMode) {
59 | ExampleApp(
60 | onToggleDarkMode = { useDarkMode = !useDarkMode }
61 | )
62 | }
63 | }
64 | }
65 |
66 | @OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
67 | @Composable
68 | private fun ExampleApp(
69 | onToggleDarkMode: () -> Unit,
70 | modifier: Modifier = Modifier,
71 | ) {
72 | Scaffold(
73 | modifier = modifier,
74 | topBar = {
75 | ExampleTopAppBar(onToggleDarkMode = onToggleDarkMode)
76 | },
77 | bottomBar = {
78 | ExampleBottomAppBar()
79 | },
80 | contentWindowInsets = WindowInsets.systemBars
81 | ) {
82 | ExampleContent(
83 | modifier = Modifier
84 | .padding(it)
85 | .consumeWindowInsets(it)
86 | )
87 | }
88 | }
89 |
90 | @OptIn(ExperimentalMaterial3Api::class)
91 | @Composable
92 | private fun ExampleTopAppBar(
93 | modifier: Modifier = Modifier,
94 | onToggleDarkMode: () -> Unit,
95 | ) {
96 | TopAppBar(
97 | modifier = modifier,
98 | title = { Text("InsetsX") },
99 | actions = {
100 | IconButton(onClick = onToggleDarkMode) {
101 | Icon(
102 | imageVector = Icons.Filled.Nightlight,
103 | contentDescription = null
104 | )
105 | }
106 | },
107 | windowInsets = WindowInsets.safeArea.only(
108 | WindowInsetsSides.Top + WindowInsetsSides.Horizontal
109 | )
110 | )
111 | }
112 |
113 | @Composable
114 | private fun ExampleBottomAppBar(
115 | modifier: Modifier = Modifier,
116 | ) {
117 | BottomAppBar(
118 | modifier = modifier,
119 | windowInsets = WindowInsets.safeArea.only(
120 | WindowInsetsSides.Bottom + WindowInsetsSides.Horizontal
121 | )
122 | ) {
123 | IconButton(onClick = { /* no op */ }) {
124 | Icon(
125 | imageVector = Icons.Filled.Menu,
126 | contentDescription = "Menu Button"
127 | )
128 | }
129 | }
130 | }
131 |
132 | @OptIn(ExperimentalMaterial3Api::class, ExperimentalSoftwareKeyboardApi::class)
133 | @Composable
134 | private fun ExampleContent(
135 | modifier: Modifier = Modifier,
136 | ) {
137 | var text by remember { mutableStateOf("") }
138 | Box(
139 | modifier = modifier
140 | .fillMaxSize()
141 | .imePadding(),
142 | contentAlignment = Alignment.Center
143 | ) {
144 | TextField(
145 | value = text,
146 | onValueChange = { text = it },
147 | placeholder = { Text("Text Field") }
148 | )
149 | }
150 | }
151 |
--------------------------------------------------------------------------------
/example/src/desktopMain/kotlin/Main.desktop.kt:
--------------------------------------------------------------------------------
1 | import androidx.compose.ui.unit.dp
2 | import androidx.compose.ui.window.Window
3 | import androidx.compose.ui.window.application
4 | import androidx.compose.ui.window.rememberWindowState
5 | import com.moriatsushi.insetsx.example.ExampleApp
6 |
7 | fun main() = application {
8 | Window(
9 | title = "InsetsX",
10 | state = rememberWindowState(width = 600.dp, height = 800.dp),
11 | onCloseRequest = ::exitApplication
12 | ) {
13 | ExampleApp()
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/example/src/macosMain/kotlin/Main.macos.kt:
--------------------------------------------------------------------------------
1 | import androidx.compose.ui.window.Window
2 | import com.moriatsushi.insetsx.example.ExampleApp
3 | import platform.AppKit.NSApp
4 | import platform.AppKit.NSApplication
5 |
6 | fun main() {
7 | NSApplication.sharedApplication()
8 | Window("Chat App") {
9 | ExampleApp()
10 | }
11 | NSApp?.run()
12 | }
13 |
--------------------------------------------------------------------------------
/example/src/uikitMain/kotlin/Main.uikit.kt:
--------------------------------------------------------------------------------
1 | import androidx.compose.ui.main.defaultUIKitMain
2 | import com.moriatsushi.insetsx.WindowInsetsUIViewController
3 | import com.moriatsushi.insetsx.example.ExampleApp
4 |
5 | fun main() {
6 | defaultUIKitMain(
7 | "InsetsX",
8 | WindowInsetsUIViewController {
9 | ExampleApp()
10 | }
11 | )
12 | }
13 |
--------------------------------------------------------------------------------
/example/src/wasmMain/kotlin/Main.wasm.kt:
--------------------------------------------------------------------------------
1 | import androidx.compose.ui.ExperimentalComposeUiApi
2 | import androidx.compose.ui.window.CanvasBasedWindow
3 | import com.moriatsushi.insetsx.example.ExampleApp
4 |
5 | @OptIn(ExperimentalComposeUiApi::class)
6 | fun main() {
7 | CanvasBasedWindow("InsetsX", canvasElementId = "canvas") {
8 | ExampleApp()
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/example/src/wasmMain/resources/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | InsetsX
6 |
7 |
8 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/example/src/wasmMain/resources/load.mjs:
--------------------------------------------------------------------------------
1 | import { instantiate } from './insetsx-example.uninstantiated.mjs';
2 |
3 | await wasmSetup;
4 |
5 | let te = null;
6 | try {
7 | await instantiate({ skia: Module['asm'] });
8 | } catch (e) {
9 | te = e;
10 | }
11 |
12 | if (te == null) {
13 | document.getElementById("warning").style.display="none";
14 | } else {
15 | throw te;
16 | }
17 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | #Gradle
2 | org.gradle.jvmargs=-Xmx2048M -Dfile.encoding=UTF-8 -Dkotlin.daemon.jvm.options\="-Xmx2048M"
3 |
4 | #Kotlin
5 | kotlin.code.style=official
6 |
7 | #Android
8 | android.useAndroidX=true
9 | android.nonTransitiveRClass=true
10 |
11 | #MPP
12 | kotlin.mpp.enableCInteropCommonization=true
13 | kotlin.mpp.stability.nowarn=true
14 | kotlin.mpp.androidSourceSetLayoutVersion=2
15 | kotlin.native.binary.memoryModel=experimental
16 | kotlin.native.cacheKind=none
17 |
18 | #compose
19 | org.jetbrains.compose.experimental.uikit.enabled=true
20 | org.jetbrains.compose.experimental.macos.enabled=true
21 | org.jetbrains.compose.experimental.jscanvas.enabled=true
22 |
23 | # Maven Central
24 | SONATYPE_HOST=S01
25 | RELEASE_SIGNING_ENABLED=true
26 | GROUP=com.moriatsushi.insetsx
27 | VERSION_NAME=0.1.0-alpha10
28 |
29 | POM_NAME=InsetsX
30 | POM_DESCRIPTION=WindowInsets utility for compose multiplatform
31 | POM_INCEPTION_YEAR=2023
32 | POM_URL=https://github.com/mori-atsushi/insetsx
33 |
34 | POM_LICENSE_NAME=The Apache Software License, Version 2.0
35 | POM_LICENSE_URL=https://www.apache.org/licenses/LICENSE-2.0.txt
36 | POM_LICENSE_DIST=repo
37 |
38 | POM_SCM_URL=https://github.com/mori-atsushi/insetsx
39 | POM_SCM_CONNECTION=scm:git:https://github.com/mori-atsushi/insetsx
40 | POM_SCM_DEV_CONNECTION=scm:git:https://github.com/mori-atsushi/insetsx
41 |
42 | POM_DEVELOPER_ID=moriatsushi
43 | POM_DEVELOPER_NAME=Mori Atsushi
44 | POM_DEVELOPER_URL=https://github.com/mori-atsushi/
45 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mori-atsushi/insetsx/1be176bee608c2d30817e8e82a013bc653b36031/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip
4 | networkTimeout=10000
5 | validateDistributionUrl=true
6 | zipStoreBase=GRADLE_USER_HOME
7 | zipStorePath=wrapper/dists
8 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | #
4 | # Copyright © 2015-2021 the original authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | #
21 | # Gradle start up script for POSIX generated by Gradle.
22 | #
23 | # Important for running:
24 | #
25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
26 | # noncompliant, but you have some other compliant shell such as ksh or
27 | # bash, then to run this script, type that shell name before the whole
28 | # command line, like:
29 | #
30 | # ksh Gradle
31 | #
32 | # Busybox and similar reduced shells will NOT work, because this script
33 | # requires all of these POSIX shell features:
34 | # * functions;
35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»;
37 | # * compound commands having a testable exit status, especially «case»;
38 | # * various built-in commands including «command», «set», and «ulimit».
39 | #
40 | # Important for patching:
41 | #
42 | # (2) This script targets any POSIX shell, so it avoids extensions provided
43 | # by Bash, Ksh, etc; in particular arrays are avoided.
44 | #
45 | # The "traditional" practice of packing multiple parameters into a
46 | # space-separated string is a well documented source of bugs and security
47 | # problems, so this is (mostly) avoided, by progressively accumulating
48 | # options in "$@", and eventually passing that to Java.
49 | #
50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
52 | # see the in-line comments for details.
53 | #
54 | # There are tweaks for specific operating systems such as AIX, CygWin,
55 | # Darwin, MinGW, and NonStop.
56 | #
57 | # (3) This script is generated from the Groovy template
58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
59 | # within the Gradle project.
60 | #
61 | # You can find Gradle at https://github.com/gradle/gradle/.
62 | #
63 | ##############################################################################
64 |
65 | # Attempt to set APP_HOME
66 |
67 | # Resolve links: $0 may be a link
68 | app_path=$0
69 |
70 | # Need this for daisy-chained symlinks.
71 | while
72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
73 | [ -h "$app_path" ]
74 | do
75 | ls=$( ls -ld "$app_path" )
76 | link=${ls#*' -> '}
77 | case $link in #(
78 | /*) app_path=$link ;; #(
79 | *) app_path=$APP_HOME$link ;;
80 | esac
81 | done
82 |
83 | # This is normally unused
84 | # shellcheck disable=SC2034
85 | APP_BASE_NAME=${0##*/}
86 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
87 | APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
88 |
89 | # Use the maximum available, or set MAX_FD != -1 to use that value.
90 | MAX_FD=maximum
91 |
92 | warn () {
93 | echo "$*"
94 | } >&2
95 |
96 | die () {
97 | echo
98 | echo "$*"
99 | echo
100 | exit 1
101 | } >&2
102 |
103 | # OS specific support (must be 'true' or 'false').
104 | cygwin=false
105 | msys=false
106 | darwin=false
107 | nonstop=false
108 | case "$( uname )" in #(
109 | CYGWIN* ) cygwin=true ;; #(
110 | Darwin* ) darwin=true ;; #(
111 | MSYS* | MINGW* ) msys=true ;; #(
112 | NONSTOP* ) nonstop=true ;;
113 | esac
114 |
115 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
116 |
117 |
118 | # Determine the Java command to use to start the JVM.
119 | if [ -n "$JAVA_HOME" ] ; then
120 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
121 | # IBM's JDK on AIX uses strange locations for the executables
122 | JAVACMD=$JAVA_HOME/jre/sh/java
123 | else
124 | JAVACMD=$JAVA_HOME/bin/java
125 | fi
126 | if [ ! -x "$JAVACMD" ] ; then
127 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
128 |
129 | Please set the JAVA_HOME variable in your environment to match the
130 | location of your Java installation."
131 | fi
132 | else
133 | JAVACMD=java
134 | if ! command -v java >/dev/null 2>&1
135 | then
136 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
137 |
138 | Please set the JAVA_HOME variable in your environment to match the
139 | location of your Java installation."
140 | fi
141 | fi
142 |
143 | # Increase the maximum file descriptors if we can.
144 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
145 | case $MAX_FD in #(
146 | max*)
147 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
148 | # shellcheck disable=SC2039,SC3045
149 | MAX_FD=$( ulimit -H -n ) ||
150 | warn "Could not query maximum file descriptor limit"
151 | esac
152 | case $MAX_FD in #(
153 | '' | soft) :;; #(
154 | *)
155 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
156 | # shellcheck disable=SC2039,SC3045
157 | ulimit -n "$MAX_FD" ||
158 | warn "Could not set maximum file descriptor limit to $MAX_FD"
159 | esac
160 | fi
161 |
162 | # Collect all arguments for the java command, stacking in reverse order:
163 | # * args from the command line
164 | # * the main class name
165 | # * -classpath
166 | # * -D...appname settings
167 | # * --module-path (only if needed)
168 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
169 |
170 | # For Cygwin or MSYS, switch paths to Windows format before running java
171 | if "$cygwin" || "$msys" ; then
172 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
173 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
174 |
175 | JAVACMD=$( cygpath --unix "$JAVACMD" )
176 |
177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
178 | for arg do
179 | if
180 | case $arg in #(
181 | -*) false ;; # don't mess with options #(
182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
183 | [ -e "$t" ] ;; #(
184 | *) false ;;
185 | esac
186 | then
187 | arg=$( cygpath --path --ignore --mixed "$arg" )
188 | fi
189 | # Roll the args list around exactly as many times as the number of
190 | # args, so each arg winds up back in the position where it started, but
191 | # possibly modified.
192 | #
193 | # NB: a `for` loop captures its iteration list before it begins, so
194 | # changing the positional parameters here affects neither the number of
195 | # iterations, nor the values presented in `arg`.
196 | shift # remove old arg
197 | set -- "$@" "$arg" # push replacement arg
198 | done
199 | fi
200 |
201 |
202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
204 |
205 | # Collect all arguments for the java command:
206 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
207 | # and any embedded shellness will be escaped.
208 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
209 | # treated as '${Hostname}' itself on the command line.
210 |
211 | set -- \
212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \
213 | -classpath "$CLASSPATH" \
214 | org.gradle.wrapper.GradleWrapperMain \
215 | "$@"
216 |
217 | # Stop when "xargs" is not available.
218 | if ! command -v xargs >/dev/null 2>&1
219 | then
220 | die "xargs is not available"
221 | fi
222 |
223 | # Use "xargs" to parse quoted args.
224 | #
225 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed.
226 | #
227 | # In Bash we could simply go:
228 | #
229 | # readarray ARGS < <( xargs -n1 <<<"$var" ) &&
230 | # set -- "${ARGS[@]}" "$@"
231 | #
232 | # but POSIX shell has neither arrays nor command substitution, so instead we
233 | # post-process each arg (as a line of input to sed) to backslash-escape any
234 | # character that might be a shell metacharacter, then use eval to reverse
235 | # that process (while maintaining the separation between arguments), and wrap
236 | # the whole thing up as a single "set" statement.
237 | #
238 | # This will of course break if any of these variables contains a newline or
239 | # an unmatched quote.
240 | #
241 |
242 | eval "set -- $(
243 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
244 | xargs -n1 |
245 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
246 | tr '\n' ' '
247 | )" '"$@"'
248 |
249 | exec "$JAVACMD" "$@"
250 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%"=="" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%"=="" set DIRNAME=.
29 | @rem This is normally unused
30 | set APP_BASE_NAME=%~n0
31 | set APP_HOME=%DIRNAME%
32 |
33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
35 |
36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
38 |
39 | @rem Find java.exe
40 | if defined JAVA_HOME goto findJavaFromJavaHome
41 |
42 | set JAVA_EXE=java.exe
43 | %JAVA_EXE% -version >NUL 2>&1
44 | if %ERRORLEVEL% equ 0 goto execute
45 |
46 | echo.
47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
48 | echo.
49 | echo Please set the JAVA_HOME variable in your environment to match the
50 | echo location of your Java installation.
51 |
52 | goto fail
53 |
54 | :findJavaFromJavaHome
55 | set JAVA_HOME=%JAVA_HOME:"=%
56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
57 |
58 | if exist "%JAVA_EXE%" goto execute
59 |
60 | echo.
61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
62 | echo.
63 | echo Please set the JAVA_HOME variable in your environment to match the
64 | echo location of your Java installation.
65 |
66 | goto fail
67 |
68 | :execute
69 | @rem Setup the command line
70 |
71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
72 |
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if %ERRORLEVEL% equ 0 goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | set EXIT_CODE=%ERRORLEVEL%
85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1
86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
87 | exit /b %EXIT_CODE%
88 |
89 | :mainEnd
90 | if "%OS%"=="Windows_NT" endlocal
91 |
92 | :omega
93 |
--------------------------------------------------------------------------------
/insetsx/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | kotlin("multiplatform")
3 | alias(libs.plugins.android.library)
4 | alias(libs.plugins.jetbrains.compose)
5 | alias(libs.plugins.publish)
6 | }
7 |
8 | kotlin {
9 | android {
10 | publishLibraryVariants("release")
11 | }
12 |
13 | listOf(
14 | iosX64("uikitX64"),
15 | iosArm64("uikitArm64"),
16 | iosSimulatorArm64("uikitSimArm64")
17 | ).forEach {
18 | it.binaries.framework {
19 | baseName = "insetsx"
20 | }
21 | it.compilations.getByName("main") {
22 | cinterops {
23 | // Workaround to override uikit classes
24 | val uikit by cinterops.creating {
25 | }
26 | }
27 | }
28 | }
29 |
30 | macosX64()
31 | macosArm64()
32 |
33 | jvm("desktop")
34 |
35 | js(IR) {
36 | browser()
37 | }
38 |
39 | wasm {
40 | browser()
41 | }
42 |
43 | sourceSets {
44 | val commonMain by getting {
45 | dependencies {
46 | implementation(compose.foundation)
47 | implementation(compose.runtime)
48 |
49 | // Workaround for https://youtrack.jetbrains.com/issue/KT-41821
50 | implementation(libs.kotlinx.atomicfu)
51 | }
52 | }
53 | val commonTest by getting {
54 | dependencies {
55 | implementation(kotlin("test"))
56 | }
57 | }
58 | val androidMain by getting {
59 | dependencies {
60 | implementation(libs.accompanist.systemuicontroller)
61 | implementation(libs.androidx.core)
62 | }
63 | }
64 | val androidUnitTest by getting
65 | val uikitMain by creating {
66 | dependsOn(commonMain)
67 | }
68 | val uikitX64Main by getting {
69 | dependsOn(uikitMain)
70 | }
71 | val uikitArm64Main by getting {
72 | dependsOn(uikitMain)
73 | }
74 | val uikitSimArm64Main by getting {
75 | dependsOn(uikitMain)
76 | }
77 | val uikitTest by creating {
78 | dependsOn(commonTest)
79 | }
80 | val noOpMain by creating {
81 | dependsOn(commonMain)
82 | }
83 | val macosX64Main by getting {
84 | dependsOn(noOpMain)
85 | }
86 | val macosArm64Main by getting {
87 | dependsOn(noOpMain)
88 | }
89 | val desktopMain by getting {
90 | dependsOn(noOpMain)
91 | }
92 | val jsMain by getting {
93 | dependsOn(noOpMain)
94 | }
95 | val wasmMain by getting {
96 | dependsOn(noOpMain)
97 | }
98 | }
99 | }
100 |
101 | android {
102 | namespace = "com.moriatsushi.insetsx"
103 | compileSdk = 33
104 | defaultConfig {
105 | minSdk = 21
106 | }
107 |
108 | buildFeatures {
109 | buildConfig = false
110 | }
111 |
112 | compileOptions {
113 | sourceCompatibility = JavaVersion.VERSION_17
114 | targetCompatibility = JavaVersion.VERSION_17
115 | }
116 | }
117 |
--------------------------------------------------------------------------------
/insetsx/gradle.properties:
--------------------------------------------------------------------------------
1 | # Maven Central
2 | POM_ARTIFACT_ID=insetsx
3 | POM_NAME=InsetsX
4 | POM_DESCRIPTION=WindowInsets utility for compose multiplatform
5 | POM_PACKAGING=aar
6 |
--------------------------------------------------------------------------------
/insetsx/src/androidMain/kotlin/com/moriatsushi/insetsx/SystemBarsBehavior.android.kt:
--------------------------------------------------------------------------------
1 | package com.moriatsushi.insetsx
2 |
3 | import androidx.core.view.WindowInsetsControllerCompat
4 |
5 | /**
6 | * A class that represents options for behavior when system bars are hidden.
7 | */
8 | actual class SystemBarsBehavior private constructor(
9 | internal val value: Int,
10 | ) {
11 | actual companion object {
12 | /**
13 | * Default option to to remain interactive when hiding system bars.
14 | * The system bars can be revealed with system gestures,
15 | * such as swiping from the edge.
16 | */
17 | actual val Default: SystemBarsBehavior = SystemBarsBehavior(
18 | WindowInsetsControllerCompat.BEHAVIOR_DEFAULT
19 | )
20 |
21 | /**
22 | * An immersive mode that limits user interaction when system bars are hidden.
23 | * The system bar can be revealed temporarily with system gestures,
24 | * but disappears after a period of time.
25 | */
26 | actual val Immersive: SystemBarsBehavior = SystemBarsBehavior(
27 | WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
28 | )
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/insetsx/src/androidMain/kotlin/com/moriatsushi/insetsx/WindowInsets.android.kt:
--------------------------------------------------------------------------------
1 | package com.moriatsushi.insetsx
2 |
3 | import androidx.compose.foundation.layout.WindowInsets
4 | import androidx.compose.foundation.layout.captionBar as androidCaptionBar
5 | import androidx.compose.foundation.layout.displayCutout as androidDisplayCutout
6 | import androidx.compose.foundation.layout.ime as androidIme
7 | import androidx.compose.foundation.layout.mandatorySystemGestures as androidMandatorySystemGestures
8 | import androidx.compose.foundation.layout.navigationBars as androidNavigationBars
9 | import androidx.compose.foundation.layout.safeContent as androidSafeContent
10 | import androidx.compose.foundation.layout.safeDrawing as androidSafeDrawing
11 | import androidx.compose.foundation.layout.safeGestures as androidSafeGestures
12 | import androidx.compose.foundation.layout.statusBars as androidStatusBars
13 | import androidx.compose.foundation.layout.systemBars as androidSystemBars
14 | import androidx.compose.foundation.layout.systemGestures as androidSystemGestures
15 | import androidx.compose.foundation.layout.tappableElement as androidTappableElement
16 | import androidx.compose.foundation.layout.union
17 | import androidx.compose.foundation.layout.waterfall as androidWaterfall
18 | import androidx.compose.runtime.Composable
19 | import androidx.compose.runtime.NonRestartableComposable
20 |
21 | /**
22 | * The insets representing navigation bars.
23 | */
24 | actual val WindowInsets.Companion.navigationBars: WindowInsets
25 | @Composable
26 | @NonRestartableComposable
27 | get() = androidNavigationBars
28 |
29 | /**
30 | * The insets representing a caption bar.
31 | */
32 | actual val WindowInsets.Companion.captionBar: WindowInsets
33 | @Composable
34 | @NonRestartableComposable
35 | get() = androidCaptionBar
36 |
37 | /**
38 | * The insets representing status bars.
39 | */
40 | actual val WindowInsets.Companion.statusBars: WindowInsets
41 | @Composable
42 | @NonRestartableComposable
43 | get() = androidStatusBars
44 |
45 | /**
46 | * The insets representing system bars, but not including ime.
47 | */
48 | actual val WindowInsets.Companion.systemBars: WindowInsets
49 | @Composable
50 | @NonRestartableComposable
51 | get() = androidSystemBars
52 |
53 | /**
54 | * The insets representing system gestures that have priority and may consume some or all touch
55 | * input.
56 | */
57 | actual val WindowInsets.Companion.systemGestures: WindowInsets
58 | @Composable
59 | @NonRestartableComposable
60 | get() = androidSystemGestures
61 |
62 | /**
63 | * The insets representing the tappable element.
64 | */
65 | actual val WindowInsets.Companion.tappableElement: WindowInsets
66 | @Composable
67 | @NonRestartableComposable
68 | get() = androidTappableElement
69 |
70 | /**
71 | * The insets that include unsafe areas such as system bars and display cutouts,
72 | * but not including ime.
73 | */
74 | actual val WindowInsets.Companion.safeArea: WindowInsets
75 | @Composable
76 | @NonRestartableComposable
77 | get() = androidSystemBars.union(androidDisplayCutout)
78 |
79 | /**
80 | * The insets representing curved areas in a waterfall display.
81 | */
82 | actual val WindowInsets.Companion.waterfall: WindowInsets
83 | @Composable
84 | @NonRestartableComposable
85 | get() = androidWaterfall
86 |
87 | /**
88 | * The insets representing system gestures that have priority and may consume some or all touch
89 | * input.
90 | */
91 | actual val WindowInsets.Companion.mandatorySystemGestures: WindowInsets
92 | @Composable
93 | @NonRestartableComposable
94 | get() = androidMandatorySystemGestures
95 |
96 | /**
97 | * The insets representing the area of the software keyboard.
98 | */
99 | actual val WindowInsets.Companion.ime: WindowInsets
100 | @Composable
101 | @NonRestartableComposable
102 | get() = androidIme
103 |
104 | /**
105 | * The insets that include areas where content may be covered by other drawn content.
106 | */
107 | actual val WindowInsets.Companion.safeDrawing: WindowInsets
108 | @Composable
109 | @NonRestartableComposable
110 | get() = androidSafeDrawing
111 |
112 | /**
113 | * The insets that include areas where gestures may be confused with other input.
114 | */
115 | actual val WindowInsets.Companion.safeGestures: WindowInsets
116 | @Composable
117 | @NonRestartableComposable
118 | get() = androidSafeGestures
119 |
120 | /**
121 | * The insets that include all areas that may be drawn over or have gesture confusion.
122 | */
123 | actual val WindowInsets.Companion.safeContent: WindowInsets
124 | @Composable
125 | @NonRestartableComposable
126 | get() = androidSafeContent
127 |
--------------------------------------------------------------------------------
/insetsx/src/androidMain/kotlin/com/moriatsushi/insetsx/WindowInsetsController.android.kt:
--------------------------------------------------------------------------------
1 | package com.moriatsushi.insetsx
2 |
3 | import androidx.compose.runtime.Composable
4 | import androidx.compose.runtime.remember
5 | import com.google.accompanist.systemuicontroller.SystemUiController
6 | import com.google.accompanist.systemuicontroller.rememberSystemUiController
7 |
8 | private class AndroidWindowInsetsController(
9 | private val systemUiController: SystemUiController,
10 | ) : WindowInsetsController {
11 | override fun setStatusBarContentColor(dark: Boolean) {
12 | systemUiController.statusBarDarkContentEnabled = dark
13 | }
14 |
15 | override fun setNavigationBarsContentColor(dark: Boolean) {
16 | systemUiController.navigationBarDarkContentEnabled = dark
17 | }
18 |
19 | override fun setIsStatusBarsVisible(isVisible: Boolean) {
20 | systemUiController.isStatusBarVisible = isVisible
21 | }
22 |
23 | override fun setIsNavigationBarsVisible(isVisible: Boolean) {
24 | systemUiController.isNavigationBarVisible = isVisible
25 | }
26 |
27 | override fun setSystemBarsBehavior(behavior: SystemBarsBehavior) {
28 | systemUiController.systemBarsBehavior = behavior.value
29 | }
30 | }
31 |
32 | /**
33 | * Find and return a [WindowInsetsController].
34 | */
35 | @Composable
36 | actual fun rememberWindowInsetsController(): WindowInsetsController? {
37 | val systemUIController = rememberSystemUiController()
38 | return remember {
39 | AndroidWindowInsetsController(systemUIController)
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/insetsx/src/commonMain/kotlin/com/moriatsushi/insetsx/ExperimentalSoftwareKeyboardApi.kt:
--------------------------------------------------------------------------------
1 | package com.moriatsushi.insetsx
2 |
3 | /**
4 | * Mark declarations as experimental by the software keyboard.
5 | *
6 | * In iOS, software keyboard behavior is not yet complete.
7 | * Specifically, the window moves automatically when the focused element is
8 | * obscured by the keyboard, but we can't disable it.
9 | *
10 | * https://github.com/JetBrains/compose-multiplatform/issues/3128
11 | */
12 | @MustBeDocumented
13 | @Retention(value = AnnotationRetention.BINARY)
14 | @RequiresOptIn(
15 | level = RequiresOptIn.Level.WARNING,
16 | message = "This API is experimental for the software keyboard."
17 | )
18 | annotation class ExperimentalSoftwareKeyboardApi
19 |
--------------------------------------------------------------------------------
/insetsx/src/commonMain/kotlin/com/moriatsushi/insetsx/SystemBarsBehavior.kt:
--------------------------------------------------------------------------------
1 | package com.moriatsushi.insetsx
2 |
3 | /**
4 | * A class that represents options for behavior when system bars are hidden.
5 | */
6 | expect class SystemBarsBehavior {
7 | companion object {
8 | /**
9 | * Default option to to remain interactive when hiding system bars.
10 | *
11 | * * In Android: The system bars can be revealed with system gestures,
12 | * such as swiping from the edge.
13 | * * In iOS: The system bar can be revealed temporarily with system gestures,
14 | * but disappears after a period of time.
15 | */
16 | val Default: SystemBarsBehavior
17 |
18 | /**
19 | * An immersive mode that limits user interaction when system bars are hidden.
20 | * The system bar can be revealed temporarily with system gestures,
21 | * but disappears after a period of time.
22 | */
23 | val Immersive: SystemBarsBehavior
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/insetsx/src/commonMain/kotlin/com/moriatsushi/insetsx/WindowInsets.kt:
--------------------------------------------------------------------------------
1 | package com.moriatsushi.insetsx
2 |
3 | import androidx.compose.foundation.layout.WindowInsets
4 | import androidx.compose.runtime.Composable
5 | import androidx.compose.runtime.Immutable
6 | import androidx.compose.ui.unit.Density
7 | import androidx.compose.ui.unit.LayoutDirection
8 |
9 | /**
10 | * The insets representing navigation bars.
11 | *
12 | * When the navigation bars are hidden, all values are changed to 0.
13 | *
14 | * * In Android: navigation bars
15 | * * In iOS: bottom of safe area (home indicator)
16 | * * In desktop and web: return 0
17 | */
18 | expect val WindowInsets.Companion.navigationBars: WindowInsets
19 | @Composable get
20 |
21 | /**
22 | * The insets representing a caption bar.
23 | *
24 | * * In Android: a caption bar
25 | * * In iOS, desktop and web: return 0
26 | */
27 | expect val WindowInsets.Companion.captionBar: WindowInsets
28 | @Composable get
29 |
30 | /**
31 | * The insets representing status bars.
32 | *
33 | * When the status bars are hidden, all values are changed to 0.
34 | *
35 | * * In Android: status bars
36 | * * In iOS: top of safe area (status bar)
37 | * * In desktop and web: return 0
38 | */
39 | expect val WindowInsets.Companion.statusBars: WindowInsets
40 | @Composable get
41 |
42 | /**
43 | * The insets representing system bars ([navigationBars] + [statusBars]),
44 | * but not including [ime].
45 | *
46 | * * In Android: navigation bars + status bars + caption bars
47 | * * In iOS: top and bottom of safe area (home indicator + status bar)
48 | * * In desktop and web: return 0
49 | */
50 | expect val WindowInsets.Companion.systemBars: WindowInsets
51 | @Composable get
52 |
53 | /**
54 | * The insets representing system gestures that have priority and may consume some or all touch
55 | * input.
56 | *
57 | * * In Android: system gestures
58 | * * In iOS: bottom of safe area (home indicator)
59 | * * In desktop and web: return 0
60 | */
61 | expect val WindowInsets.Companion.systemGestures: WindowInsets
62 | @Composable get
63 |
64 | /**
65 | * The insets representing the tappable element.
66 | *
67 | * * In Android: tappable element
68 | * * In iOS: top of safe area (status bar)
69 | * * In desktop and web: return 0
70 | */
71 | expect val WindowInsets.Companion.tappableElement: WindowInsets
72 | @Composable get
73 |
74 | /**
75 | * The insets representing curved areas in a waterfall display.
76 | *
77 | * * In Android: waterfall
78 | * * In iOS, desktop and web: return 0
79 | */
80 | expect val WindowInsets.Companion.waterfall: WindowInsets
81 | @Composable get
82 |
83 | /**
84 | * The insets that include unsafe areas such as system bars and display cutouts,
85 | * but not including [ime].
86 | *
87 | * * In Android: system bars + display cutouts (not including IME)
88 | * * In iOS: safe area (not including IME)
89 | * * In desktop and web: return 0
90 | */
91 | expect val WindowInsets.Companion.safeArea: WindowInsets
92 | @Composable get
93 |
94 | /**
95 | * The insets representing system gestures that have priority and may consume some or all touch
96 | * input.
97 | *
98 | * * In Android: mandatory system gestures
99 | * * In iOS: bottom of safe area (home indicator)
100 | * * In desktop and web: return 0
101 | */
102 | expect val WindowInsets.Companion.mandatorySystemGestures: WindowInsets
103 | @Composable get
104 |
105 | /**
106 | * The insets representing the area of the software keyboard.
107 | *
108 | * * In Android: IME
109 | * * In iOS: IME
110 | * * In desktop and web: return 0
111 | */
112 | @ExperimentalSoftwareKeyboardApi
113 | expect val WindowInsets.Companion.ime: WindowInsets
114 | @Composable get
115 |
116 | /**
117 | * The insets that include areas where content may be covered by other drawn content.
118 | *
119 | * * In Android: system bars + display cutouts + IME
120 | * * In iOS: safe area + IME
121 | * * In desktop and web: return 0
122 | */
123 | @ExperimentalSoftwareKeyboardApi
124 | expect val WindowInsets.Companion.safeDrawing: WindowInsets
125 | @Composable get
126 |
127 | /**
128 | * The insets that include areas where gestures may be confused with other input.
129 | *
130 | * * In Android: [system gestures][systemGestures] + [mandatory system gestures][mandatorySystemGestures],
131 | * [rounded display areas][waterfall], and [tappable areas][tappableElement].
132 | * * In iOS: top and bottom of safe area (home indicator + status bar)
133 | * * In desktop and web: return 0
134 | */
135 | expect val WindowInsets.Companion.safeGestures: WindowInsets
136 | @Composable get
137 |
138 | /**
139 | * The insets that include all areas that may be drawn over or have gesture confusion.
140 | *
141 | * * In Android: [systemGestures] + [safeGestures].
142 | * * In iOS: safe area + IME
143 | * * In desktop and web: return 0
144 | */
145 | expect val WindowInsets.Companion.safeContent: WindowInsets
146 | @Composable get
147 |
148 | /**
149 | * It always returns 0.
150 | */
151 | internal val WindowInsets.Companion.zero: WindowInsets
152 | get() = ZeroWindowInsets
153 |
154 | @Immutable
155 | private object ZeroWindowInsets : WindowInsets {
156 | override fun getBottom(density: Density): Int {
157 | return 0
158 | }
159 |
160 | override fun getLeft(density: Density, layoutDirection: LayoutDirection): Int {
161 | return 0
162 | }
163 |
164 | override fun getRight(density: Density, layoutDirection: LayoutDirection): Int {
165 | return 0
166 | }
167 |
168 | override fun getTop(density: Density): Int {
169 | return 0
170 | }
171 | }
172 |
--------------------------------------------------------------------------------
/insetsx/src/commonMain/kotlin/com/moriatsushi/insetsx/WindowInsetsController.kt:
--------------------------------------------------------------------------------
1 | package com.moriatsushi.insetsx
2 |
3 | import androidx.compose.runtime.Composable
4 |
5 | /**
6 | * A class which provides utilities for updating the system UI
7 | * such as the status bars and the navigation bars.
8 | */
9 | interface WindowInsetsController {
10 | /**
11 | * The status bars icon + content will change to a dark color if [dark] is true.
12 | * This is appropriate when the background is light.
13 | *
14 | * * In Android: This setting is ignored on API <23.
15 | * * In iOS: Use with `WindowInsetsUIViewController`. If the current `UIViewController`
16 | * is not the main one in the window, this setting is ignored.
17 | */
18 | fun setStatusBarContentColor(dark: Boolean)
19 |
20 | /**
21 | * The navigation bars icons will change to a dark color if [dark] is true.
22 | * This is appropriate when the background is light.
23 | *
24 | * * In Android: This setting is ignored on API <26 or on the gesture
25 | * navigation mode.
26 | * * In iOS: This setting is ignored.
27 | */
28 | fun setNavigationBarsContentColor(dark: Boolean)
29 |
30 | /**
31 | * Change the visibility of the status bars.
32 | */
33 | fun setIsStatusBarsVisible(isVisible: Boolean)
34 |
35 | /**
36 | * Change the visibility of the navigation bars.
37 | */
38 | fun setIsNavigationBarsVisible(isVisible: Boolean)
39 |
40 | /**
41 | * Change an options for behavior when system bars are hidden.
42 | */
43 | fun setSystemBarsBehavior(behavior: SystemBarsBehavior)
44 | }
45 |
46 | /**
47 | * Find and return a [WindowInsetsController].
48 | *
49 | * * In iOS, you must use `WindowInsetsUIViewController`.
50 | * * In desktop and web, this always returns `null`.
51 | */
52 | @Composable
53 | expect fun rememberWindowInsetsController(): WindowInsetsController?
54 |
--------------------------------------------------------------------------------
/insetsx/src/commonMain/kotlin/com/moriatsushi/insetsx/WindowInsetsPadding.kt:
--------------------------------------------------------------------------------
1 | package com.moriatsushi.insetsx
2 |
3 | import androidx.compose.foundation.layout.WindowInsets
4 | import androidx.compose.foundation.layout.windowInsetsPadding
5 | import androidx.compose.runtime.Composable
6 | import androidx.compose.ui.Modifier
7 | import androidx.compose.ui.composed
8 |
9 | /**
10 | * Adds padding to accommodate the [safe drawing][WindowInsets.Companion.safeDrawing] insets.
11 | */
12 | @ExperimentalSoftwareKeyboardApi
13 | fun Modifier.safeDrawingPadding(): Modifier = windowInsetsPadding {
14 | WindowInsets.safeDrawing
15 | }
16 |
17 | /**
18 | * Adds padding to accommodate the [safe area][WindowInsets.Companion.safeArea] insets.
19 | */
20 | fun Modifier.safeAreaPadding(): Modifier = windowInsetsPadding {
21 | WindowInsets.safeArea
22 | }
23 |
24 | /**
25 | * Adds padding to accommodate the [status bars][WindowInsets.Companion.statusBars] insets.
26 | */
27 | fun Modifier.statusBarsPadding(): Modifier = windowInsetsPadding {
28 | WindowInsets.statusBars
29 | }
30 |
31 | /**
32 | * Adds padding to accommodate the [system bars][WindowInsets.Companion.systemBars] insets.
33 | */
34 | fun Modifier.systemBarsPadding(): Modifier = windowInsetsPadding {
35 | WindowInsets.systemBars
36 | }
37 |
38 | /**
39 | * Adds padding to accommodate the [system gestures][WindowInsets.Companion.systemGestures] insets.
40 | */
41 | fun Modifier.systemGesturesPadding(): Modifier = windowInsetsPadding {
42 | WindowInsets.systemGestures
43 | }
44 |
45 | /**
46 | * Adds padding to accommodate the [waterfall][WindowInsets.Companion.waterfall] insets.
47 | */
48 | fun Modifier.waterfallPadding(): Modifier = windowInsetsPadding {
49 | WindowInsets.waterfall
50 | }
51 |
52 | /**
53 | * Adds padding to accommodate the
54 | * [mandatory system gestures][WindowInsets.Companion.mandatorySystemGestures] insets.
55 | */
56 | fun Modifier.mandatorySystemGesturesPadding(): Modifier = windowInsetsPadding {
57 | WindowInsets.mandatorySystemGestures
58 | }
59 |
60 | /**
61 | * Adds padding to accommodate the [ime][WindowInsets.Companion.ime] insets.
62 | */
63 | @ExperimentalSoftwareKeyboardApi
64 | fun Modifier.imePadding(): Modifier = windowInsetsPadding {
65 | WindowInsets.ime
66 | }
67 |
68 | /**
69 | * Adds padding to accommodate the [navigation bars][WindowInsets.Companion.navigationBars] insets.
70 | */
71 | fun Modifier.navigationBarsPadding(): Modifier = windowInsetsPadding {
72 | WindowInsets.navigationBars
73 | }
74 |
75 | /**
76 | * Adds padding to accommodate the [caption bar][WindowInsets.Companion.captionBar] insets.
77 | */
78 | fun Modifier.captionBarPadding(): Modifier = windowInsetsPadding {
79 | WindowInsets.captionBar
80 | }
81 |
82 | /**
83 | * Adds padding to accommodate the [safe gestures][WindowInsets.Companion.safeGestures] insets.
84 | */
85 | fun Modifier.safeGesturesPadding(): Modifier = windowInsetsPadding {
86 | WindowInsets.safeGestures
87 | }
88 |
89 | /**
90 | * Adds padding to accommodate the [safe content][WindowInsets.Companion.safeContent] insets.
91 | */
92 | fun Modifier.safeContentPadding(): Modifier = windowInsetsPadding {
93 | WindowInsets.safeContent
94 | }
95 |
96 | private inline fun Modifier.windowInsetsPadding(
97 | crossinline block: @Composable () -> WindowInsets,
98 | ): Modifier = composed {
99 | Modifier.windowInsetsPadding(block())
100 | }
101 |
--------------------------------------------------------------------------------
/insetsx/src/nativeInterop/cinterop/uikit.def:
--------------------------------------------------------------------------------
1 | package = com.moriatsushi.insetsx.cinterop
2 | language = Objective-C
3 | ---
4 |
5 | #import
6 | #import
7 |
8 | @protocol UIViewControllerWithOverrides
9 | - (bool) prefersHomeIndicatorAutoHidden;
10 | - (UIRectEdge) preferredScreenEdgesDeferringSystemGestures;
11 | @end
12 |
--------------------------------------------------------------------------------
/insetsx/src/noOpMain/kotlin/com/moriatsushi/insetsx/SystemBarsBehavior.noop.kt:
--------------------------------------------------------------------------------
1 | package com.moriatsushi.insetsx
2 |
3 | /**
4 | * No operation.
5 | */
6 | actual class SystemBarsBehavior {
7 | actual companion object {
8 | private val instance = SystemBarsBehavior()
9 |
10 | /**
11 | * No operation.
12 | */
13 | actual val Default: SystemBarsBehavior = instance
14 |
15 | /**
16 | * No operation.
17 | */
18 | actual val Immersive: SystemBarsBehavior = instance
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/insetsx/src/noOpMain/kotlin/com/moriatsushi/insetsx/WindowInsets.noop.kt:
--------------------------------------------------------------------------------
1 | package com.moriatsushi.insetsx
2 |
3 | import androidx.compose.foundation.layout.WindowInsets
4 | import androidx.compose.runtime.Composable
5 | import androidx.compose.runtime.NonRestartableComposable
6 |
7 | /**
8 | * It always returns 0.
9 | */
10 | actual val WindowInsets.Companion.navigationBars: WindowInsets
11 | @Composable
12 | @NonRestartableComposable
13 | get() = zero
14 |
15 | /**
16 | * It always returns 0.
17 | */
18 | actual val WindowInsets.Companion.captionBar: WindowInsets
19 | @Composable
20 | @NonRestartableComposable
21 | get() = zero
22 |
23 | /**
24 | * It always returns 0.
25 | */
26 | actual val WindowInsets.Companion.statusBars: WindowInsets
27 | @Composable
28 | @NonRestartableComposable
29 | get() = zero
30 |
31 | /**
32 | * It always returns 0.
33 | */
34 | actual val WindowInsets.Companion.systemBars: WindowInsets
35 | @Composable
36 | @NonRestartableComposable
37 | get() = zero
38 |
39 | /**
40 | * It always returns 0.
41 | */
42 | actual val WindowInsets.Companion.systemGestures: WindowInsets
43 | @Composable
44 | @NonRestartableComposable
45 | get() = zero
46 |
47 | /**
48 | * It always returns 0.
49 | */
50 | actual val WindowInsets.Companion.tappableElement: WindowInsets
51 | @Composable
52 | @NonRestartableComposable
53 | get() = zero
54 |
55 | /**
56 | * It always returns 0.
57 | */
58 | actual val WindowInsets.Companion.safeArea: WindowInsets
59 | @Composable
60 | @NonRestartableComposable
61 | get() = zero
62 |
63 | /**
64 | * It always returns 0.
65 | */
66 | actual val WindowInsets.Companion.waterfall: WindowInsets
67 | @Composable
68 | @NonRestartableComposable
69 | get() = zero
70 |
71 | /**
72 | * It always returns 0.
73 | */
74 | actual val WindowInsets.Companion.mandatorySystemGestures: WindowInsets
75 | @Composable
76 | @NonRestartableComposable
77 | get() = zero
78 |
79 | /**
80 | * It always returns 0.
81 | */
82 | actual val WindowInsets.Companion.ime: WindowInsets
83 | @Composable
84 | @NonRestartableComposable
85 | get() = zero
86 |
87 | /**
88 | * It always returns 0.
89 | */
90 | actual val WindowInsets.Companion.safeDrawing: WindowInsets
91 | @Composable
92 | @NonRestartableComposable
93 | get() = zero
94 |
95 | /**
96 | * It always returns 0.
97 | */
98 | actual val WindowInsets.Companion.safeGestures: WindowInsets
99 | @Composable
100 | @NonRestartableComposable
101 | get() = zero
102 |
103 | /**
104 | * It always returns 0.
105 | */
106 | actual val WindowInsets.Companion.safeContent: WindowInsets
107 | @Composable
108 | @NonRestartableComposable
109 | get() = zero
110 |
--------------------------------------------------------------------------------
/insetsx/src/noOpMain/kotlin/com/moriatsushi/insetsx/WindowInsetsController.noop.kt:
--------------------------------------------------------------------------------
1 | package com.moriatsushi.insetsx
2 |
3 | import androidx.compose.runtime.Composable
4 |
5 | /**
6 | * It always returns `null`.
7 | */
8 | @Composable
9 | actual fun rememberWindowInsetsController(): WindowInsetsController? {
10 | return value
11 | }
12 |
13 | // Workaround for Kotlin/Wasm
14 | private val value: WindowInsetsController? = null
15 |
--------------------------------------------------------------------------------
/insetsx/src/uikitMain/kotlin/com/moriatsushi/insetsx/NavigationBarsInsets.kt:
--------------------------------------------------------------------------------
1 | package com.moriatsushi.insetsx
2 |
3 | import androidx.compose.foundation.layout.WindowInsets
4 | import androidx.compose.runtime.Stable
5 | import androidx.compose.runtime.getValue
6 | import androidx.compose.runtime.mutableStateOf
7 | import androidx.compose.runtime.setValue
8 | import androidx.compose.ui.unit.Density
9 | import androidx.compose.ui.unit.LayoutDirection
10 | import androidx.compose.ui.unit.dp
11 | import kotlinx.cinterop.useContents
12 | import platform.UIKit.UIView
13 |
14 | @Stable
15 | internal class NavigationBarsInsets(
16 | private val isVisible: () -> Boolean,
17 | ) : WindowInsets {
18 | private var value by mutableStateOf(0.dp)
19 |
20 | override fun getBottom(density: Density): Int {
21 | if (!isVisible()) return 0
22 |
23 | return with(density) {
24 | value.roundToPx()
25 | }
26 | }
27 |
28 | override fun getLeft(density: Density, layoutDirection: LayoutDirection): Int {
29 | return 0
30 | }
31 |
32 | override fun getRight(density: Density, layoutDirection: LayoutDirection): Int {
33 | return 0
34 | }
35 |
36 | override fun getTop(density: Density): Int {
37 | return 0
38 | }
39 |
40 | fun update(view: UIView) {
41 | value = view.window?.safeAreaInsets?.useContents {
42 | bottom.toFloat().dp
43 | } ?: 0.dp
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/insetsx/src/uikitMain/kotlin/com/moriatsushi/insetsx/SafeAreaInsets.kt:
--------------------------------------------------------------------------------
1 | package com.moriatsushi.insetsx
2 |
3 | import androidx.compose.foundation.layout.WindowInsets
4 | import androidx.compose.runtime.Immutable
5 | import androidx.compose.runtime.Stable
6 | import androidx.compose.runtime.getValue
7 | import androidx.compose.runtime.mutableStateOf
8 | import androidx.compose.runtime.setValue
9 | import androidx.compose.ui.unit.Density
10 | import androidx.compose.ui.unit.Dp
11 | import androidx.compose.ui.unit.LayoutDirection
12 | import androidx.compose.ui.unit.dp
13 | import kotlinx.cinterop.useContents
14 | import platform.UIKit.UIView
15 |
16 | @Stable
17 | internal class SafeAreaInsets : WindowInsets {
18 | private var values by mutableStateOf(InsetsValues())
19 |
20 | override fun getBottom(density: Density): Int {
21 | return with(density) {
22 | values.bottom.roundToPx()
23 | }
24 | }
25 |
26 | override fun getLeft(density: Density, layoutDirection: LayoutDirection): Int {
27 | return with(density) {
28 | values.left.roundToPx()
29 | }
30 | }
31 |
32 | override fun getRight(density: Density, layoutDirection: LayoutDirection): Int {
33 | return with(density) {
34 | values.right.roundToPx()
35 | }
36 | }
37 |
38 | override fun getTop(density: Density): Int {
39 | return with(density) {
40 | values.top.roundToPx()
41 | }
42 | }
43 |
44 | fun update(view: UIView) {
45 | values = view.window?.safeAreaInsets?.useContents {
46 | InsetsValues(
47 | bottom = bottom.toFloat().dp,
48 | left = left.toFloat().dp,
49 | right = right.toFloat().dp,
50 | top = top.toFloat().dp
51 | )
52 | } ?: InsetsValues()
53 | }
54 |
55 | @Immutable
56 | private data class InsetsValues(
57 | val bottom: Dp = 0.dp,
58 | val left: Dp = 0.dp,
59 | val right: Dp = 0.dp,
60 | val top: Dp = 0.dp,
61 | )
62 | }
63 |
--------------------------------------------------------------------------------
/insetsx/src/uikitMain/kotlin/com/moriatsushi/insetsx/StatusBarsInsets.kt:
--------------------------------------------------------------------------------
1 | package com.moriatsushi.insetsx
2 |
3 | import androidx.compose.foundation.layout.WindowInsets
4 | import androidx.compose.runtime.Stable
5 | import androidx.compose.runtime.getValue
6 | import androidx.compose.runtime.mutableStateOf
7 | import androidx.compose.runtime.setValue
8 | import androidx.compose.ui.unit.Density
9 | import androidx.compose.ui.unit.LayoutDirection
10 | import androidx.compose.ui.unit.dp
11 | import kotlinx.cinterop.useContents
12 | import platform.UIKit.UIView
13 |
14 | @Stable
15 | internal class StatusBarsInsets(
16 | private val isVisible: () -> Boolean,
17 | ) : WindowInsets {
18 | private var value by mutableStateOf(0.dp)
19 |
20 | override fun getBottom(density: Density): Int {
21 | return 0
22 | }
23 |
24 | override fun getLeft(density: Density, layoutDirection: LayoutDirection): Int {
25 | return 0
26 | }
27 |
28 | override fun getRight(density: Density, layoutDirection: LayoutDirection): Int {
29 | return 0
30 | }
31 |
32 | override fun getTop(density: Density): Int {
33 | if (!isVisible()) return 0
34 |
35 | return with(density) {
36 | value.roundToPx()
37 | }
38 | }
39 |
40 | fun update(view: UIView) {
41 | value = view.window?.safeAreaInsets?.useContents {
42 | top.toFloat().dp
43 | } ?: 0.dp
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/insetsx/src/uikitMain/kotlin/com/moriatsushi/insetsx/SystemBarsBehavior.uikit.kt:
--------------------------------------------------------------------------------
1 | package com.moriatsushi.insetsx
2 |
3 | import platform.UIKit.UIRectEdge
4 |
5 | /**
6 | * A class that represents options for behavior when system bars are hidden.
7 | */
8 | actual class SystemBarsBehavior private constructor(
9 | internal val preferredScreenEdgesDeferringSystemGesturesWhenHidden: UIRectEdge,
10 | ) {
11 | actual companion object {
12 | /**
13 | * Default option to to remain interactive when hiding system bars.
14 | * The system bar can be revealed temporarily with system gestures,
15 | * but disappears after a period of time.
16 | */
17 | actual val Default: SystemBarsBehavior = SystemBarsBehavior(
18 | UIRectEdgeValue.None
19 | )
20 |
21 | /**
22 | * An immersive mode that limits user interaction when system bars are hidden.
23 | * The system bar can be revealed temporarily with system gestures,
24 | * but disappears after a period of time.
25 | */
26 | actual val Immersive: SystemBarsBehavior = SystemBarsBehavior(
27 | UIRectEdgeValue.All
28 | )
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/insetsx/src/uikitMain/kotlin/com/moriatsushi/insetsx/UIKeyboardInsets.kt:
--------------------------------------------------------------------------------
1 | package com.moriatsushi.insetsx
2 |
3 | import androidx.compose.animation.core.Animatable
4 | import androidx.compose.animation.core.Easing
5 | import androidx.compose.animation.core.VectorConverter
6 | import androidx.compose.animation.core.tween
7 | import androidx.compose.foundation.layout.WindowInsets
8 | import androidx.compose.runtime.Stable
9 | import androidx.compose.ui.unit.Density
10 | import androidx.compose.ui.unit.Dp
11 | import androidx.compose.ui.unit.LayoutDirection
12 | import androidx.compose.ui.unit.dp
13 |
14 | @Stable
15 | internal class UIKeyboardInsets : WindowInsets {
16 | private val animatable = Animatable(0.dp, Dp.VectorConverter)
17 |
18 | override fun getBottom(density: Density): Int {
19 | return with(density) {
20 | animatable.value.roundToPx()
21 | }
22 | }
23 |
24 | override fun getLeft(density: Density, layoutDirection: LayoutDirection): Int {
25 | return 0
26 | }
27 |
28 | override fun getRight(density: Density, layoutDirection: LayoutDirection): Int {
29 | return 0
30 | }
31 |
32 | override fun getTop(density: Density): Int {
33 | return 0
34 | }
35 |
36 | suspend fun update(
37 | height: Dp,
38 | durationMillis: Int,
39 | easing: Easing,
40 | ) {
41 | animatable.animateTo(
42 | targetValue = height,
43 | animationSpec = tween(
44 | durationMillis = durationMillis,
45 | easing = easing
46 | )
47 | )
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/insetsx/src/uikitMain/kotlin/com/moriatsushi/insetsx/UIRectEdgeValue.kt:
--------------------------------------------------------------------------------
1 | package com.moriatsushi.insetsx
2 |
3 | import platform.UIKit.UIRectEdge
4 |
5 | internal object UIRectEdgeValue {
6 | val None: UIRectEdge = 0.toULong()
7 | val Top: UIRectEdge = (1 shl 0).toULong()
8 | val Left: UIRectEdge = (1 shl 1).toULong()
9 | val Bottom: UIRectEdge = (1 shl 2).toULong()
10 | val Right: UIRectEdge = (1 shl 3).toULong()
11 | val All: UIRectEdge = Top or Left or Bottom or Right
12 | }
13 |
--------------------------------------------------------------------------------
/insetsx/src/uikitMain/kotlin/com/moriatsushi/insetsx/WindowInsets.uikit.kt:
--------------------------------------------------------------------------------
1 | package com.moriatsushi.insetsx
2 |
3 | import androidx.compose.foundation.layout.WindowInsets
4 | import androidx.compose.runtime.Composable
5 | import androidx.compose.runtime.NonRestartableComposable
6 |
7 | /**
8 | * The insets representing the home indicator.
9 | */
10 | actual val WindowInsets.Companion.navigationBars: WindowInsets
11 | @Composable
12 | @NonRestartableComposable
13 | get() = WindowInsetsHolder.current().navigationBars
14 |
15 | /**
16 | * It always returns 0.
17 | */
18 | actual val WindowInsets.Companion.captionBar: WindowInsets
19 | @Composable
20 | @NonRestartableComposable
21 | get() = zero
22 |
23 | /**
24 | * The insets representing the status bar.
25 | */
26 | actual val WindowInsets.Companion.statusBars: WindowInsets
27 | @Composable
28 | @NonRestartableComposable
29 | get() = WindowInsetsHolder.current().statusBars
30 |
31 | /**
32 | * The insets representing system bars, but not including ime.
33 | */
34 | actual val WindowInsets.Companion.systemBars: WindowInsets
35 | @Composable
36 | @NonRestartableComposable
37 | get() = WindowInsetsHolder.current().systemBars
38 |
39 | /**
40 | * The insets representing system gestures that have priority and may consume some or all touch
41 | * input.
42 | */
43 | actual val WindowInsets.Companion.systemGestures: WindowInsets
44 | @Composable
45 | @NonRestartableComposable
46 | get() = WindowInsetsHolder.current().systemGestures
47 |
48 | /**
49 | * The insets representing the tappable element.
50 | */
51 | actual val WindowInsets.Companion.tappableElement: WindowInsets
52 | @Composable
53 | @NonRestartableComposable
54 | get() = WindowInsetsHolder.current().tappableElement
55 |
56 | /**
57 | * The insets representing the safe area.
58 | */
59 | actual val WindowInsets.Companion.safeArea: WindowInsets
60 | @Composable
61 | @NonRestartableComposable
62 | get() = WindowInsetsHolder.current().safeArea
63 |
64 | /**
65 | * It always returns 0.
66 | */
67 | actual val WindowInsets.Companion.waterfall: WindowInsets
68 | @Composable
69 | @NonRestartableComposable
70 | get() = zero
71 |
72 | /**
73 | * The insets representing system gestures that have priority and may consume some or all touch
74 | * input.
75 | */
76 | actual val WindowInsets.Companion.mandatorySystemGestures: WindowInsets
77 | @Composable
78 | @NonRestartableComposable
79 | get() = WindowInsetsHolder.current().systemGestures
80 |
81 | /**
82 | * The insets representing the area of the software keyboard.
83 | */
84 | @ExperimentalSoftwareKeyboardApi
85 | actual val WindowInsets.Companion.ime: WindowInsets
86 | @Composable
87 | @NonRestartableComposable
88 | get() = WindowInsetsHolder.current().ime
89 |
90 | /**
91 | * The insets that include areas where content may be covered by other drawn content.
92 | */
93 | @ExperimentalSoftwareKeyboardApi
94 | actual val WindowInsets.Companion.safeDrawing: WindowInsets
95 | @Composable
96 | @NonRestartableComposable
97 | get() = WindowInsetsHolder.current().safeDrawing
98 |
99 | /**
100 | * The insets that include areas where gestures may be confused with other input.
101 | */
102 | @ExperimentalSoftwareKeyboardApi
103 | actual val WindowInsets.Companion.safeGestures: WindowInsets
104 | @Composable
105 | @NonRestartableComposable
106 | get() = WindowInsetsHolder.current().safeGestures
107 |
108 | /**
109 | * The insets that include all areas that may be drawn over or have gesture confusion.
110 | */
111 | @ExperimentalSoftwareKeyboardApi
112 | actual val WindowInsets.Companion.safeContent: WindowInsets
113 | @Composable
114 | @NonRestartableComposable
115 | get() = WindowInsetsHolder.current().safeDrawing
116 |
--------------------------------------------------------------------------------
/insetsx/src/uikitMain/kotlin/com/moriatsushi/insetsx/WindowInsetsController.ios.kt:
--------------------------------------------------------------------------------
1 | package com.moriatsushi.insetsx
2 |
3 | import androidx.compose.runtime.Composable
4 | import androidx.compose.runtime.Stable
5 | import androidx.compose.runtime.staticCompositionLocalOf
6 |
7 | @Stable
8 | internal interface UIKitWindowInsetsController : WindowInsetsController {
9 | val isStatusBarVisible: Boolean
10 | val isNavigationBarVisible: Boolean
11 | }
12 |
13 | internal val LocalWindowInsetsController = staticCompositionLocalOf {
14 | null
15 | }
16 |
17 | /**
18 | * Find and return a [WindowInsetsController].
19 | */
20 | @Composable
21 | actual fun rememberWindowInsetsController(): WindowInsetsController? {
22 | return LocalWindowInsetsController.current
23 | }
24 |
--------------------------------------------------------------------------------
/insetsx/src/uikitMain/kotlin/com/moriatsushi/insetsx/WindowInsetsHolder.uikit.kt:
--------------------------------------------------------------------------------
1 | package com.moriatsushi.insetsx
2 |
3 | import androidx.compose.animation.core.FastOutLinearInEasing
4 | import androidx.compose.animation.core.LinearOutSlowInEasing
5 | import androidx.compose.foundation.layout.WindowInsetsSides
6 | import androidx.compose.foundation.layout.only
7 | import androidx.compose.foundation.layout.union
8 | import androidx.compose.runtime.Composable
9 | import androidx.compose.runtime.DisposableEffect
10 | import androidx.compose.runtime.rememberCoroutineScope
11 | import androidx.compose.ui.interop.LocalUIViewController
12 | import androidx.compose.ui.unit.Dp
13 | import androidx.compose.ui.unit.dp
14 | import kotlin.coroutines.CoroutineContext
15 | import kotlinx.cinterop.ObjCAction
16 | import kotlinx.cinterop.useContents
17 | import kotlinx.coroutines.CoroutineScope
18 | import kotlinx.coroutines.Job
19 | import kotlinx.coroutines.launch
20 | import platform.CoreGraphics.CGRectMake
21 | import platform.Foundation.NSNotification
22 | import platform.Foundation.NSNotificationCenter
23 | import platform.Foundation.NSSelectorFromString
24 | import platform.Foundation.NSTimeInterval
25 | import platform.Foundation.NSValue
26 | import platform.UIKit.CGRectValue
27 | import platform.UIKit.UIKeyboardWillHideNotification
28 | import platform.UIKit.UIKeyboardWillShowNotification
29 | import platform.UIKit.UIView
30 | import platform.UIKit.UIViewController
31 | import platform.darwin.NSObject
32 |
33 | internal class WindowInsetsHolder(
34 | private val windowInsetsController: UIKitWindowInsetsController?,
35 | private val coroutineContext: CoroutineContext,
36 | ) {
37 | val safeArea = SafeAreaInsets()
38 | val navigationBars = NavigationBarsInsets(
39 | isVisible = {
40 | windowInsetsController?.isNavigationBarVisible ?: true
41 | }
42 | )
43 | val statusBars = StatusBarsInsets(
44 | isVisible = {
45 | windowInsetsController?.isStatusBarVisible ?: true
46 | }
47 | )
48 | val systemBars = navigationBars.union(statusBars)
49 | val systemGestures = safeArea.only(WindowInsetsSides.Bottom)
50 | val tappableElement = safeArea.only(WindowInsetsSides.Top)
51 | val ime = UIKeyboardInsets()
52 | val safeDrawing = safeArea.union(ime)
53 | val safeGestures = safeArea.only(WindowInsetsSides.Vertical)
54 |
55 | private val coroutineJob = Job()
56 | private val coroutineScope = CoroutineScope(coroutineContext + Job())
57 |
58 | /**
59 | * The number of accesses to [WindowInsetsHolder].
60 | * When this increases to 1, the view is attached and the listeners are added.
61 | * When it reaches zero, the view is detached and listeners are removed.
62 | */
63 | private var accessCount = 0
64 |
65 | private val keyboardVisibilityListener = object : NSObject() {
66 | @Suppress("unused")
67 | @ObjCAction
68 | fun keyboardWillShow(arg: NSNotification) {
69 | val height = arg.keyboardHeight
70 | val durationMillis = arg.keyboardAnimationDurationMills
71 |
72 | coroutineScope.launch {
73 | ime.update(height, durationMillis, LinearOutSlowInEasing)
74 | }
75 | }
76 |
77 | @Suppress("unused")
78 | @ObjCAction
79 | fun keyboardWillHide(arg: NSNotification) {
80 | val durationMillis = arg.keyboardAnimationDurationMills
81 |
82 | coroutineScope.launch {
83 | ime.update(0.dp, durationMillis, FastOutLinearInEasing)
84 | }
85 | }
86 | }
87 |
88 | private val insetsListenerView = object : UIView(CGRectMake(.0, .0, .0, .0)) {
89 | @Suppress("unused")
90 | @ObjCAction
91 | override fun safeAreaInsetsDidChange() {
92 | updateSafeArea()
93 | }
94 | }
95 |
96 | fun incrementAccessors(viewController: UIViewController) {
97 | accessCount++
98 | if (accessCount == 1) {
99 | viewController.view.insertSubview(insetsListenerView, 0)
100 | updateSafeArea()
101 | NSNotificationCenter.defaultCenter.addObserver(
102 | observer = keyboardVisibilityListener,
103 | selector = NSSelectorFromString("keyboardWillShow:"),
104 | name = UIKeyboardWillShowNotification,
105 | `object` = null
106 | )
107 | NSNotificationCenter.defaultCenter.addObserver(
108 | observer = keyboardVisibilityListener,
109 | selector = NSSelectorFromString("keyboardWillHide:"),
110 | name = UIKeyboardWillHideNotification,
111 | `object` = null
112 | )
113 | }
114 | }
115 |
116 | fun decrementAccessors(): Boolean {
117 | accessCount--
118 | if (accessCount == 0) {
119 | insetsListenerView.removeFromSuperview()
120 | coroutineJob.cancel()
121 | NSNotificationCenter.defaultCenter.removeObserver(
122 | observer = keyboardVisibilityListener,
123 | name = UIKeyboardWillShowNotification,
124 | `object` = null
125 | )
126 | NSNotificationCenter.defaultCenter.removeObserver(
127 | observer = keyboardVisibilityListener,
128 | name = UIKeyboardWillHideNotification,
129 | `object` = null
130 | )
131 | }
132 | return accessCount == 0
133 | }
134 |
135 | private fun updateSafeArea() {
136 | safeArea.update(insetsListenerView)
137 | navigationBars.update(insetsListenerView)
138 | statusBars.update(insetsListenerView)
139 | }
140 |
141 | private val NSNotification.keyboardHeight: Dp
142 | get() {
143 | val keyboardInfo = userInfo!!["UIKeyboardFrameEndUserInfoKey"] as NSValue
144 | return keyboardInfo.CGRectValue().useContents { size.height }.toFloat().dp
145 | }
146 |
147 | private val NSNotification.keyboardAnimationDurationMills: Int
148 | get() {
149 | val duration = userInfo!!["UIKeyboardAnimationDurationUserInfoKey"] as NSTimeInterval
150 | return (duration * 1000).toInt()
151 | }
152 |
153 | companion object {
154 | private val viewControllerMap = mutableMapOf()
155 |
156 | @Composable
157 | fun current(): WindowInsetsHolder {
158 | val viewController = LocalUIViewController.current
159 | val windowInsetsController = LocalWindowInsetsController.current
160 | val coroutineContext = rememberCoroutineScope().coroutineContext
161 | val holder = getOrCreateFor(
162 | viewController,
163 | windowInsetsController,
164 | coroutineContext
165 | )
166 |
167 | DisposableEffect(holder) {
168 | holder.incrementAccessors(viewController)
169 | onDispose {
170 | if (holder.decrementAccessors()) {
171 | viewControllerMap.remove(viewController)
172 | }
173 | }
174 | }
175 |
176 | return holder
177 | }
178 |
179 | private fun getOrCreateFor(
180 | viewController: UIViewController,
181 | windowInsetsController: UIKitWindowInsetsController?,
182 | coroutineContext: CoroutineContext,
183 | ): WindowInsetsHolder {
184 | return viewControllerMap.getOrPut(viewController) {
185 | WindowInsetsHolder(
186 | windowInsetsController,
187 | coroutineContext
188 | )
189 | }
190 | }
191 | }
192 | }
193 |
--------------------------------------------------------------------------------
/insetsx/src/uikitMain/kotlin/com/moriatsushi/insetsx/WindowInsetsUIViewController.kt:
--------------------------------------------------------------------------------
1 | package com.moriatsushi.insetsx
2 |
3 | import androidx.compose.runtime.Composable
4 | import androidx.compose.runtime.CompositionLocalProvider
5 | import androidx.compose.runtime.getValue
6 | import androidx.compose.runtime.mutableStateOf
7 | import androidx.compose.runtime.setValue
8 | import androidx.compose.ui.window.ComposeUIViewController
9 | import com.moriatsushi.insetsx.cinterop.UIViewControllerWithOverridesProtocol
10 | import platform.Foundation.NSCoder
11 | import platform.UIKit.UIRectEdge
12 | import platform.UIKit.UIStatusBarStyle
13 | import platform.UIKit.UIView
14 | import platform.UIKit.UIViewAutoresizingFlexibleHeight
15 | import platform.UIKit.UIViewAutoresizingFlexibleWidth
16 | import platform.UIKit.UIViewController
17 | import platform.UIKit.addChildViewController
18 | import platform.UIKit.didMoveToParentViewController
19 | import platform.UIKit.setNeedsUpdateOfHomeIndicatorAutoHidden
20 | import platform.UIKit.setNeedsUpdateOfScreenEdgesDeferringSystemGestures
21 |
22 | /**
23 | * Create a [UIViewController] with window insets support
24 | */
25 | @Suppress("FunctionName")
26 | fun WindowInsetsUIViewController(content: @Composable () -> Unit): UIViewController =
27 | WindowInsetsUIViewController().apply {
28 | setContent(content)
29 | }
30 |
31 | internal class WindowInsetsUIViewController :
32 | UIViewController,
33 | UIViewControllerWithOverridesProtocol {
34 | @OverrideInit
35 | constructor() : super(nibName = null, bundle = null)
36 |
37 | @OverrideInit
38 | constructor(coder: NSCoder) : super(coder)
39 |
40 | private lateinit var content: @Composable () -> Unit
41 |
42 | private var _preferredStatusBarStyle: UIStatusBarStyle = 0L
43 | override fun preferredStatusBarStyle(): UIStatusBarStyle =
44 | _preferredStatusBarStyle
45 |
46 | private var _prefersStatusBarHidden: Boolean by mutableStateOf(false)
47 | override fun prefersStatusBarHidden(): Boolean =
48 | _prefersStatusBarHidden
49 |
50 | private var _prefersHomeIndicatorAutoHidden: Boolean by mutableStateOf(false)
51 | override fun prefersHomeIndicatorAutoHidden(): Boolean =
52 | _prefersHomeIndicatorAutoHidden
53 |
54 | private var _preferredScreenEdgesDeferringSystemGestures: UIRectEdge = UIRectEdgeValue.None
55 | override fun preferredScreenEdgesDeferringSystemGestures(): UIRectEdge =
56 | _preferredScreenEdgesDeferringSystemGestures
57 |
58 | private val windowInsetsController = object : UIKitWindowInsetsController {
59 | private var preferredScreenEdgesDeferringSystemGesturesWhenHidden: UIRectEdge =
60 | UIRectEdgeValue.None
61 |
62 | override val isStatusBarVisible: Boolean
63 | get() = !_prefersStatusBarHidden
64 |
65 | override val isNavigationBarVisible: Boolean
66 | get() = !_prefersHomeIndicatorAutoHidden
67 |
68 | override fun setStatusBarContentColor(dark: Boolean) {
69 | _preferredStatusBarStyle = if (dark) 3L else 1L
70 | setNeedsStatusBarAppearanceUpdate()
71 | }
72 |
73 | override fun setNavigationBarsContentColor(dark: Boolean) {
74 | // no op
75 | }
76 |
77 | override fun setIsStatusBarsVisible(isVisible: Boolean) {
78 | _prefersStatusBarHidden = !isVisible
79 | setNeedsStatusBarAppearanceUpdate()
80 | applyScreenEdgesDeferringSystemGestures()
81 | }
82 |
83 | override fun setIsNavigationBarsVisible(isVisible: Boolean) {
84 | _prefersHomeIndicatorAutoHidden = !isVisible
85 | setNeedsUpdateOfHomeIndicatorAutoHidden()
86 | applyScreenEdgesDeferringSystemGestures()
87 | }
88 |
89 | override fun setSystemBarsBehavior(behavior: SystemBarsBehavior) {
90 | preferredScreenEdgesDeferringSystemGesturesWhenHidden =
91 | behavior.preferredScreenEdgesDeferringSystemGesturesWhenHidden
92 | applyScreenEdgesDeferringSystemGestures()
93 | }
94 |
95 | private fun applyScreenEdgesDeferringSystemGestures() {
96 | _preferredScreenEdgesDeferringSystemGestures =
97 | if (_prefersHomeIndicatorAutoHidden || _prefersStatusBarHidden) {
98 | preferredScreenEdgesDeferringSystemGesturesWhenHidden
99 | } else {
100 | UIRectEdgeValue.None
101 | }
102 | setNeedsUpdateOfScreenEdgesDeferringSystemGestures()
103 | }
104 | }
105 |
106 | override fun loadView() {
107 | super.loadView()
108 |
109 | val rootView = UIView()
110 | val composeViewController = ComposeUIViewController {
111 | CompositionLocalProvider(
112 | LocalWindowInsetsController provides windowInsetsController,
113 | content = content
114 | )
115 | }
116 | addChildViewController(composeViewController)
117 | rootView.addSubview(composeViewController.view)
118 | rootView.setAutoresizesSubviews(true)
119 | composeViewController.view.setAutoresizingMask(
120 | UIViewAutoresizingFlexibleWidth or UIViewAutoresizingFlexibleHeight
121 | )
122 | view = rootView
123 | composeViewController.didMoveToParentViewController(this)
124 | }
125 |
126 | fun setContent(
127 | content: @Composable () -> Unit,
128 | ) {
129 | this.content = content
130 | }
131 | }
132 |
--------------------------------------------------------------------------------
/renovate.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json",
3 | "extends": [
4 | "config:base"
5 | ]
6 | }
7 |
--------------------------------------------------------------------------------
/settings.gradle.kts:
--------------------------------------------------------------------------------
1 | pluginManagement {
2 | repositories {
3 | gradlePluginPortal()
4 | mavenCentral()
5 | maven("https://maven.pkg.jetbrains.space/public/p/compose/dev")
6 | maven("https://maven.pkg.jetbrains.space/kotlin/p/wasm/experimental")
7 | google()
8 | }
9 | }
10 |
11 | dependencyResolutionManagement {
12 | repositories {
13 | mavenCentral()
14 | maven("https://maven.pkg.jetbrains.space/public/p/compose/dev")
15 | maven("https://maven.pkg.jetbrains.space/kotlin/p/wasm/experimental")
16 | google()
17 | }
18 |
19 | versionCatalogs {
20 | create("libs") {
21 | version("kotlin", "1.8.20")
22 | version("kotlinx-atomicfu", "0.21.0")
23 | version("agp", "8.1.0")
24 | version("androidx-appcompat", "1.6.1")
25 | version("androidx-activity", "1.7.2")
26 | version("androidx-core", "1.10.1")
27 | version("jetbrains-compose", "1.4.0-dev-wasm06")
28 | version("accompanist", "0.30.1")
29 | version("spotless", "6.22.0")
30 | version("ktlint", "0.48.1")
31 | version("publish", "0.25.3")
32 |
33 | library("kotlinx-atomicfu", "org.jetbrains.kotlinx", "atomicfu")
34 | .versionRef("kotlinx-atomicfu")
35 | library("androidx-appcompat", "androidx.appcompat", "appcompat")
36 | .versionRef("androidx-appcompat")
37 | library("androidx-core", "androidx.core", "core-ktx")
38 | .versionRef("androidx-core")
39 | library("androidx-activity-compose", "androidx.activity", "activity-compose")
40 | .versionRef("androidx-activity")
41 | library(
42 | "accompanist-systemuicontroller",
43 | "com.google.accompanist",
44 | "accompanist-systemuicontroller"
45 | )
46 | .versionRef("accompanist")
47 |
48 | plugin("android-application", "com.android.application")
49 | .versionRef("agp")
50 | plugin("android-library", "com.android.library")
51 | .versionRef("agp")
52 | plugin("jetbrains-compose", "org.jetbrains.compose")
53 | .versionRef("jetbrains-compose")
54 | plugin("spotless", "com.diffplug.spotless")
55 | .versionRef("spotless")
56 | plugin("publish", "com.vanniktech.maven.publish")
57 | .versionRef("publish")
58 | }
59 | }
60 | }
61 |
62 | rootProject.name = "insetsx"
63 | include(":insetsx")
64 | include(":example")
65 |
--------------------------------------------------------------------------------