[Widgets]: Use AppIntentConfiguration instead of StaticConfiguration and cleanup

This commit is contained in:
Magesh K
2025-01-10 08:11:35 +05:30
parent 4e10527f03
commit f69b293004
9 changed files with 340 additions and 178 deletions

View File

@@ -7,7 +7,6 @@
//
import AppIntents
import WidgetKit
public enum Direction: String, Sendable{
case up = "up"
@@ -15,43 +14,42 @@ public enum Direction: String, Sendable{
}
@available(iOS 17, *)
class PaginationIntent: AppIntent, @unchecked Sendable {
static var title: LocalizedStringResource { "Scroll up or down in Active Apps Widget" }
final class PaginationIntent: AppIntent, @unchecked Sendable {
static var title: LocalizedStringResource { "Page Navigation Intent" }
static var isDiscoverable: Bool { false }
@Parameter(title: "Direction")
var direction: String
@Parameter(title: "Widget Identifier")
@Parameter(title: "WidgetID")
var widgetID: String
private lazy var widgetHolderQ = {
DispatchQueue(label: widgetID)
}()
required init(){}
var uuid: String = UUID().uuidString
required init(){
print()
}
init(_ direction: Direction, _ widgetID: String){
self.direction = direction.rawValue
self.widgetID = widgetID
}
func perform() async throws -> some IntentResult {
guard let direction = Direction(rawValue: self.direction) else {
return .result()
}
widgetHolderQ.sync {
// update direction for this widgetID
let dataholder = PaginationDataHolder.holder(for: self.widgetID)
dataholder?.updateDirection(direction)
// if let widgetID = self.widgetID
// {
// WidgetCenter.shared.reloadTimelines(ofKind: widgetID)
// }
// return .result()
// ask widget views to be re-drawn by triggering timeline update
// for the widget uniquely identified by the 'kind: widgetID'
WidgetCenter.shared.reloadTimelines(ofKind: self.widgetID)
}
let result = try await WidgetUpdateIntent(
Direction(rawValue: self.direction),
self.widgetID
).perform()
return .result()
return result
}
}

View File

@@ -0,0 +1,42 @@
//
// WidgetUpdateIntent.swift
// AltStore
//
// Created by Magesh K on 10/01/25.
// Copyright © 2025 SideStore. All rights reserved.
//
import AppIntents
@available(iOS 17, *)
final class WidgetUpdateIntent: WidgetConfigurationIntent, @unchecked Sendable {
static var title: LocalizedStringResource { "Intent for WidgetAppIntentConfiguration receiver type" }
static var isDiscoverable: Bool { false }
var uuid: String = UUID().uuidString
private var widgetID: String?
@Parameter(title: "ID", description: "Change this to unique ID to keep changes isolated from other widgets", default: "1")
var ID: String?
// this static hack is required, coz we are making these intents stateful
private static var directionMap: [String: Direction] = [:]
init(){
print()
}
func getDirection( _ widgetID: String) -> Direction? {
// remove it, since the event is processed. if needed it will be added again
return Self.directionMap.removeValue(forKey: widgetID)
}
init(_ direction: Direction?, _ widgetID: String){
Self.directionMap[widgetID] = direction
}
func perform() async throws -> some IntentResult {
return .result()
}
}

View File

@@ -0,0 +1,36 @@
//
// ActiveAppsTimelineProvider+Simulator.swift
// AltStore
//
// Created by Magesh K on 10/01/25.
// Copyright © 2025 SideStore. All rights reserved.
//
/// Simulator data generator
#if DEBUG
@available(iOS 17, *)
extension ActiveAppsTimelineProvider {
func getSimulatedData(apps: [AppSnapshot]) -> [AppSnapshot]{
var apps = apps
var newSets: [AppSnapshot] = []
// this dummy data is for simulator (uncomment when testing ActiveAppsWidget pagination)
if (apps.count > 0){
let app = apps[0]
for i in 0..<10 {
let name = "\(app.name) - \(i)"
let x = AppSnapshot(name: name,
bundleIdentifier: app.bundleIdentifier,
expirationDate: app.expirationDate,
refreshedDate: app.refreshedDate
)
newSets.append(x)
}
apps = newSets
}
return apps
}
}
#endif

View File

@@ -0,0 +1,85 @@
//
// ActiveAppsTimelineProvider.swift
// AltStore
//
// Created by Magesh K on 10/01/25.
// Copyright © 2025 SideStore. All rights reserved.
//
import WidgetKit
protocol Navigation{
var direction: Direction? { get }
}
@available(iOS 17, *)
class ActiveAppsTimelineProvider: AppsTimelineProviderBase<Navigation> {
let uuid = UUID().uuidString
private let dataHolder: PaginationDataHolder
private let widgetID: String
init(kind: String){
print("Executing ActiveAppsTimelineProvider.init() for instance \(uuid)")
let itemsPerPage = ActiveAppsWidget.Constants.MAX_ROWS_PER_PAGE
self.dataHolder = PaginationDataHolder(itemsPerPage: itemsPerPage)
self.widgetID = kind
}
override func getUpdatedData(_ apps: [AppSnapshot], _ context: Navigation?) -> [AppSnapshot] {
guard let context = context else { return apps }
var apps = apps
// #if DEBUG
// apps = getSimulatedData(apps: apps)
// #endif
if let direction = context.direction{
// get paged data if available
switch (direction){
case Direction.up:
apps = dataHolder.prevPage(inItems: apps, whenUnavailable: .current)!
case Direction.down:
apps = dataHolder.nextPage(inItems: apps, whenUnavailable: .current)!
}
}else{
// retain what ever page we were on as-is
apps = dataHolder.currentPage(inItems: apps)
}
return apps
}
}
@available(iOS 17, *)
extension ActiveAppsTimelineProvider: AppIntentTimelineProvider {
struct IntentData: Navigation{
let direction: Direction?
}
typealias Intent = WidgetUpdateIntent
func snapshot(for intent: Intent, in context: Context) async -> AppsEntry {
let data = IntentData(direction: intent.getDirection(widgetID))
let bundleIDs = await super.fetchActiveAppBundleIDs()
let snapshot = await self.snapshot(for: bundleIDs, in: data)
return snapshot
}
func timeline(for intent: Intent, in context: Context) async -> Timeline<AppsEntry> {
let data = IntentData(direction: intent.getDirection(widgetID))
let bundleIDs = await self.fetchActiveAppBundleIDs()
let timeline = await self.timeline(for: bundleIDs, in: data)
return timeline
}
}

View File

@@ -20,22 +20,16 @@ struct AppsEntry: TimelineEntry
var isPlaceholder: Bool = false
}
struct AppsTimelineProvider
class AppsTimelineProviderBase<T>
{
typealias Entry = AppsEntry
private var dataHolder: PaginationDataHolder?
init(_ dataHolder: PaginationDataHolder? = nil){
self.dataHolder = dataHolder
}
func placeholder(in context: TimelineProviderContext) -> AppsEntry
{
return AppsEntry(date: Date(), apps: [], isPlaceholder: true)
}
func snapshot(for appBundleIDs: [String]) async -> AppsEntry
func snapshot(for appBundleIDs: [String], in context: T? = nil) async -> AppsEntry
{
do
{
@@ -43,7 +37,7 @@ struct AppsTimelineProvider
var apps = try await self.fetchApps(withBundleIDs: appBundleIDs)
apps = getUpdatedData(apps)
apps = getUpdatedData(apps, context)
let entry = AppsEntry(date: Date(), apps: apps)
return entry
@@ -57,7 +51,7 @@ struct AppsTimelineProvider
}
}
func timeline(for appBundleIDs: [String]) async -> Timeline<AppsEntry>
func timeline(for appBundleIDs: [String], in context: T? = nil) async -> Timeline<AppsEntry>
{
do
{
@@ -65,7 +59,7 @@ struct AppsTimelineProvider
var apps = try await self.fetchApps(withBundleIDs: appBundleIDs)
apps = getUpdatedData(apps)
apps = getUpdatedData(apps, context)
let entries = self.makeEntries(for: apps)
let timeline = Timeline(entries: entries, policy: .atEnd)
@@ -80,32 +74,22 @@ struct AppsTimelineProvider
return timeline
}
}
}
private extension AppsTimelineProvider
{
private func getUpdatedData(_ apps: [AppSnapshot]) -> [AppSnapshot]{
var apps = apps
// #if DEBUG
// // this dummy data is for simulator (uncomment when testing ActiveAppsWidget pagination)
// apps = apps + apps + apps + apps + apps + apps + apps + apps
// #endif
if let dataHolder{
// get paged data if present if available
apps = dataHolder.getUpdatedData(entries: apps)
}
func getUpdatedData(_ apps: [AppSnapshot], _ context: T?) -> [AppSnapshot]{
// override in subclasses as required
return apps
}
}
extension AppsTimelineProviderBase
{
func prepare() async throws
private func prepare() async throws
{
try await DatabaseManager.shared.start()
}
func fetchApps(withBundleIDs bundleIDs: [String]) async throws -> [AppSnapshot]
private func fetchApps(withBundleIDs bundleIDs: [String]) async throws -> [AppSnapshot]
{
let context = DatabaseManager.shared.persistentContainer.newBackgroundContext()
let apps = try await context.performAsync {
@@ -176,31 +160,8 @@ private extension AppsTimelineProvider
return entries
}
}
extension AppsTimelineProvider: TimelineProvider
{
func getSnapshot(in context: Context, completion: @escaping (AppsEntry) -> Void)
{
Task<Void, Never> {
let bundleIDs = await self.fetchActiveAppBundleIDs()
let snapshot = await self.snapshot(for: bundleIDs)
completion(snapshot)
}
}
func getTimeline(in context: Context, completion: @escaping (Timeline<AppsEntry>) -> Void)
{
Task<Void, Never> {
let bundleIDs = await self.fetchActiveAppBundleIDs()
let timeline = await self.timeline(for: bundleIDs)
completion(timeline)
}
}
private func fetchActiveAppBundleIDs() async -> [String]
func fetchActiveAppBundleIDs() async -> [String]
{
do
{
@@ -227,9 +188,8 @@ extension AppsTimelineProvider: TimelineProvider
}
}
extension AppsTimelineProvider: IntentTimelineProvider
class AppsTimelineProvider: AppsTimelineProviderBase<ViewAppIntent>, IntentTimelineProvider
{
typealias Intent = ViewAppIntent
func getSnapshot(for intent: Intent, in context: Context, completion: @escaping (AppsEntry) -> Void)
@@ -237,7 +197,7 @@ extension AppsTimelineProvider: IntentTimelineProvider
Task<Void, Never> {
let bundleIDs = [intent.app?.identifier ?? StoreApp.altstoreAppID]
let snapshot = await self.snapshot(for: bundleIDs)
let snapshot = await self.snapshot(for: bundleIDs, in: intent)
completion(snapshot)
}
}
@@ -247,7 +207,7 @@ extension AppsTimelineProvider: IntentTimelineProvider
Task<Void, Never> {
let bundleIDs = [intent.app?.identifier ?? StoreApp.altstoreAppID]
let timeline = await self.timeline(for: bundleIDs)
let timeline = await self.timeline(for: bundleIDs, in: intent)
completion(timeline)
}
}

View File

@@ -9,6 +9,8 @@
import SwiftUI
import WidgetKit
import AltStoreCore
private extension Color
{
static let altGradientLight = Color.init(.displayP3, red: 123.0/255.0, green: 200.0/255.0, blue: 176.0/255.0)
@@ -17,44 +19,36 @@ private extension Color
static let altGradientExtraDark = Color.init(.displayP3, red: 2.0/255.0, green: 82.0/255.0, blue: 103.0/255.0)
}
//@available(iOS 17, *)
struct ActiveAppsWidget: Widget
{
// only constants/singleton what needs to be for the life of all widgets of ActiveAppsWidget type
// should be declared as instance or class fields for ActiveAppWidgets
struct Constants{
static let MAX_ROWS_PER_PAGE: UInt = 3
}
// NOTE: The computed property (widget)body is recomputed/re-run for every
// 'type' refers to struct/class types and 'kind' refers to the tag which the widget is marked with
// multiple instances of same type or multiple types can be tagged with same 'kind'
// or each instance of same kind too, can be tagged as different(unique) 'kind'
// 1. widget-resizing(of same type)
// 2. new widget addition(of same type)
let ID = UUID().uuidString
public var body: some WidgetConfiguration {
print("Executing ActiveAppsWidget.body for instance \(ID)")
if #available(iOS 17, *)
{
let kind = "ActiveApps"
let widgetID = kind + "-" + UUID().uuidString
let widgetID = "ActiveApps - \(UUID().uuidString)"
let holder = PaginationDataHolder.instance(widgetID)
let timelineProvider = AppsTimelineProvider(holder) // pass the holder
// each instance of this widget type is identified by unique 'kind' tag
// so that a reloadTimelineFor(kind:) will trigger reload only for that instance
let staticConfig = StaticConfiguration(
let widgetConfig = AppIntentConfiguration(
kind: widgetID,
provider: timelineProvider
// intent: PaginationIntent.self, // Use the defined AppIntent
intent: WidgetUpdateIntent.self, // Use the defined AppIntent
provider: ActiveAppsTimelineProvider(kind: widgetID)
) { entry in
// actual view of the widget
// this gets recreated for each trigger from the scheduled timeline entries provided by the timeline provider
// NOTE: widget views do not adhere to statefulness
// so, Combine constructs such as @State, @StateObject, @ObservedObject etc are simply ignored
ActiveAppsWidgetView(entry: entry, widgetID: widgetID)
}
.supportedFamilies([.systemMedium])
.configurationDisplayName("Active Apps")
.description("View remaining days until your active apps expire. Tap the countdown timers to refresh them in the background.")
return staticConfig
return widgetConfig
}
else
{
@@ -71,6 +65,15 @@ private struct ActiveAppsWidgetView: View
var entry: AppsEntry
var widgetID: String
let ID = UUID().uuidString
init(entry: AppsEntry, widgetID: String) {
print("Executing ActiveAppsWidgetView.init() for instance \(ID)")
self.entry = entry
self.widgetID = widgetID
}
@Environment(\.colorScheme)
private var colorScheme
@@ -101,9 +104,9 @@ private struct ActiveAppsWidgetView: View
private var content: some View {
GeometryReader { (geometry) in
let MAX_ROWS_PER_PAGE = PaginationDataHolder.MAX_ROWS_PER_PAGE
let itemsPerPage = ActiveAppsWidget.Constants.MAX_ROWS_PER_PAGE
let preferredRowHeight = (geometry.size.height / Double(MAX_ROWS_PER_PAGE)) - 8
let preferredRowHeight = (geometry.size.height / Double(itemsPerPage)) - 8
let rowHeight = min(preferredRowHeight, geometry.size.height / 2)
HStack(alignment: .center) {

View File

@@ -1,72 +0,0 @@
//
// PaginationViewModel.swift
// AltStore
//
// Created by Magesh K on 09/01/25.
// Copyright © 2025 SideStore. All rights reserved.
//
import Foundation
class PaginationDataHolder: ObservableObject {
public static let MAX_ROWS_PER_PAGE: UInt = 3
private static var instances: [String:PaginationDataHolder] = [:]
public static func instance(_ widgetID: String) -> PaginationDataHolder {
let instance = PaginationDataHolder(widgetID)
Self.instances[widgetID] = instance
return instance
}
public static func holder(for widgetID: String) -> PaginationDataHolder? {
return Self.instances[widgetID]
}
private lazy var serializationQ = {
DispatchQueue(label: widgetID)
}()
public let widgetID: String
private var currentPageindex: UInt = 0
private init(_ widgetID: String){
self.widgetID = widgetID
}
deinit {
Self.instances.removeValue(forKey: widgetID)
}
public func updateDirection(_ direction: Direction) {
switch(direction){
case .up:
let pageIndex = Int(currentPageindex)
currentPageindex = UInt(max(0, pageIndex-1))
case .down:
// upper-bounds is checked when computing targetPageIndex in getUpdatedData
currentPageindex+=1
}
}
public func getUpdatedData(entries: [AppSnapshot]) -> [AppSnapshot] {
let count = UInt(entries.count)
if(count == 0) { return entries }
let availablePages = UInt(ceil(Double(entries.count) / Double(Self.MAX_ROWS_PER_PAGE)))
let targetPageIndex: UInt = currentPageindex < availablePages ? currentPageindex : availablePages-1
// do blocking update
serializationQ.sync {
self.currentPageindex = targetPageIndex // preserve it
}
let startIndex = targetPageIndex * Self.MAX_ROWS_PER_PAGE
let estimatedEndIndex = startIndex + (Self.MAX_ROWS_PER_PAGE-1)
let endIndex: UInt = min(count-1, estimatedEndIndex)
let currentPageEntries = entries[Int(startIndex) ... Int(endIndex)]
return Array(currentPageEntries)
}
}