Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions AKPlugin.swift
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,10 @@ class AKPlugin: NSObject, Plugin {
NSApplication.shared.windows.first!.styleMask.contains(.fullScreen)
}

@objc var isApplicationActive: Bool {
NSApplication.shared.isActive
}

var cmdPressed: Bool = false
var cursorHideLevel = 0
func hideCursor() {
Expand Down Expand Up @@ -286,11 +290,13 @@ class AKPlugin: NSObject, Plugin {
func setMenuBarVisible(_ visible: Bool) {
NSMenu.setMenuBarVisible(visible)
}
}

private extension AKPlugin {
/// Convenience instance property that exposes the cached static preference.
private var hideTitleBarSetting: Bool { Self.akAppSettingsData?.hideTitleBar ?? false }
private var floatingWindowSetting: Bool { Self.akAppSettingsData?.floatingWindow ?? false }
private var aspectRatioSetting: NSSize? {
var hideTitleBarSetting: Bool { Self.akAppSettingsData?.hideTitleBar ?? false }
var floatingWindowSetting: Bool { Self.akAppSettingsData?.floatingWindow ?? false }
var aspectRatioSetting: NSSize? {
guard Self.akAppSettingsData?.resolution == 6 else {
return nil
}
Expand All @@ -302,7 +308,7 @@ class AKPlugin: NSObject, Plugin {
return NSSize(width: width, height: height)
}

fileprivate static var akAppSettingsData: AKAppSettingsData? = {
static var akAppSettingsData: AKAppSettingsData? = {
let bundleIdentifier = Bundle.main.bundleIdentifier ?? ""
let settingsURL = URL(fileURLWithPath: "/Users/\(NSUserName())/Library/Containers/io.playcover.PlayCover")
.appendingPathComponent("App Settings")
Expand Down
4 changes: 0 additions & 4 deletions PlayTools.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,6 @@
B127172528817C040025112B /* DiscordIPC.swift in Sources */ = {isa = PBXBuildFile; fileRef = B127172428817C040025112B /* DiscordIPC.swift */; };
B1271729288284BE0025112B /* DiscordActivity.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1271728288284BE0025112B /* DiscordActivity.swift */; };
B1E8CF8A28BBE2AB004340D3 /* Keymapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1E8CF8928BBE2AB004340D3 /* Keymapping.swift */; };
B444BB0D2F49C1D100ADCC5A /* ControllerFocus.m in Sources */ = {isa = PBXBuildFile; fileRef = B444BB0B2F49C1D100ADCC5A /* ControllerFocus.m */; };
B46C02C72C634AB5007637AB /* BatteryLevel.m in Sources */ = {isa = PBXBuildFile; fileRef = B46C02C62C634AB5007637AB /* BatteryLevel.m */; };
B66E65002C936EA100E48FD0 /* PlayedAppleDBConstants.swift in Sources */ = {isa = PBXBuildFile; fileRef = B66E64FF2C936E9800E48FD0 /* PlayedAppleDBConstants.swift */; };
B6D774FF2ACFC3D900C0D9D8 /* SwordRPC in Frameworks */ = {isa = PBXBuildFile; productRef = B6D774FE2ACFC3D900C0D9D8 /* SwordRPC */; };
Expand Down Expand Up @@ -184,7 +183,6 @@
B127172428817C040025112B /* DiscordIPC.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DiscordIPC.swift; sourceTree = "<group>"; };
B1271728288284BE0025112B /* DiscordActivity.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DiscordActivity.swift; sourceTree = "<group>"; };
B1E8CF8928BBE2AB004340D3 /* Keymapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Keymapping.swift; sourceTree = "<group>"; };
B444BB0B2F49C1D100ADCC5A /* ControllerFocus.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = ControllerFocus.m; sourceTree = "<group>"; };
B46C02C62C634AB5007637AB /* BatteryLevel.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = BatteryLevel.m; sourceTree = "<group>"; };
B46C02C82C634C60007637AB /* BatteryLevel.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = BatteryLevel.h; sourceTree = "<group>"; };
B66E64FF2C936E9800E48FD0 /* PlayedAppleDBConstants.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayedAppleDBConstants.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -488,7 +486,6 @@
65F0487A0C752EE4930AF0AB /* UserPluginLoader.swift */,
B46C02C62C634AB5007637AB /* BatteryLevel.m */,
B46C02C82C634C60007637AB /* BatteryLevel.h */,
B444BB0B2F49C1D100ADCC5A /* ControllerFocus.m */,
D04B12C92EF6F3DD008FEC14 /* MediaVolume.m */,
D04B12CC2EF6F3F9008FEC14 /* MediaVolume.h */,
);
Expand Down Expand Up @@ -720,7 +717,6 @@
files = (
954389CA2B392D7800B063BB /* DraggableButton.swift in Sources */,
9562D16D2AB505D4002C329D /* ControllerEventAdapter.swift in Sources */,
B444BB0D2F49C1D100ADCC5A /* ControllerFocus.m in Sources */,
AA71975A287A480D00623C15 /* Toucher.swift in Sources */,
AA7197A1287A481500623C15 /* CircleMenuLoader.swift in Sources */,
6E76639B28D0FAE700DE4AF9 /* Plugin.swift in Sources */,
Expand Down
29 changes: 21 additions & 8 deletions PlayTools/Controls/Backend/Action/PlayAction.swift
Original file line number Diff line number Diff line change
Expand Up @@ -355,19 +355,31 @@ class CameraAction: Action {
class SwipeAction: Action {
var location: CGPoint = CGPoint.zero
private var id: Int?
let timer = DispatchSource.makeTimerSource(flags: [], queue: PlayInput.touchQueue)
private var timer: DispatchSourceTimer?
private let actionName: String, keyName: String
init(actionName: String, keyName: String) {
self.actionName = actionName
self.keyName = keyName
timer.schedule(deadline: DispatchTime.now() + 1, repeating: 0.1, leeway: DispatchTimeInterval.milliseconds(50))
timer.setEventHandler(qos: .userInteractive, handler: self.checkEnded)
timer.activate()
timer.suspend()
}

deinit {
timer.cancel()
timer?.cancel()
}

private func startTimer() {
guard timer == nil, id != nil else { return }
let source = DispatchSource.makeTimerSource(queue: PlayInput.touchQueue)
source.schedule(deadline: .now() + .milliseconds(100), repeating: .milliseconds(100),
leeway: .milliseconds(50))
source.setEventHandler(qos: .userInteractive) { [weak self] in self?.checkEnded() }
timer = source
source.activate()
}

private func stopTimer() {
// Every source is activated exactly once. Never release a suspended source.
timer?.cancel()
timer = nil
}

func delay(_ delay: Double, closure: @escaping () -> Void) {
Expand Down Expand Up @@ -430,7 +442,7 @@ class SwipeAction: Action {
counter = 0
Toucher.touchcam(point: location, phase: UITouch.Phase.began, tid: &id,
actionName: actionName, keyName: keyName)
timer.resume()
startTimer()
} else {
if shouldEdgeReset {
doLiftOff()
Expand Down Expand Up @@ -474,13 +486,14 @@ class SwipeAction: Action {

public func doLiftOff() {
if id == nil {
stopTimer()
return
}
Toucher.touchcam(point: self.location, phase: UITouch.Phase.ended, tid: &id,
actionName: actionName, keyName: keyName)
// Touch might somehow fail to end
if id == nil {
timer.suspend()
stopTimer()
delay(0.02) {
self.cooldown = false
}
Expand Down
13 changes: 9 additions & 4 deletions PlayTools/Controls/Frontend/ControlMode.swift
Original file line number Diff line number Diff line change
Expand Up @@ -80,12 +80,17 @@ public class ControlMode: Equatable {
private func setupGameController() {
let centre = NotificationCenter.default
let main = OperationQueue.main
centre.addObserver(forName: NSNotification.Name.GCControllerDidConnect, object: nil, queue: main) { _ in
GCController.shouldMonitorBackgroundEvents = true
GCController.current?.extendedGamepad?.valueChangedHandler = { profile, element in
self.controllerAdapter.handleValueChanged(profile, element)
let configure: (GCController) -> Void = { [weak self] controller in
controller.extendedGamepad?.valueChangedHandler = { [weak self] profile, element in
guard PlayInput.shared.acceptsControllerInput else { return }
self?.controllerAdapter.handleValueChanged(profile, element)
}
}
centre.addObserver(forName: NSNotification.Name.GCControllerDidConnect,
object: nil, queue: main) { notification in
if let controller = notification.object as? GCController { configure(controller) }
}
GCController.controllers().forEach(configure)
}

private func setupKeyboard() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,16 +79,22 @@ class ThumbstickCursorControl {
}

public func update(velocityX: CGFloat, velocityY: CGFloat) {
self.thumbstickVelocity.dx = velocityX
self.thumbstickVelocity.dy = velocityY
if !thumbstickPolling {
PlayInput.touchQueue.async(execute: self.thumbstickPoll)
self.thumbstickPolling = true
// Controller callbacks and the polling worker may run on different queues.
// Keep velocity and worker ownership on one queue, including focus changes.
PlayInput.touchQueue.async {
self.thumbstickVelocity.dx = velocityX
self.thumbstickVelocity.dy = velocityY
if !self.thumbstickPolling {
self.thumbstickPolling = true
self.thumbstickPoll()
}
}
}

private func thumbstickPoll() {
if !ThumbstickCursorControl.isVectorSignificant(self.thumbstickVelocity) {
if !PlayInput.shared.acceptsControllerInput
|| !ThumbstickCursorControl.isVectorSignificant(self.thumbstickVelocity) {
self.thumbstickVelocity = .zero
self.thumbstickPolling = false
return
}
Expand Down
80 changes: 75 additions & 5 deletions PlayTools/Controls/PlayInput.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import Foundation
import UIKit
import GameController
import Atomics

// This class is a coordinator (and module entrance), coordinating other concrete classes

Expand All @@ -11,25 +12,38 @@ class PlayInput {
qos: .userInteractive,
autoreleaseFrequency: .workItem)

private var displayLink: CADisplayLink?
private let appActive = ManagedAtomic(false)
private var isAppActive: Bool {
get { appActive.load(ordering: .acquiring) }
set { appActive.store(newValue, ordering: .releasing) }
}
private var initialized = false

var acceptsControllerInput: Bool { isAppActive }

@objc func drainMainDispatchQueue() {
_dispatch_main_queue_callback_4CF(nil)
}

func initialize() {
// drain the dispatch queue every frame for responding to GCController events
let displaylink = CADisplayLink(target: self, selector: #selector(drainMainDispatchQueue))
displaylink.add(to: .main, forMode: .common)

guard !initialized else { return }
initialized = true
if PlaySettings.shared.disableBuiltinMouse {
simulateGCMouseDisconnect()
}

if !PlaySettings.shared.keymapping {
guard PlaySettings.shared.keymapping else {
return
}

isAppActive = AKInterface.shared?.isApplicationActive
?? (UIApplication.shared.applicationState == .active)

let centre = NotificationCenter.default
let main = OperationQueue.main
registerInputLifecycleObservers(centre: centre, main: main)
updateDisplayLinkState()

centre.addObserver(forName: NSNotification.Name(rawValue: "NSWindowDidBecomeKeyNotification"), object: nil,
queue: main) { _ in
Expand All @@ -47,6 +61,32 @@ class PlayInput {
mode.initialize()
}

private func setAppActive(_ active: Bool) {
// AppKit focus notifications are authoritative on Catalyst, where UIKit
// can remain foreground-active even when another Mac app owns focus.
let wasActive = isAppActive
isAppActive = active && (AKInterface.shared?.isApplicationActive ?? true)
if wasActive && !isAppActive {
ActionDispatcher.invalidateActions()
}
updateDisplayLinkState()
}

private func updateDisplayLinkState() {
let hasController = !GCController.controllers().isEmpty
if !hasController || !isAppActive {
displayLink?.invalidate()
displayLink = nil
return
}
if displayLink == nil {
// Drain the main dispatch queue per frame while a GCController is active.
let link = CADisplayLink(target: self, selector: #selector(drainMainDispatchQueue))
link.add(to: .main, forMode: .common)
displayLink = link
}
}

private func simulateGCMouseDisconnect() {
NotificationCenter.default.addObserver(
forName: .GCMouseDidConnect,
Expand All @@ -73,4 +113,34 @@ class PlayInput {
}
}
}

private func registerInputLifecycleObservers(centre: NotificationCenter, main: OperationQueue) {
// Only run the CADisplayLink queue-drainer while keymapping is active,
// at least one GCController is connected, and the app is foreground-active.
for name in [
NSNotification.Name.GCControllerDidConnect,
NSNotification.Name.GCControllerDidDisconnect
] {
centre.addObserver(forName: name, object: nil, queue: main) { [weak self] _ in
self?.updateDisplayLinkState()
}
}
for name in [UIApplication.didBecomeActiveNotification,
NSNotification.Name("NSApplicationDidBecomeActiveNotification")] {
centre.addObserver(forName: name, object: nil, queue: main) { [weak self] _ in
self?.setAppActive(true)
}
}
for name in [
UIApplication.willResignActiveNotification,
UIApplication.didEnterBackgroundNotification,
NSNotification.Name("NSApplicationDidResignActiveNotification"),
NSNotification.Name("NSApplicationDidHideNotification"),
NSNotification.Name("NSApplicationWillTerminateNotification")
] {
centre.addObserver(forName: name, object: nil, queue: main) { [weak self] _ in
self?.setAppActive(false)
}
}
}
}
Loading