diff --git a/.github/workflows/FUNDING.yml b/.github/workflows/FUNDING.yml new file mode 100644 index 0000000..ad13e96 --- /dev/null +++ b/.github/workflows/FUNDING.yml @@ -0,0 +1,13 @@ +# These are supported funding model platforms + +github: [0xLeif] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..bbfe0c3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +.DS_Store +/.build +/Packages +xcuserdata/ +DerivedData/ +.swiftpm/ +.netrc +Package.resolved \ No newline at end of file diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..9e45c96 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Zach Eriksen + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Package.swift b/Package.swift new file mode 100644 index 0000000..c66242a --- /dev/null +++ b/Package.swift @@ -0,0 +1,32 @@ +// swift-tools-version: 5.7 + +import PackageDescription + +let package = Package( + name: "ApplicationKit", + platforms: [ + .iOS(.v15), + .watchOS(.v8), + .macOS(.v11), + .tvOS(.v15) + ], + products: [ + .library( + name: "ApplicationKit", + targets: ["ApplicationKit"] + ) + ], + dependencies: [ + .package(url: "https://github.com/0xLeif/AppState", from: "1.0.0") + ], + targets: [ + .target( + name: "ApplicationKit", + dependencies: ["AppState"] + ), + .testTarget( + name: "ApplicationKitTests", + dependencies: ["ApplicationKit"] + ) + ] +) diff --git a/README.md b/README.md new file mode 100644 index 0000000..bbf34c0 --- /dev/null +++ b/README.md @@ -0,0 +1,75 @@ +# ApplicationKit + +ApplicationKit is a Swift-based library that provides a rich set of tools for managing and working with application state. Building upon [AppState](https://github.com/0xLeif/AppState), it provides an additional layer of functionality to manage lifecycle notifications and state changes in applications. + +## Features + +- A Lifecycle Management API that provides callback functions for significant events in the application lifecycle. +- A simplified interface to run closures only once from anywhere within the codebase. +- A streamlined approach to handling and observing different lifecycle notifications. +- Debugging support with file location attributes for effective lifecycle event tracking. +- More to come... + +## Getting Started + +### Requirements + +- Swift 5.7 or later + +- iOS 15.0 or later +- watchOS 8.0 or later +- macOS 11.0 or later +- tvOS 15.0 or later + +### Installation + +You can integrate ApplicationKit into your project using Swift Package Manager. + +Once you have your Swift package set up, adding ApplicationKit as a dependency is as easy as adding it to the dependencies value of your Package.swift file. + +```swift +dependencies: [ + .package(url: "https://github.com/0xLeif/ApplicationKit.git", from: "0.1.0") +] +``` + +## Usage + +To handle various application states, override the necessary methods in your custom application class: + +```swift +private class MyApplication: LifecyleApplication { + + override var lifecycleNotifications: [LifecyleNotification] { + super.lifecycleNotifications + [ + // Your additional lifecycle notifications + ] + } + + /// Gets called when application state becomes active + override func didBecomeActiveNotification(notification: Notification) { + // Custom code implementation + } +} +``` + +In your App initialization, promote your custom application class: + +```swift +Application.promote(to: MyApplication.self) +``` + +Use ApplicationKit's `.runOnce` feature to run a specific closure code once within the lifecycle of the application: +```swift +Application.runOnce { performExpensiveTaskHere() } +``` + +## Contributing + +Pull requests are very welcome. For major changes, please open an issue first to discuss what you would like to change. + +Please make sure to update tests as appropriate. + +## License + +ApplicationKit is distributed under the MIT license. For more information, refer to the LICENSE file. diff --git a/Sources/ApplicationKit/AppState+export.swift b/Sources/ApplicationKit/AppState+export.swift new file mode 100644 index 0000000..c9b4ff1 --- /dev/null +++ b/Sources/ApplicationKit/AppState+export.swift @@ -0,0 +1 @@ +@_exported import AppState diff --git a/Sources/ApplicationKit/LifecyleApplication/LifecyleApplication+LifecyleNotification.swift b/Sources/ApplicationKit/LifecyleApplication/LifecyleApplication+LifecyleNotification.swift new file mode 100644 index 0000000..2bb5d58 --- /dev/null +++ b/Sources/ApplicationKit/LifecyleApplication/LifecyleApplication+LifecyleNotification.swift @@ -0,0 +1,30 @@ +import Foundation + +extension LifecyleApplication { + /** + Represents a Lifecycle Notification event in the scope of `LifecyleApplication`. + + This structure holds two properties: + - Selector: An action to be performed when the notification is observed. + - Notification.Name: The name of the notification event to be observed. + */ + public struct LifecyleNotification { + /// The action to be performed when the notification is observed. + public let selector: Selector + + /// The name of the notification event to be observed. + public let name: Notification.Name + + /** + Creates a `LifecyleNotification` with specified selector and notification name. + + - Parameters: + - selector: The selector to be called when the notification is posted. + - name: The unique name of the notification to observe. + */ + public init(selector: Selector, name: Notification.Name) { + self.selector = selector + self.name = name + } + } +} diff --git a/Sources/ApplicationKit/LifecyleApplication/LifecyleApplication.swift b/Sources/ApplicationKit/LifecyleApplication/LifecyleApplication.swift new file mode 100644 index 0000000..098ce47 --- /dev/null +++ b/Sources/ApplicationKit/LifecyleApplication/LifecyleApplication.swift @@ -0,0 +1,347 @@ +import AppState +import Foundation +import SwiftUI + +#if os(iOS) +/// This is an open class that observes various lifecycle and system events. +open class LifecyleApplication: Application { + /** + An array of the lifecycle events this class is observing. This includes: + - backgroundRefreshStatusDidChangeNotification + - didBecomeActiveNotification + - didEnterBackgroundNotification + - didFinishLaunchingNotification + - didReceiveMemoryWarningNotification + - significantTimeChangeNotification + - userDidTakeScreenshotNotification + - willEnterForegroundNotification + - willResignActiveNotification + - willTerminateNotification + */ + open var lifecycleNotifications: [LifecyleNotification] { + [ + LifecyleNotification( + selector: #selector(backgroundRefreshStatusDidChangeNotification(notification:)), + name: UIApplication.backgroundRefreshStatusDidChangeNotification + ), + LifecyleNotification( + selector: #selector(didBecomeActiveNotification(notification:)), + name: UIApplication.didBecomeActiveNotification + ), + LifecyleNotification( + selector: #selector(didEnterBackgroundNotification(notification:)), + name: UIApplication.didEnterBackgroundNotification + ), + LifecyleNotification( + selector: #selector(didFinishLaunchingNotification(notification:)), + name: UIApplication.didFinishLaunchingNotification + ), + LifecyleNotification( + selector: #selector(didReceiveMemoryWarningNotification(notification:)), + name: UIApplication.didReceiveMemoryWarningNotification + ), + LifecyleNotification( + selector: #selector(significantTimeChangeNotification(notification:)), + name: UIApplication.significantTimeChangeNotification + ), + LifecyleNotification( + selector: #selector(userDidTakeScreenshotNotification(notification:)), + name: UIApplication.userDidTakeScreenshotNotification + ), + LifecyleNotification( + selector: #selector(willEnterForegroundNotification(notification:)), + name: UIApplication.willEnterForegroundNotification + ), + LifecyleNotification( + selector: #selector(willResignActiveNotification(notification:)), + name: UIApplication.willResignActiveNotification + ), + LifecyleNotification( + selector: #selector(willTerminateNotification(notification:)), + name: UIApplication.willTerminateNotification + ) + ] + } + + /// Initializes the class and registers to observe the lifecycle notifications. + public required init() { + super.init() + + for notification in lifecycleNotifications { + NotificationCenter.default.addObserver( + self, + selector: notification.selector, + name: notification.name, + object: nil + ) + } + } + + /// Called when system's background refresh status changes + @objc open func backgroundRefreshStatusDidChangeNotification(notification: Notification) { } + /// Called when application becomes active + @objc open func didBecomeActiveNotification(notification: Notification) { } + /// Called when application enters background + @objc open func didEnterBackgroundNotification(notification: Notification) { } + /// Called when application finishes launching + @objc open func didFinishLaunchingNotification(notification: Notification) { } + /// Called when application receives a memory warning + @objc open func didReceiveMemoryWarningNotification(notification: Notification) { } + /// Called when system time changes significantly + @objc open func significantTimeChangeNotification(notification: Notification) { } + /// Called when user takes a screenshot + @objc open func userDidTakeScreenshotNotification(notification: Notification) { } + /// Called when application is about to enter foreground + @objc open func willEnterForegroundNotification(notification: Notification) { } + /// Called when application is about to become inactive + @objc open func willResignActiveNotification(notification: Notification) { } + /// Called when application is about to terminate + @objc open func willTerminateNotification(notification: Notification) { } +} +#elseif os(macOS) +/// This is an open class that observes various lifecycle and system events. +open class LifecyleApplication: Application { + /** + An array of the lifecycle events and some system events this class is observing. This includes: + - didBecomeActiveNotification + - didHideNotification + - didFinishLaunchingNotification + - didResignActiveNotification + - didUnhideNotification + - didUpdateNotification + - willBecomeActiveNotification + - willHideNotification + - willFinishLaunchingNotification + - willResignActiveNotification + - willUnhideNotification + - willUpdateNotification + - willTerminateNotification + - didChangeScreenParametersNotification + */ + open var lifecycleNotifications: [LifecyleNotification] { + [ + LifecyleNotification( + selector: #selector(didBecomeActiveNotification(notification:)), + name: NSApplication.didBecomeActiveNotification + ), + LifecyleNotification( + selector: #selector(didHideNotification(notification:)), + name: NSApplication.didHideNotification + ), + LifecyleNotification( + selector: #selector(didFinishLaunchingNotification(notification:)), + name: NSApplication.didFinishLaunchingNotification + ), + LifecyleNotification( + selector: #selector(didResignActiveNotification(notification:)), + name: NSApplication.didResignActiveNotification + ), + LifecyleNotification( + selector: #selector(didUnhideNotification(notification:)), + name: NSApplication.didUnhideNotification + ), + LifecyleNotification( + selector: #selector(didUpdateNotification(notification:)), + name: NSApplication.didUpdateNotification + ), + LifecyleNotification( + selector: #selector(willBecomeActiveNotification(notification:)), + name: NSApplication.willBecomeActiveNotification + ), + LifecyleNotification( + selector: #selector(willHideNotification(notification:)), + name: NSApplication.willHideNotification + ), + LifecyleNotification( + selector: #selector(willFinishLaunchingNotification(notification:)), + name: NSApplication.willFinishLaunchingNotification + ), + LifecyleNotification( + selector: #selector(willResignActiveNotification(notification:)), + name: NSApplication.willResignActiveNotification + ), + LifecyleNotification( + selector: #selector(willUnhideNotification(notification:)), + name: NSApplication.willUnhideNotification + ), + LifecyleNotification( + selector: #selector(willUpdateNotification(notification:)), + name: NSApplication.willUpdateNotification + ), + LifecyleNotification( + selector: #selector(willTerminateNotification(notification:)), + name: NSApplication.willTerminateNotification + ), + LifecyleNotification( + selector: #selector(didChangeScreenParametersNotification(notification:)), + name: NSApplication.didChangeScreenParametersNotification + ) + ] + } + + /// Initializes the class and registers to observe the lifecycle and system notifications. + public required init() { + super.init() + + for notification in lifecycleNotifications { + NotificationCenter.default.addObserver( + self, + selector: notification.selector, + name: notification.name, + object: nil + ) + } + } + + /// Called when application becomes active + @objc open func didBecomeActiveNotification(notification: Notification) { } + /// Called when application hides + @objc open func didHideNotification(notification: Notification) { } + /// Called when application finishes launching + @objc open func didFinishLaunchingNotification(notification: Notification) { } + /// Called when application resigns active state + @objc open func didResignActiveNotification(notification: Notification) { } + /// Called when application unhides + @objc open func didUnhideNotification(notification: Notification) { } + /// Called after application updates its windows and views + @objc open func didUpdateNotification(notification: Notification) { } + /// Called just before application becomes active + @objc open func willBecomeActiveNotification(notification: Notification) { } + /// Called just before application hides + @objc open func willHideNotification(notification: Notification) { } + /// Called just before application finishes launching + @objc open func willFinishLaunchingNotification(notification: Notification) { } + /// Called as application is about to resign its active status + @objc open func willResignActiveNotification(notification: Notification) { } + /// Called just as the application is about to unhide + @objc open func willUnhideNotification(notification: Notification) { } + /// Called just before application updates its windows and views + @objc open func willUpdateNotification(notification: Notification) { } + /// Called when application is about to terminate + @objc open func willTerminateNotification(notification: Notification) { } + /// Called when screen parameters (like resolution or color depth) change + @objc open func didChangeScreenParametersNotification(notification: Notification) { } +} +#elseif os(watchOS) +/// This is an open class that observes various lifecycle and system events. +open class LifecyleApplication: Application { + /** + An array of the lifecycle events observed by this class. This includes: + - didFinishLaunchingNotification + - willEnterForegroundNotification + - didBecomeActiveNotification + - didEnterBackgroundNotification + - willResignActiveNotification + */ + open var lifecycleNotifications: [LifecyleNotification] { + [ + LifecyleNotification( + selector: #selector(didFinishLaunchingNotification(notification:)), + name: WKApplication.didFinishLaunchingNotification + ), + LifecyleNotification( + selector: #selector(willEnterForegroundNotification(notification:)), + name: WKApplication.willEnterForegroundNotification + ), + LifecyleNotification( + selector: #selector(didBecomeActiveNotification(notification:)), + name: WKApplication.didBecomeActiveNotification + ), + LifecyleNotification( + selector: #selector(didEnterBackgroundNotification(notification:)), + name: WKApplication.didEnterBackgroundNotification + ), + LifecyleNotification( + selector: #selector(willResignActiveNotification(notification:)), + name: WKApplication.willResignActiveNotification + ) + ] + } + + /// Initializes the class and registers to observe the lifecycle notifications. + public required init() { + super.init() + + for notification in lifecycleNotifications { + NotificationCenter.default.addObserver( + self, + selector: notification.selector, + name: notification.name, + object: nil + ) + } + } + + /// Called when application finishes launching + @objc open func didFinishLaunchingNotification(notification: Notification) { } + /// Called when application will enter the foreground + @objc open func willEnterForegroundNotification(notification: Notification) { } + /// Called when application becomes active + @objc open func didBecomeActiveNotification(notification: Notification) { } + /// Called when application enters the background + @objc open func didEnterBackgroundNotification(notification: Notification) { } + /// Called when application is about to become inactive + @objc open func willResignActiveNotification(notification: Notification) { } +} +#elseif os(tvOS) +/// This is an open class that observes various lifecycle and system events. +open class LifecyleApplication: Application { + /** + An array of the lifecycle events observed by this class. This includes: + - didFinishLaunchingNotification + - willEnterForegroundNotification + - didBecomeActiveNotification + - didEnterBackgroundNotification + - willResignActiveNotification + */ + open var lifecycleNotifications: [LifecyleNotification] { + [ + LifecyleNotification( + selector: #selector(didFinishLaunchingNotification(notification:)), + name: UIApplication.didFinishLaunchingNotification + ), + LifecyleNotification( + selector: #selector(willEnterForegroundNotification(notification:)), + name: UIApplication.willEnterForegroundNotification + ), + LifecyleNotification( + selector: #selector(didBecomeActiveNotification(notification:)), + name: UIApplication.didBecomeActiveNotification + ), + LifecyleNotification( + selector: #selector(didEnterBackgroundNotification(notification:)), + name: UIApplication.didEnterBackgroundNotification + ), + LifecyleNotification( + selector: #selector(willResignActiveNotification(notification:)), + name: UIApplication.willResignActiveNotification + ) + ] + } + + /// Initializes the class and registers to observe the lifecycle notifications. + public required init() { + super.init() + + for notification in lifecycleNotifications { + NotificationCenter.default.addObserver( + self, + selector: notification.selector, + name: notification.name, + object: nil + ) + } + } + + /// Called when application finishes launching + @objc open func didFinishLaunchingNotification(notification: Notification) { } + /// Called when application will enter the foreground + @objc open func willEnterForegroundNotification(notification: Notification) { } + /// Called when application becomes active + @objc open func didBecomeActiveNotification(notification: Notification) { } + /// Called when application enters the background + @objc open func didEnterBackgroundNotification(notification: Notification) { } + /// Called when application is about to become inactive + @objc open func willResignActiveNotification(notification: Notification) { } +} +#endif diff --git a/Sources/ApplicationKit/RunOnce/RunOnce.swift b/Sources/ApplicationKit/RunOnce/RunOnce.swift new file mode 100644 index 0000000..b76bfc9 --- /dev/null +++ b/Sources/ApplicationKit/RunOnce/RunOnce.swift @@ -0,0 +1,62 @@ +import AppState +import Foundation + +private class RunOnceManager { + private var lock: NSLock + private var ran: [String] + + init() { + self.lock = NSLock() + self.ran = [] + } + + func add(_ id: String) { + lock.lock() + ran.append(id) + lock.unlock() + } + + func contains(id: String) -> Bool { + lock.lock(); defer { lock.unlock() } + + return ran.contains(id) + } +} + +extension Application { + private var runOnceManager: Dependency { + dependency(RunOnceManager()) + } + + /** + Ensures the specified closure only runs once within the lifecycle of the application. + + This function creates a unique identifier based on the passed in file identifier, function name, line number, and column number, where it's called. If the function has been called before with the same parameters, it will not execute the closure. Otherwise, it will add the unique identifier to the `runOnceManager` and execute the closure. + + Usage example: + ```swift + Application.runOnce { + performExpensiveTask() + } + ``` + + - Parameters: + - closure: The closure to be executed only once. + */ + public static func runOnce( + _ fileID: StaticString = #fileID, + _ function: StaticString = #function, + _ line: Int = #line, + _ column: Int = #column, + closure: () -> Void + ) { + let codeID = "\(fileID).\(function)@\(line)-\(column)" + let runOnceManager = dependency(\.runOnceManager) + + guard runOnceManager.contains(id: codeID) == false else { return } + + runOnceManager.add(codeID) + + closure() + } +} diff --git a/Tests/ApplicationKitTests/LifecyleApplicationTests.swift b/Tests/ApplicationKitTests/LifecyleApplicationTests.swift new file mode 100644 index 0000000..1e16cc5 --- /dev/null +++ b/Tests/ApplicationKitTests/LifecyleApplicationTests.swift @@ -0,0 +1,21 @@ +import XCTest +@testable import ApplicationKit + +private class MyApplication: LifecyleApplication { + + override var lifecycleNotifications: [LifecyleApplication.LifecyleNotification] { + super.lifecycleNotifications + [ + // Your notitifications + ] + } + + override func didBecomeActiveNotification(notification: Notification) { + + } +} + +final class LifecyleApplicationTests: XCTestCase { + func testLifecyleApplication() throws { + Application.promote(to: MyApplication.self) + } +} diff --git a/Tests/ApplicationKitTests/RunOnceTests.swift b/Tests/ApplicationKitTests/RunOnceTests.swift new file mode 100644 index 0000000..5a016fd --- /dev/null +++ b/Tests/ApplicationKitTests/RunOnceTests.swift @@ -0,0 +1,14 @@ +import XCTest +@testable import ApplicationKit + +final class RunOnceTests: XCTestCase { + func testRunOnceRunsOnce() throws { + for i in 0 ..< 10 { + Application.runOnce { + if i > 0 { + XCTFail() + } + } + } + } +}