├── .gitignore
├── .swiftpm
└── xcode
│ └── package.xcworkspace
│ ├── contents.xcworkspacedata
│ └── xcshareddata
│ ├── IDETemplateMacros.plist
│ └── IDEWorkspaceChecks.plist
├── LICENSE
├── Package.swift
├── README.md
├── Sources
└── VisionKeyboardKit
│ ├── KeyboardButtonStyle.swift
│ ├── KeyboardClickSound.swift
│ ├── KeyboardEvent.swift
│ ├── KeyboardEventPS2.swift
│ ├── KeyboardIdentifier.swift
│ ├── KeyboardKeyView.swift
│ ├── KeyboardLayoutANSI.swift
│ ├── KeyboardLayoutTenkeys.swift
│ ├── KeyboardLayoutType.swift
│ ├── KeyboardSettingsViewModifier.swift
│ ├── KeyboardState.swift
│ ├── KeyboardView.swift
│ └── KeyboardWindowGroup.swift
├── Tests
└── VisionKeyboardKitTests
│ └── VisionKeyboardKitTests.swift
└── screenshot.png
/.gitignore:
--------------------------------------------------------------------------------
1 | # Xcode
2 | #
3 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
4 |
5 | ## User settings
6 | xcuserdata/
7 |
8 | ## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9)
9 | *.xcscmblueprint
10 | *.xccheckout
11 |
12 | ## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4)
13 | build/
14 | DerivedData/
15 | *.moved-aside
16 | *.pbxuser
17 | !default.pbxuser
18 | *.mode1v3
19 | !default.mode1v3
20 | *.mode2v3
21 | !default.mode2v3
22 | *.perspectivev3
23 | !default.perspectivev3
24 |
25 | ## Obj-C/Swift specific
26 | *.hmap
27 |
28 | ## App packaging
29 | *.ipa
30 | *.dSYM.zip
31 | *.dSYM
32 |
33 | ## Playgrounds
34 | timeline.xctimeline
35 | playground.xcworkspace
36 |
37 | # Swift Package Manager
38 | #
39 | # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies.
40 | # Packages/
41 | # Package.pins
42 | # Package.resolved
43 | # *.xcodeproj
44 | #
45 | # Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata
46 | # hence it is not needed unless you have added a package configuration file to your project
47 | # .swiftpm
48 |
49 | .build/
50 |
51 | # CocoaPods
52 | #
53 | # We recommend against adding the Pods directory to your .gitignore. However
54 | # you should judge for yourself, the pros and cons are mentioned at:
55 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
56 | #
57 | # Pods/
58 | #
59 | # Add this line if you want to avoid checking in source code from the Xcode workspace
60 | # *.xcworkspace
61 |
62 | # Carthage
63 | #
64 | # Add this line if you want to avoid checking in source code from Carthage dependencies.
65 | # Carthage/Checkouts
66 |
67 | Carthage/Build/
68 |
69 | # Accio dependency management
70 | Dependencies/
71 | .accio/
72 |
73 | # fastlane
74 | #
75 | # It is recommended to not store the screenshots in the git repo.
76 | # Instead, use fastlane to re-generate the screenshots whenever they are needed.
77 | # For more information about the recommended setup visit:
78 | # https://docs.fastlane.tools/best-practices/source-control/#source-control
79 |
80 | fastlane/report.xml
81 | fastlane/Preview.html
82 | fastlane/screenshots/**/*.png
83 | fastlane/test_output
84 |
85 | # Code Injection
86 | #
87 | # After new code Injection tools there's a generated folder /iOSInjectionProject
88 | # https://github.com/johnno1962/injectionforxcode
89 |
90 | iOSInjectionProject/
91 |
92 | .DS_Store
93 |
94 |
--------------------------------------------------------------------------------
/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.swiftpm/xcode/package.xcworkspace/xcshareddata/IDETemplateMacros.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | FILEHEADER
6 |
7 | // Copyright © ___YEAR___ osy. All rights reserved.
8 | //
9 | // Licensed under the Apache License, Version 2.0 (the "License");
10 | // you may not use this file except in compliance with the License.
11 | // You may obtain a copy of the License at
12 | //
13 | // http://www.apache.org/licenses/LICENSE-2.0
14 | //
15 | // Unless required by applicable law or agreed to in writing, software
16 | // distributed under the License is distributed on an "AS IS" BASIS,
17 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 | // See the License for the specific language governing permissions and
19 | // limitations under the License.
20 | //
21 |
22 |
23 |
--------------------------------------------------------------------------------
/.swiftpm/xcode/package.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | IDEDidComputeMac32BitWarning
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/Package.swift:
--------------------------------------------------------------------------------
1 | // swift-tools-version: 5.9
2 |
3 | import PackageDescription
4 |
5 | let package = Package(
6 | name: "VisionKeyboardKit",
7 | platforms: [
8 | .visionOS(.v1)
9 | ],
10 | products: [
11 | .library(
12 | name: "VisionKeyboardKit",
13 | targets: ["VisionKeyboardKit"]),
14 | ],
15 | targets: [
16 | .target(
17 | name: "VisionKeyboardKit"),
18 | .testTarget(
19 | name: "VisionKeyboardKitTests",
20 | dependencies: ["VisionKeyboardKit"]),
21 | ]
22 | )
23 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | Vision Keyboard Kit
2 | ===================
3 | 
4 |
5 | ## Features
6 | * Full sized (104-keys) or 60% (no arrow/num keys) mode
7 | * Support for multiple keyboard layouts
8 | * PS/2 Set 1 scan code generation
9 | * Multiple instances with independent event handlers
10 | * Key down and key up events
11 |
12 | ## Usage
13 | Declare `KeyboardWindowGroup` in your `Scene`:
14 | ```swift
15 | import SwiftUI
16 | import VisionKeyboardKit
17 |
18 | @main
19 | struct YourApp: App {
20 | var body: some Scene {
21 | WindowGroup {
22 | ContentView()
23 | }
24 | KeyboardWindowGroup()
25 | }
26 | }
27 | ```
28 |
29 | Open/close the keyboard window using `OpenWindowAction`/`DismissWindowAction` and receive events through `KeyboardEvent.publisher(for:)`:
30 | ```swift
31 | import SwiftUI
32 | import VisionKeyboardKit
33 |
34 | struct ContentView: View {
35 | @Environment(\.openWindow) private var openWindow
36 | @Environment(\.dismissWindow) private var dismissWindow
37 | @State private var isKeyboardShown: Bool = false
38 |
39 | var body: some View {
40 | Button {
41 | if !isKeyboardShown {
42 | openWindow(keyboardFor: .global)
43 | } else {
44 | dismissWindow(keyboardFor: .global)
45 | }
46 | } label: {
47 | Text("Toggle Keyboard")
48 | }.onReceive(KeyboardEvent.publisher(for: .global)) { event in
49 | if case .keyboardDidAppear = event {
50 | isKeyboardShown = true
51 | } else if case .keyboardDidDisappear = event {
52 | isKeyboardShown = false
53 | } else {
54 | print("Got event: \(event)")
55 | }
56 | }
57 | }
58 | }
59 | ```
60 |
61 | If you need more than one keyboard with independent event publishers, just pass in any `Hashable` which serves as an identifier for the keyboard.
62 |
63 | The returned `Publisher` can be used in the Combine framework for chained processing (such as debounce).
64 |
--------------------------------------------------------------------------------
/Sources/VisionKeyboardKit/KeyboardButtonStyle.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright © 2023 osy. All rights reserved.
3 | //
4 | // Licensed under the Apache License, Version 2.0 (the "License");
5 | // you may not use this file except in compliance with the License.
6 | // You may obtain a copy of the License at
7 | //
8 | // http://www.apache.org/licenses/LICENSE-2.0
9 | //
10 | // Unless required by applicable law or agreed to in writing, software
11 | // distributed under the License is distributed on an "AS IS" BASIS,
12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | // See the License for the specific language governing permissions and
14 | // limitations under the License.
15 | //
16 |
17 | import SwiftUI
18 | import RealityKit
19 |
20 | private let kDebounceTime: Duration = .milliseconds(25)
21 |
22 | struct KeyboardButtonStyle: PrimitiveButtonStyle {
23 | let isDark: Bool
24 | let isToggled: Bool
25 | let fontSize: CGFloat
26 | let width: CGFloat
27 | let height: CGFloat
28 | let clickSound: KeyboardClickSound.File
29 | let onTouchDown: () -> Void
30 | let onTouchUp: () -> Void
31 |
32 | @State private var isPressed: Bool = false
33 | @State private var debounceTask: Task?
34 | @Environment(KeyboardState.self) private var state
35 |
36 | private func spatialGesture(configuration: Configuration) -> some Gesture {
37 | SpatialEventGesture()
38 | .onChanged { events in
39 | for event in events {
40 | switch event.kind {
41 | case .indirectPinch, .pointer, .touch:
42 | if !isPressed {
43 | isPressed = true
44 | onTouchDown()
45 | }
46 | // touch events require debouncing
47 | if event.kind == .touch {
48 | debounceTask?.cancel()
49 | debounceTask = nil
50 | }
51 | default: break
52 | }
53 | }
54 | }
55 | .onEnded { events in
56 | for event in events {
57 | switch event.kind {
58 | case .indirectPinch, .pointer:
59 | isPressed = false
60 | onTouchUp()
61 | configuration.trigger()
62 | case .touch:
63 | // ignore any .ended phase followed immediately by an .active phase
64 | let trigger = configuration.trigger
65 | debounceTask = Task { @MainActor in
66 | try? await Task.sleep(for: kDebounceTime)
67 | if !Task.isCancelled {
68 | isPressed = false
69 | onTouchUp()
70 | trigger()
71 | }
72 | }
73 | default: break
74 | }
75 | }
76 | }
77 | }
78 |
79 | func makeBody(configuration: Configuration) -> some View {
80 | ZStack {
81 | if isPressed {
82 | // we only create the RealityView when the button is activated
83 | // this is where the click sound will orginate from
84 | RealityView { content in
85 | content.add(state.clicker.entity)
86 | Task {
87 | state.clicker.play(sound: clickSound)
88 | }
89 | }
90 | }
91 | if isToggled {
92 | Capsule()
93 | .frame(width: width, height: height)
94 | .foregroundStyle(.white)
95 | .background(in: Capsule())
96 | .backgroundStyle(.shadow(.drop(radius: 2, x: 2, y: 2)))
97 | } else if isDark {
98 | Capsule()
99 | .frame(width: width, height: height)
100 | .foregroundStyle(.thickMaterial.shadow(.inner(radius: 1, x: -1, y: -1)))
101 | .background(in: Capsule())
102 | .backgroundStyle(.shadow(.drop(radius: 2, x: 2, y: 2)))
103 | } else {
104 | Capsule()
105 | .frame(width: width, height: height)
106 | .foregroundStyle(.shadow(.inner(radius: 1, x: -1, y: -1)).tertiary)
107 | .background(in: Capsule())
108 | .backgroundStyle(.shadow(.drop(radius: 2, x: 2, y: 2)))
109 | }
110 | if isPressed {
111 | Capsule()
112 | .frame(width: width+8, height: height+8)
113 | .foregroundStyle(.white.opacity(0.25))
114 | }
115 | configuration.label
116 | .font(.system(size: fontSize))
117 | .foregroundStyle(isToggled ? .black : .white)
118 | }
119 | .frame(width: width + 4, height: height + 4)
120 | .hoverEffect()
121 | .frame(depth: isPressed ? 0 : 12)
122 | .gesture(spatialGesture(configuration: configuration))
123 | }
124 | }
125 |
126 | extension PrimitiveButtonStyle where Self == KeyboardButtonStyle {
127 | static func keyboardButton(isDark: Bool = false, isToggled: Bool = false, fontSize: CGFloat = 24, width: CGFloat = 50, height: CGFloat = 50, clickSound: KeyboardClickSound.File = .normal, onTouchDown: @escaping () -> Void = {}, onTouchUp: @escaping () -> Void = {}) -> KeyboardButtonStyle {
128 | KeyboardButtonStyle(isDark: isDark, isToggled: isToggled, fontSize: fontSize, width: width, height: height, clickSound: clickSound, onTouchDown: onTouchDown, onTouchUp: onTouchUp)
129 | }
130 | }
131 |
--------------------------------------------------------------------------------
/Sources/VisionKeyboardKit/KeyboardClickSound.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright © 2023 osy. All rights reserved.
3 | //
4 | // Licensed under the Apache License, Version 2.0 (the "License");
5 | // you may not use this file except in compliance with the License.
6 | // You may obtain a copy of the License at
7 | //
8 | // http://www.apache.org/licenses/LICENSE-2.0
9 | //
10 | // Unless required by applicable law or agreed to in writing, software
11 | // distributed under the License is distributed on an "AS IS" BASIS,
12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | // See the License for the specific language governing permissions and
14 | // limitations under the License.
15 | //
16 |
17 | import AVFAudio
18 | import RealityKit
19 |
20 | /// Plays the system keyboard click sound
21 | class KeyboardClickSound {
22 | enum File {
23 | case normal
24 | case delete
25 | case modifier
26 | }
27 |
28 | /// The RK entity where the sound will originate
29 | let entity = Entity()
30 |
31 | private var pressNormalPlayer: AudioPlaybackController?
32 | private var pressDeletePlayer: AudioPlaybackController?
33 | private var pressModifierPlayer: AudioPlaybackController?
34 |
35 | private func loadAudioResource(for url: URL) -> AudioFileResource? {
36 | let configuration = AudioFileResource.Configuration(calibration: .absolute(dBSPL: 58.0))
37 | return try? .load(contentsOf: url, configuration: configuration)
38 | }
39 |
40 | #if targetEnvironment(simulator)
41 | /// This is a very hacky way to get the keyboard sound files in a simulator
42 | private lazy var uiSoundsUrl: URL = {
43 | let fm = FileManager.default
44 | let library = fm.urls(for: .libraryDirectory, in: .localDomainMask)[0]
45 | let simulators = library.appending(components: "Developer", "CoreSimulator", "Volumes")
46 | let visionos = try? fm.contentsOfDirectory(at: simulators, includingPropertiesForKeys: nil).first(where: { $0.lastPathComponent.starts(with: "xrOS") || $0.lastPathComponent.starts(with: "visionOS") })
47 | guard let visionos = visionos else {
48 | return Bundle.main.resourceURL!
49 | }
50 | let runtimes = visionos.appending(components: "Library", "Developer", "CoreSimulator", "Profiles", "Runtimes")
51 | let runtime = try? fm.contentsOfDirectory(at: runtimes, includingPropertiesForKeys: nil).first
52 | guard let runtime = runtime else {
53 | return Bundle.main.resourceURL!
54 | }
55 | return runtime.appending(components: "Contents", "Resources", "RuntimeRoot", "System", "Library", "Audio", "UISounds")
56 | }()
57 | #else
58 | private lazy var uiSoundsUrl: URL = {
59 | let fm = FileManager.default
60 | let library = fm.urls(for: .libraryDirectory, in: .systemDomainMask)[0]
61 | return library.appending(components: "Audio", "UISounds")
62 | }()
63 | #endif
64 |
65 | private lazy var isEnabled: Bool = {
66 | var valid: DarwinBoolean = false
67 | CFPreferencesAppSynchronize("com.apple.preferences.sounds" as CFString)
68 | let enabled = CFPreferencesGetAppBooleanValue("keyboard-audio" as CFString, "com.apple.preferences.sounds" as CFString, &valid)
69 | return !valid.boolValue || enabled
70 | }()
71 |
72 | init() {
73 | // if we disabled system sounds then do not create the players
74 | guard isEnabled else {
75 | return
76 | }
77 | let pressNormalUrl = uiSoundsUrl.appending(component: "key_press_click.caf")
78 | let pressDeleteUrl = uiSoundsUrl.appending(component: "key_press_delete.caf")
79 | let pressModifierUrl = uiSoundsUrl.appending(component: "key_press_modifier.caf")
80 | if let resource = loadAudioResource(for: pressNormalUrl) {
81 | pressNormalPlayer = entity.prepareAudio(resource)
82 | }
83 | if let resource = loadAudioResource(for: pressDeleteUrl) {
84 | pressDeletePlayer = entity.prepareAudio(resource)
85 | }
86 | if let resource = loadAudioResource(for: pressModifierUrl) {
87 | pressModifierPlayer = entity.prepareAudio(resource)
88 | }
89 | }
90 |
91 | private func withAmbientSession(_ callback: () -> Void) {
92 | let session = AVAudioSession.sharedInstance()
93 | let oldCategory = session.category
94 | let oldMode = session.mode
95 | let oldPolicy = session.routeSharingPolicy
96 | let oldOptions = session.categoryOptions
97 | do {
98 | try session.setCategory(.ambient, mode: .default, policy: .default, options: .mixWithOthers)
99 | callback()
100 | try session.setCategory(oldCategory, mode: oldMode, policy: oldPolicy, options: oldOptions)
101 | } catch {
102 | print(error)
103 | }
104 | }
105 |
106 | @MainActor
107 | private func play(_ player: AudioPlaybackController?) {
108 | guard let player = player else {
109 | return
110 | }
111 | withAmbientSession {
112 | if player.isPlaying {
113 | player.seek(to: .zero)
114 | }
115 | player.play()
116 | }
117 | }
118 |
119 | /// Play the click sound
120 | /// - Parameter sound: Which sound to play
121 | @MainActor
122 | func play(sound: File = .normal) {
123 | switch sound {
124 | case .normal: play(pressNormalPlayer)
125 | case .delete: play(pressDeletePlayer)
126 | case .modifier: play(pressModifierPlayer)
127 | }
128 | }
129 | }
130 |
--------------------------------------------------------------------------------
/Sources/VisionKeyboardKit/KeyboardEvent.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright © 2023 osy. All rights reserved.
3 | //
4 | // Licensed under the Apache License, Version 2.0 (the "License")
5 | // you may not use this file except in compliance with the License.
6 | // You may obtain a copy of the License at
7 | //
8 | // http://www.apache.org/licenses/LICENSE-2.0
9 | //
10 | // Unless required by applicable law or agreed to in writing, software
11 | // distributed under the License is distributed on an "AS IS" BASIS,
12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | // See the License for the specific language governing permissions and
14 | // limitations under the License.
15 | //
16 |
17 | import Combine
18 | import os
19 |
20 | /// Events posted by the keyboard
21 | public enum KeyboardEvent {
22 | /// Sent from the keyboard view's `onAppear()`
23 | case keyboardDidAppear
24 | /// Sent from the keyboard view's `onDisappear()`
25 | case keyboardDidDisappear
26 | /// Sent when a keyboard key is held down
27 | case keyDown(KeyboardKeyCode, modifier: KeyboardModifier)
28 | /// Sent when a keyboard key is released
29 | case keyUp(KeyboardKeyCode, modifier: KeyboardModifier)
30 |
31 | static func subject(for id: KeyboardIdentifier) -> KeyboardEventSubject {
32 | KeyboardEventSubject.for(id)
33 | }
34 |
35 | /// Returns a publisher that emits events from the keyboard.
36 | /// - Parameter id: A `KeyboardIdentifier` that uniquely identifies this keyboard instance.
37 | /// - Returns: A `Publisher` that emits events from the keyboard.
38 | public static func publisher(for id: KeyboardIdentifier) -> AnyPublisher {
39 | KeyboardEventSubject.for(id).eraseToAnyPublisher()
40 | }
41 |
42 | /// Returns a publisher that emits events from the keyboard.
43 | /// - Parameter id: Unique identifier for the keyboard to handle events from.
44 | /// - Returns: A `Publisher` that emits events from the keyboard.
45 | public static func publisher(for id: H) -> AnyPublisher {
46 | publisher(for: KeyboardIdentifier(for: id))
47 | }
48 | }
49 |
50 | /// Modifier key state
51 | public struct KeyboardModifier: OptionSet {
52 | public let rawValue: Int
53 |
54 | public static var none = KeyboardModifier(rawValue: 0)
55 | public static var leftShift = KeyboardModifier(rawValue: 1 << 0)
56 | public static var rightShift = KeyboardModifier(rawValue: 1 << 1)
57 | public static var leftControl = KeyboardModifier(rawValue: 1 << 2)
58 | public static var rightControl = KeyboardModifier(rawValue: 1 << 3)
59 | public static var leftOption = KeyboardModifier(rawValue: 1 << 4)
60 | public static var rightOption = KeyboardModifier(rawValue: 1 << 5)
61 | public static var leftCommand = KeyboardModifier(rawValue: 1 << 6)
62 | public static var rightCommand = KeyboardModifier(rawValue: 1 << 7)
63 | public static var capsLock = KeyboardModifier(rawValue: 1 << 8)
64 | public static var scrollLock = KeyboardModifier(rawValue: 1 << 9)
65 | public static var numLock = KeyboardModifier(rawValue: 1 << 10)
66 |
67 | public init(rawValue: Int) {
68 | self.rawValue = rawValue
69 | }
70 |
71 | mutating func removeNontoggle() {
72 | subtract([.leftShift, .rightShift, .leftControl, .rightControl, .leftCommand, .rightCommand, .leftOption, .rightOption])
73 | }
74 | }
75 |
76 | public enum KeyboardKeyCode {
77 | case key0
78 | case key1
79 | case key2
80 | case key3
81 | case key4
82 | case key5
83 | case key6
84 | case key7
85 | case key8
86 | case key9
87 | case keyA
88 | case keyACPIPower
89 | case keyACPISleep
90 | case keyACPIWake
91 | case keyApplication
92 | case keyB
93 | case keyBackslash
94 | case keyBackspace
95 | case keyC
96 | case keyCapsLock
97 | case keyComma
98 | case keyCommand
99 | case keyControl
100 | case keyD
101 | case keyDelete
102 | case keyDownArrow
103 | case keyE
104 | case keyEnd
105 | case keyEqual
106 | case keyEscape
107 | case keyF
108 | case keyF1
109 | case keyF10
110 | case keyF11
111 | case keyF12
112 | case keyF2
113 | case keyF3
114 | case keyF4
115 | case keyF5
116 | case keyF6
117 | case keyF7
118 | case keyF8
119 | case keyF9
120 | case keyG
121 | case keyGrave
122 | case keyH
123 | case keyHome
124 | case keyI
125 | case keyInsert
126 | case keyInternational107
127 | case keyInternational42
128 | case keyInternational45
129 | case keyJ
130 | case keyJISEisu
131 | case keyJISKana
132 | case keyJISUnderscore
133 | case keyJISYen
134 | case keyK
135 | case keyKeypad0
136 | case keyKeypad1
137 | case keyKeypad2
138 | case keyKeypad3
139 | case keyKeypad4
140 | case keyKeypad5
141 | case keyKeypad6
142 | case keyKeypad7
143 | case keyKeypad8
144 | case keyKeypad9
145 | case keyKeypadDecimal
146 | case keyKeypadDivide
147 | case keyKeypadEnter
148 | case keyKeypadMinus
149 | case keyKeypadMultiply
150 | case keyKeypadPlus
151 | case keyL
152 | case keyLeftArrow
153 | case keyLeftBracket
154 | case keyM
155 | case keyMinus
156 | case keyN
157 | case keyNumLock
158 | case keyO
159 | case keyOption
160 | case keyP
161 | case keyPageDown
162 | case keyPageUp
163 | case keyPause
164 | case keyPeriod
165 | case keyPrintScreen
166 | case keyQ
167 | case keyQuote
168 | case keyR
169 | case keyReturn
170 | case keyRightArrow
171 | case keyRightBracket
172 | case keyRightCommand
173 | case keyRightControl
174 | case keyRightOption
175 | case keyRightShift
176 | case keyS
177 | case keyScrollLock
178 | case keySemicolon
179 | case keyShift
180 | case keySlash
181 | case keySpace
182 | case keyT
183 | case keyTab
184 | case keyU
185 | case keyUpArrow
186 | case keyV
187 | case keyW
188 | case keyX
189 | case keyY
190 | case keyZ
191 |
192 | var isModifier: Bool {
193 | switch self {
194 | case .keyShift, .keyRightShift, .keyControl, .keyRightControl, .keyCommand, .keyRightCommand, .keyOption, .keyRightOption:
195 | return true
196 | case .keyCapsLock, .keyNumLock, .keyScrollLock:
197 | return true
198 | default:
199 | return false
200 | }
201 | }
202 | }
203 |
204 | /// Box for holding a weak reference
205 | private struct Weak {
206 | weak var ref: S?
207 | }
208 |
209 | /// We maintain a map of `KeyboardIdentifier` to `KeyboardEventSubject` in order to maintain that
210 | /// each identifier gets a unique instance of the `Subject`. When they keyboard view posts events to the `Subject`,
211 | /// any `Publisher` who is listening to it shall receive the event.
212 | ///
213 | /// Once all references are dropped, that means that the keyboard window is closed and all listeners have released
214 | /// their reference and so it is safe to clean up the map entry (which should be holding a box with a nil reference).
215 | /// We make sure all this is done in a thread safe manner by the use of `subjectsLock`.
216 | final class KeyboardEventSubject: Subject {
217 | typealias Output = KeyboardEvent
218 | typealias Failure = Never
219 |
220 | private static var subjectsLock = OSAllocatedUnfairLock()
221 | private static var allSubjects: [KeyboardIdentifier: Weak] = [:]
222 | private let id: KeyboardIdentifier
223 | private let underlyingSubject = PassthroughSubject