From e29d9f7904d1a7d3319d4d6a221cda8dfec93d50 Mon Sep 17 00:00:00 2001 From: Magesh K <47920326+mahee96@users.noreply.github.com> Date: Sat, 11 Jan 2025 03:25:25 +0530 Subject: [PATCH] [Widgets]: Enhanced to isolate operations from multiple views of same widget type --- AltStore.xcodeproj/project.pbxproj | 26 +- AltWidget/Extensions/View+AltWidget.swift | 8 +- AltWidget/Intents/PaginationIntent.swift | 59 +++-- AltWidget/Intents/WidgetUpdateIntent.swift | 29 +- AltWidget/Manager/PageInfoManager.swift | 31 +++ ...ActiveAppsTimelineProvider+Simulator.swift | 4 +- .../ActiveAppsTimelineProvider.swift | 85 +++--- .../Providers/AppsTimelineProvider.swift | 46 ++-- AltWidget/Widgets/ActiveAppsWidget.swift | 247 ++++++++++-------- AltWidget/Widgets/AppDetailWidget.swift | 12 +- AltWidget/Widgets/LockScreenWidget.swift | 14 +- .../datastructures/SingletonGenericMap.swift | 30 +++ 12 files changed, 346 insertions(+), 245 deletions(-) create mode 100644 AltWidget/Manager/PageInfoManager.swift create mode 100644 SideStore/Utils/datastructures/SingletonGenericMap.swift diff --git a/AltStore.xcodeproj/project.pbxproj b/AltStore.xcodeproj/project.pbxproj index d1e42dce..852c9266 100644 --- a/AltStore.xcodeproj/project.pbxproj +++ b/AltStore.xcodeproj/project.pbxproj @@ -63,9 +63,11 @@ A82067C42D03E0DE00645C0D /* SemanticVersion in Frameworks */ = {isa = PBXBuildFile; productRef = A82067C32D03E0DE00645C0D /* SemanticVersion */; }; A859ED5C2D1EE827003DCC58 /* OpenSSL.xcframework in Frameworks */ = {isa = PBXBuildFile; fileRef = A859ED5B2D1EE80D003DCC58 /* OpenSSL.xcframework */; }; A859ED5D2D1EE827003DCC58 /* OpenSSL.xcframework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = A859ED5B2D1EE80D003DCC58 /* OpenSSL.xcframework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; + A868CFE42D31999A002F1201 /* SingletonGenericMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = A868CFE32D319988002F1201 /* SingletonGenericMap.swift */; }; A8945AA62D059B6100D86CBE /* Roxas.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A8945AA52D059B6100D86CBE /* Roxas.framework */; }; A8A543302D04F14400D72399 /* libfragmentzip.a in Frameworks */ = {isa = PBXBuildFile; fileRef = A8A5432F2D04F0C100D72399 /* libfragmentzip.a */; }; A8A853AF2D3065A300995795 /* ActiveAppsTimelineProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8A853AE2D3065A300995795 /* ActiveAppsTimelineProvider.swift */; }; + A8AD35592D31BF2C003A28B4 /* PageInfoManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8AD35582D31BF29003A28B4 /* PageInfoManager.swift */; }; A8B516E32D2666CA0047047C /* CoreDataHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8B516E22D2666CA0047047C /* CoreDataHelper.swift */; }; A8B516E62D2668170047047C /* DateTimeUtil.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8B516E52D2668020047047C /* DateTimeUtil.swift */; }; A8BB34E52D04EC8E000A8B4D /* minimuxer-helpers.swift in Sources */ = {isa = PBXBuildFile; fileRef = A809F6A52D04DA1900F0F0F3 /* minimuxer-helpers.swift */; }; @@ -642,8 +644,10 @@ A85ACB932D1F31C400AA3DE7 /* AltWidgetExtension.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AltWidgetExtension.xcconfig; sourceTree = ""; }; A86202322D1F35640091187B /* AltStore.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AltStore.xcconfig; sourceTree = ""; }; A86202332D1F35640091187B /* AltStoreCore.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AltStoreCore.xcconfig; sourceTree = ""; }; + A868CFE32D319988002F1201 /* SingletonGenericMap.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SingletonGenericMap.swift; sourceTree = ""; }; A8945AA52D059B6100D86CBE /* Roxas.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; path = Roxas.framework; sourceTree = BUILT_PRODUCTS_DIR; }; A8A853AE2D3065A300995795 /* ActiveAppsTimelineProvider.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ActiveAppsTimelineProvider.swift; sourceTree = ""; }; + A8AD35582D31BF29003A28B4 /* PageInfoManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PageInfoManager.swift; sourceTree = ""; }; A8B516E22D2666CA0047047C /* CoreDataHelper.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CoreDataHelper.swift; sourceTree = ""; }; A8B516E52D2668020047047C /* DateTimeUtil.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DateTimeUtil.swift; sourceTree = ""; }; A8C38C1D2D206A3A00E83DBD /* ConsoleLogger.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConsoleLogger.swift; sourceTree = ""; }; @@ -1184,8 +1188,8 @@ A80D790B2D2F209700A40F40 /* Intents */ = { isa = PBXGroup; children = ( - A8096D172D30AD4F000C39C6 /* WidgetUpdateIntent.swift */, A80D790C2D2F20AF00A40F40 /* PaginationIntent.swift */, + A8096D172D30AD4F000C39C6 /* WidgetUpdateIntent.swift */, ); path = Intents; sourceTree = ""; @@ -1224,6 +1228,22 @@ path = pagination; sourceTree = ""; }; + A8AD35562D31BE8F003A28B4 /* Manager */ = { + isa = PBXGroup; + children = ( + A8AD35582D31BF29003A28B4 /* PageInfoManager.swift */, + ); + path = Manager; + sourceTree = ""; + }; + A8AD35572D31BEB2003A28B4 /* datastructures */ = { + isa = PBXGroup; + children = ( + A868CFE32D319988002F1201 /* SingletonGenericMap.swift */, + ); + path = datastructures; + sourceTree = ""; + }; A8B516DE2D2666900047047C /* dignostics */ = { isa = PBXGroup; children = ( @@ -1243,6 +1263,7 @@ A8C38C1C2D2068D100E83DBD /* Utils */ = { isa = PBXGroup; children = ( + A8AD35572D31BEB2003A28B4 /* datastructures */, A8A853AD2D3050CC00995795 /* pagination */, A8087E712D2D291B002DB21B /* importexport */, A8B516DE2D2666900047047C /* dignostics */, @@ -1731,6 +1752,7 @@ BF98916C250AABF3002ACF50 /* AltWidget */ = { isa = PBXGroup; children = ( + A8AD35562D31BE8F003A28B4 /* Manager */, A80D790B2D2F209700A40F40 /* Intents */, A8096D1D2D30ADD5000C39C6 /* Providers */, A800F6FE2CE28DE300208744 /* Extensions */, @@ -2940,7 +2962,9 @@ A8096D1C2D30ADA9000C39C6 /* ActiveAppsTimelineProvider+Simulator.swift in Sources */, A80D790D2D2F20AF00A40F40 /* PaginationIntent.swift in Sources */, D5FD4EC92A9530C00097BEE8 /* AppSnapshot.swift in Sources */, + A8AD35592D31BF2C003A28B4 /* PageInfoManager.swift in Sources */, D5151BE72A90395400C96F28 /* View+AltWidget.swift in Sources */, + A868CFE42D31999A002F1201 /* SingletonGenericMap.swift in Sources */, A8A853AF2D3065A300995795 /* ActiveAppsTimelineProvider.swift in Sources */, BF98917F250AAC4F002ACF50 /* LockScreenWidget.swift in Sources */, A800F7042CE28E3800208744 /* View+AltWidget.swift in Sources */, diff --git a/AltWidget/Extensions/View+AltWidget.swift b/AltWidget/Extensions/View+AltWidget.swift index b9a61a5a..9a7f7974 100644 --- a/AltWidget/Extensions/View+AltWidget.swift +++ b/AltWidget/Extensions/View+AltWidget.swift @@ -55,9 +55,9 @@ extension View } @ViewBuilder - func pageUpButton(_ widgetID: String) -> some View { + func pageUpButton(_ widgetID: Int?) -> some View { if #available(iOSApplicationExtension 17, *) { - Button(intent: PaginationIntent(.up, widgetID)){ + Button(intent: PaginationIntent(widgetID, .up)){ self } .buttonStyle(.plain) @@ -67,9 +67,9 @@ extension View } @ViewBuilder - func pageDownButton(_ widgetID: String) -> some View { + func pageDownButton(_ widgetID: Int?) -> some View { if #available(iOSApplicationExtension 17, *) { - Button(intent: PaginationIntent(.down, widgetID)){ + Button(intent: PaginationIntent(widgetID, .down)){ self } .buttonStyle(.plain) diff --git a/AltWidget/Intents/PaginationIntent.swift b/AltWidget/Intents/PaginationIntent.swift index 48041467..7161636a 100644 --- a/AltWidget/Intents/PaginationIntent.swift +++ b/AltWidget/Intents/PaginationIntent.swift @@ -7,49 +7,50 @@ // import AppIntents +import Intents +import WidgetKit public enum Direction: String, Sendable{ - case up = "up" - case down = "down" + case up + case down +} + +public struct NavigationEvent { + let direction: Direction? + var consumed: Bool = false } @available(iOS 17, *) -final class PaginationIntent: AppIntent, @unchecked Sendable { +class PaginationIntent: AppIntent, @unchecked Sendable { - static var title: LocalizedStringResource { "Page Navigation Intent" } - static var isDiscoverable: Bool { false } + private let COMMON_WIDGET_ID = 1 + + static var title: LocalizedStringResource = "Page Navigation Intent" + static var isDiscoverable: Bool = false + + @Parameter(title: "widgetID") + var widgetID: Int @Parameter(title: "Direction") var direction: String - @Parameter(title: "WidgetID") - var widgetID: String + required init(){} - var uuid: String = UUID().uuidString - - required init(){ - print() - } - - init(_ direction: Direction, _ widgetID: String){ + init(_ widgetID: Int?, _ direction: Direction){ + // if id was not passed in, then we assume the widget isn't customized yet + // hence we use the common ID, if this is not present in registry of PageInfoManager + // then it will return nil, triggering to show first page in the provider + self.widgetID = widgetID ?? COMMON_WIDGET_ID self.direction = direction.rawValue - self.widgetID = widgetID } func perform() async throws -> some IntentResult { -// if let widgetID = self.widgetID -// { -// WidgetCenter.shared.reloadTimelines(ofKind: widgetID) -// } -// return .result() - - let result = try await WidgetUpdateIntent( - Direction(rawValue: self.direction), - self.widgetID - ).perform() - - return result + let widgetIdString = String(widgetID) + DispatchQueue(label: widgetIdString).sync { + let navigationEvent = NavigationEvent(direction: Direction(rawValue: direction)) + PageInfoManager.shared.setPageInfo(for: widgetID, value: navigationEvent) + WidgetCenter.shared.reloadTimelines(ofKind: widgetIdString) + } + return .result() } } - - diff --git a/AltWidget/Intents/WidgetUpdateIntent.swift b/AltWidget/Intents/WidgetUpdateIntent.swift index 8781d6b2..61d0c781 100644 --- a/AltWidget/Intents/WidgetUpdateIntent.swift +++ b/AltWidget/Intents/WidgetUpdateIntent.swift @@ -11,32 +11,9 @@ import AppIntents @available(iOS 17, *) final class WidgetUpdateIntent: WidgetConfigurationIntent, @unchecked Sendable { - static var title: LocalizedStringResource { "Intent for WidgetAppIntentConfiguration receiver type" } + static var title: LocalizedStringResource { "Widget ID update Intent" } 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() - } + @Parameter(title: "ID", description: "Provide a numeric ID to identify the widget", default: 1) + var ID: Int? } diff --git a/AltWidget/Manager/PageInfoManager.swift b/AltWidget/Manager/PageInfoManager.swift new file mode 100644 index 00000000..a06e4af5 --- /dev/null +++ b/AltWidget/Manager/PageInfoManager.swift @@ -0,0 +1,31 @@ +// +// PageInfoManager.swift +// AltStore +// +// Created by Magesh K on 11/01/25. +// Copyright © 2025 SideStore. All rights reserved. +// + +// This is a utility class +class PageInfoManager { + static var shared = PageInfoManager() + private var pageInfoMap: [Int: NavigationEvent] = [:] + + private init() {} + + func setPageInfo(for key: Int, value: NavigationEvent?) { + pageInfoMap[key] = value + } + + func getPageInfo(for key: Int) -> NavigationEvent? { + return pageInfoMap[key] + } + + func popPageInfo(for key: Int) -> NavigationEvent? { + return pageInfoMap.removeValue(forKey: key) + } + + func clearAll() { + pageInfoMap.removeAll() + } +} diff --git a/AltWidget/Providers/ActiveAppsTimelineProvider+Simulator.swift b/AltWidget/Providers/ActiveAppsTimelineProvider+Simulator.swift index f074e7a1..e319d6db 100644 --- a/AltWidget/Providers/ActiveAppsTimelineProvider+Simulator.swift +++ b/AltWidget/Providers/ActiveAppsTimelineProvider+Simulator.swift @@ -8,7 +8,7 @@ /// Simulator data generator -#if DEBUG +#if targetEnvironment(simulator) @available(iOS 17, *) extension ActiveAppsTimelineProvider { @@ -18,7 +18,7 @@ extension ActiveAppsTimelineProvider { // this dummy data is for simulator (uncomment when testing ActiveAppsWidget pagination) if (apps.count > 0){ let app = apps[0] - for i in 0..<10 { + for i in 1...10 { let name = "\(app.name) - \(i)" let x = AppSnapshot(name: name, bundleIdentifier: app.bundleIdentifier, diff --git a/AltWidget/Providers/ActiveAppsTimelineProvider.swift b/AltWidget/Providers/ActiveAppsTimelineProvider.swift index ce02bd09..615f85d9 100644 --- a/AltWidget/Providers/ActiveAppsTimelineProvider.swift +++ b/AltWidget/Providers/ActiveAppsTimelineProvider.swift @@ -8,77 +8,88 @@ import WidgetKit -protocol Navigation{ - var direction: Direction? { get } +protocol WidgetInfo{ + var ID: Int? { get } } @available(iOS 17, *) -class ActiveAppsTimelineProvider: AppsTimelineProviderBase { - - let uuid = UUID().uuidString - +class ActiveAppsTimelineProvider: AppsTimelineProviderBase { + public struct WidgetData: WidgetInfo { + let ID: Int? + } + 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 } - + deinit{ + // if this provider goes out of scope, clear all entries + PageInfoManager.shared.clearAll() + } + + override func getUpdatedData(_ apps: [AppSnapshot], _ context: WidgetInfo?) -> [AppSnapshot] { var apps = apps -// #if DEBUG -// apps = getSimulatedData(apps: apps) -// #endif + #if targetEnvironment(simulator) + 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)! + var currentPageApps = dataHolder.currentPage(inItems: apps) + if let widgetInfo = context, + let widgetID = widgetInfo.ID { + + var navEvent: NavigationEvent? = PageInfoManager.shared.getPageInfo(for: widgetID) + if let event = navEvent, + let direction = event.direction + { + // process navigation request only if event wasn't consumed yet + if !event.consumed { + switch (direction){ + case Direction.up: + currentPageApps = dataHolder.prevPage(inItems: apps, whenUnavailable: .current)! + case Direction.down: + currentPageApps = dataHolder.nextPage(inItems: apps, whenUnavailable: .current)! + } + // mark the event as consumed + // this prevents duplicate getUpdatedData() requests for same navigation event + navEvent!.consumed = true + } } - }else{ - // retain what ever page we were on as-is - apps = dataHolder.currentPage(inItems: apps) + PageInfoManager.shared.setPageInfo(for: widgetID, value: navEvent) } - return apps + return currentPageApps } } +/// TimelineProvider for WidgetAppIntentConfiguration widget type @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)) + func snapshot(for intent: Intent, in context: Context) async -> AppsEntry { + // system retains the previously configured ID value and posts the same here + let widgetData = WidgetData(ID: intent.ID) let bundleIDs = await super.fetchActiveAppBundleIDs() - - let snapshot = await self.snapshot(for: bundleIDs, in: data) + let snapshot = await self.snapshot(for: bundleIDs, in: widgetData) return snapshot } - func timeline(for intent: Intent, in context: Context) async -> Timeline { - let data = IntentData(direction: intent.getDirection(widgetID)) - + func timeline(for intent: Intent, in context: Context) async -> Timeline> { + // system retains the previously configured ID value and posts the same here + let widgetData = WidgetData(ID: intent.ID) + let bundleIDs = await self.fetchActiveAppBundleIDs() - - let timeline = await self.timeline(for: bundleIDs, in: data) + let timeline = await self.timeline(for: bundleIDs, in: widgetData) return timeline } diff --git a/AltWidget/Providers/AppsTimelineProvider.swift b/AltWidget/Providers/AppsTimelineProvider.swift index eee98ef4..d6fb9a90 100644 --- a/AltWidget/Providers/AppsTimelineProvider.swift +++ b/AltWidget/Providers/AppsTimelineProvider.swift @@ -11,25 +11,28 @@ import CoreData import AltStoreCore -struct AppsEntry: TimelineEntry +struct AppsEntry: TimelineEntry { var date: Date var relevance: TimelineEntryRelevance? var apps: [AppSnapshot] var isPlaceholder: Bool = false + + var context: T? + } class AppsTimelineProviderBase { typealias Entry = AppsEntry - func placeholder(in context: TimelineProviderContext) -> AppsEntry + func placeholder(in context: TimelineProviderContext) -> AppsEntry { return AppsEntry(date: Date(), apps: [], isPlaceholder: true) } - func snapshot(for appBundleIDs: [String], in context: T? = nil) async -> AppsEntry + func snapshot(for appBundleIDs: [String], in context: T? = nil) async -> AppsEntry { do { @@ -39,19 +42,19 @@ class AppsTimelineProviderBase apps = getUpdatedData(apps, context) - let entry = AppsEntry(date: Date(), apps: apps) + let entry = AppsEntry(date: Date(), apps: apps, context: context) return entry } catch { print("Failed to prepare widget snapshot:", error) - let entry = AppsEntry(date: Date(), apps: []) + let entry = AppsEntry(date: Date(), apps: [], context: context) return entry } } - func timeline(for appBundleIDs: [String], in context: T? = nil) async -> Timeline + func timeline(for appBundleIDs: [String], in context: T? = nil) async -> Timeline> { do { @@ -61,7 +64,14 @@ class AppsTimelineProviderBase apps = getUpdatedData(apps, context) - let entries = self.makeEntries(for: apps) + var entries = self.makeEntries(for: apps, in: context) + +// #if targetEnvironment(simulator) +// if let first = entries.first{ +// entries = [first] +// } +// #endif + let timeline = Timeline(entries: entries, policy: .atEnd) return timeline } @@ -69,7 +79,7 @@ class AppsTimelineProviderBase { print("Failed to prepare widget timeline:", error) - let entry = AppsEntry(date: Date(), apps: []) + let entry = AppsEntry(date: Date(), apps: [], context: context) let timeline = Timeline(entries: [entry], policy: .atEnd) return timeline } @@ -109,7 +119,7 @@ extension AppsTimelineProviderBase return apps } - func makeEntries(for snapshots: [AppSnapshot]) -> [AppsEntry] + func makeEntries(for snapshots: [AppSnapshot], in context: T? = nil) -> [AppsEntry] { let sortedAppsByExpirationDate = snapshots.sorted { $0.expirationDate < $1.expirationDate } guard let firstExpiringApp = sortedAppsByExpirationDate.first, let lastExpiringApp = sortedAppsByExpirationDate.last else { return [] } @@ -118,16 +128,16 @@ extension AppsTimelineProviderBase let numberOfDays = lastExpiringApp.expirationDate.numberOfCalendarDays(since: currentDate) // Generate a timeline consisting of one entry per day. - var entries: [AppsEntry] = [] + var entries: [AppsEntry] = [] switch numberOfDays { case ..<0: - let entry = AppsEntry(date: currentDate, relevance: TimelineEntryRelevance(score: 0.0), apps: snapshots) + let entry = AppsEntry(date: currentDate, relevance: TimelineEntryRelevance(score: 0.0), apps: snapshots, context: context) entries.append(entry) case 0: - let entry = AppsEntry(date: currentDate, relevance: TimelineEntryRelevance(score: 1.0), apps: snapshots) + let entry = AppsEntry(date: currentDate, relevance: TimelineEntryRelevance(score: 1.0), apps: snapshots, context: context) entries.append(entry) default: @@ -151,7 +161,7 @@ extension AppsTimelineProviderBase score = 0 } - let entry = AppsEntry(date: entryDate, relevance: TimelineEntryRelevance(score: score), apps: snapshots) + let entry = AppsEntry(date: entryDate, relevance: TimelineEntryRelevance(score: score), apps: snapshots, context: context) return entry } @@ -188,11 +198,11 @@ extension AppsTimelineProviderBase } } -class AppsTimelineProvider: AppsTimelineProviderBase, IntentTimelineProvider +typealias Intent = ViewAppIntent + +class AppsTimelineProvider: AppsTimelineProviderBase, IntentTimelineProvider { - typealias Intent = ViewAppIntent - - func getSnapshot(for intent: Intent, in context: Context, completion: @escaping (AppsEntry) -> Void) + func getSnapshot(for intent: Intent, in context: Context, completion: @escaping (AppsEntry) -> Void) { Task { let bundleIDs = [intent.app?.identifier ?? StoreApp.altstoreAppID] @@ -202,7 +212,7 @@ class AppsTimelineProvider: AppsTimelineProviderBase, IntentTimel } } - func getTimeline(for intent: Intent, in context: Context, completion: @escaping (Timeline) -> Void) + func getTimeline(for intent: Intent, in context: Context, completion: @escaping (Timeline>) -> Void) { Task { let bundleIDs = [intent.app?.identifier ?? StoreApp.altstoreAppID] diff --git a/AltWidget/Widgets/ActiveAppsWidget.swift b/AltWidget/Widgets/ActiveAppsWidget.swift index 7d937624..45116fc8 100644 --- a/AltWidget/Widgets/ActiveAppsWidget.swift +++ b/AltWidget/Widgets/ActiveAppsWidget.swift @@ -11,6 +11,8 @@ import WidgetKit import AltStoreCore +import GameplayKit + private extension Color { static let altGradientLight = Color.init(.displayP3, red: 123.0/255.0, green: 200.0/255.0, blue: 176.0/255.0) @@ -19,6 +21,9 @@ private extension Color static let altGradientExtraDark = Color.init(.displayP3, red: 2.0/255.0, green: 82.0/255.0, blue: 103.0/255.0) } +struct WidgetTag: WidgetInfo{ + let ID: Int? +} //@available(iOS 17, *) struct ActiveAppsWidget: Widget @@ -27,22 +32,17 @@ struct ActiveAppsWidget: Widget static let MAX_ROWS_PER_PAGE: UInt = 3 } - let ID = UUID().uuidString - public var body: some WidgetConfiguration { - print("Executing ActiveAppsWidget.body for instance \(ID)") - if #available(iOS 17, *) { let widgetID = "ActiveApps - \(UUID().uuidString)" let widgetConfig = AppIntentConfiguration( kind: widgetID, -// intent: PaginationIntent.self, // Use the defined AppIntent - intent: WidgetUpdateIntent.self, // Use the defined AppIntent - provider: ActiveAppsTimelineProvider(kind: widgetID) + intent: WidgetUpdateIntent.self, + provider: ActiveAppsTimelineProvider(kind: widgetID) ) { entry in - ActiveAppsWidgetView(entry: entry, widgetID: widgetID) + ActiveAppsWidgetView(entry: entry) } .supportedFamilies([.systemMedium]) .configurationDisplayName("Active Apps") @@ -62,17 +62,7 @@ struct ActiveAppsWidget: Widget @available(iOS 17, *) 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 - } + var entry: AppsEntry @Environment(\.colorScheme) private var colorScheme @@ -103,104 +93,131 @@ private struct ActiveAppsWidgetView: View private var content: some View { GeometryReader { (geometry) in - - let itemsPerPage = ActiveAppsWidget.Constants.MAX_ROWS_PER_PAGE - - let preferredRowHeight = (geometry.size.height / Double(itemsPerPage)) - 8 - let rowHeight = min(preferredRowHeight, geometry.size.height / 2) - HStack(alignment: .center) { - LazyVStack(spacing: 12) { - ForEach(Array(entry.apps.enumerated()), id: \.offset) { index, app in - - let icon: UIImage = app.icon ?? UIImage(named: "SideStore")! - - // 1024x1024 images are not supported by previews but supported by device - // so we scale the image to 97% so as to reduce its actual size but not too much - // to somewhere below value, acceptable by previews ie < 1042x948 - let scalingFactor = 0.97 - - let resizedSize = CGSize( - width: icon.size.width * scalingFactor, - height: icon.size.height * scalingFactor - ) - - let resizedIcon = icon.resizing(to: resizedSize)! - - let daysRemaining = app.expirationDate.numberOfCalendarDays(since: entry.date) - let cornerRadius = rowHeight / 5.0 - - HStack(spacing: 10) { - Image(uiImage: resizedIcon) - .resizable() - .aspectRatio(contentMode: .fit) - .cornerRadius(cornerRadius) - - VStack(alignment: .leading, spacing: 1) { - Text(app.name) - .font(.system(size: 15, weight: .semibold, design: .rounded)) - - let text = if entry.date > app.expirationDate - { - Text("Expired") - } - else - { - Text("Expires in \(daysRemaining) ") + (daysRemaining == 1 ? Text("day") : Text("days")) - } - - text - .font(.system(size: 13, weight: .semibold, design: .rounded)) - .foregroundStyle(.secondary) - } - - Spacer() - - Countdown(startDate: app.refreshedDate, - endDate: app.expirationDate, - currentDate: entry.date, - strokeWidth: 3.0) // Slightly thinner circle stroke width - .background { - Color.black.opacity(0.1) - .mask(Capsule()) - .padding(.all, -5) - } - .font(.system(size: 16, weight: .semibold, design: .rounded)) - // this modifier invalidates the view (disables userinteraction and shows a blinking effect) - // until new timeline events occur, unless a observable boolean state is presented as parameter - .invalidatableContent() - .activatesRefreshAllAppsIntent() - } - .frame(height: rowHeight) - } - } + + appsListView(reader: geometry) Spacer(minLength: 16) - let buttonWidth: CGFloat = 16 - VStack { - Image(systemName: "arrow.up") - .resizable() - .frame(width: buttonWidth, height: buttonWidth) - .opacity(0.3) - // .mask(Capsule()) - .pageUpButton(widgetID) - - Spacer() - - Image(systemName: "arrow.down") - .resizable() - .frame(width: buttonWidth, height: buttonWidth) - .opacity(0.3) - // .mask(Capsule()) - .pageDownButton(widgetID) - } - .padding(.vertical) + navigationBarView() + } .frame(maxWidth: .infinity, maxHeight: .infinity) } } + private func appsListView(reader: GeometryProxy) -> some View { + let itemsPerPage = ActiveAppsWidget.Constants.MAX_ROWS_PER_PAGE + + let preferredRowHeight = (reader.size.height / Double(itemsPerPage)) - 8 + let rowHeight = min(preferredRowHeight, reader.size.height / 2) + + return LazyVStack(spacing: 12) { + ForEach(Array(entry.apps.enumerated()), id: \.offset) { index, app in + + appEntryRowView(app: app, rowHeight: rowHeight) + + } + } + } + + + private func appEntryRowView(app: AppSnapshot, rowHeight: Double) -> some View { + let icon: UIImage = app.icon ?? UIImage(named: "SideStore")! + + // 1024x1024 images are not supported by previews but supported by device + // so we scale the image to 97% so as to reduce its actual size but not too much + // to somewhere below value, acceptable by previews ie < 1042x948 + let scalingFactor = 0.97 + + let resizedSize = CGSize( + width: icon.size.width * scalingFactor, + height: icon.size.height * scalingFactor + ) + + let resizedIcon = icon.resizing(to: resizedSize)! + let cornerRadius = rowHeight / 5.0 + + return HStack(spacing: 10) { + Image(uiImage: resizedIcon) + .resizable() + .aspectRatio(contentMode: .fit) + .cornerRadius(cornerRadius) + + appDetailsView(app) + + Spacer() + + countDownView(app) + + } + .frame(height: rowHeight) + } + + + private func appDetailsView(_ app: AppSnapshot) -> some View { + let daysRemaining = app.expirationDate.numberOfCalendarDays(since: entry.date) + + return VStack(alignment: .leading, spacing: 1) { + Text(app.name) + .font(.system(size: 15, weight: .semibold, design: .rounded)) + + let text = if entry.date > app.expirationDate + { + Text("Expired") + } + else + { + Text("Expires in \(daysRemaining) ") + (daysRemaining == 1 ? Text("day") : Text("days")) + } + + text + .font(.system(size: 13, weight: .semibold, design: .rounded)) + .foregroundStyle(.secondary) + } + } + + private func countDownView(_ app: AppSnapshot) -> some View { + Countdown(startDate: app.refreshedDate, + endDate: app.expirationDate, + currentDate: entry.date, + strokeWidth: 3.0) // Slightly thinner circle stroke width + .background { + Color.black.opacity(0.1) + .mask(Capsule()) + .padding(.all, -5) + } + .font(.system(size: 16, weight: .semibold, design: .rounded)) + // this modifier invalidates the view (disables user interaction and shows a blinking effect) + .invalidatableContent() + .activatesRefreshAllAppsIntent() + + } + + private func navigationBarView() -> some View { + let buttonWidth: CGFloat = 16 + let widgetID = entry.context?.ID + + return VStack { + Image(systemName: "arrow.up") + .resizable() + .frame(width: buttonWidth, height: buttonWidth) + .opacity(0.3) + // .mask(Capsule()) + .pageUpButton(widgetID) + + Spacer() + + Image(systemName: "arrow.down") + .resizable() + .frame(width: buttonWidth, height: buttonWidth) + .opacity(0.3) + // .mask(Capsule()) + .pageDownButton(widgetID) + } + .padding(.vertical) + } + private var placeholder: some View { Text("App Not Found") .font(.system(.body, design: .rounded)) @@ -216,14 +233,14 @@ private struct ActiveAppsWidgetView: View let expiredDate = Date().addingTimeInterval(1 * 60 * 60 * 24 * 7) let (altstore, delta, clip, longAltStore, longDelta, longClip) = AppSnapshot.makePreviewSnapshots() - AppsEntry(date: Date(), apps: [altstore, delta, clip]) - AppsEntry(date: Date(), apps: [longAltStore, longDelta, longClip]) + AppsEntry(date: Date(), apps: [altstore, delta, clip]) + AppsEntry(date: Date(), apps: [longAltStore, longDelta, longClip]) - AppsEntry(date: expiredDate, apps: [altstore, delta, clip]) + AppsEntry(date: expiredDate, apps: [altstore, delta, clip]) - AppsEntry(date: Date(), apps: [altstore, delta]) - AppsEntry(date: Date(), apps: [altstore]) + AppsEntry(date: Date(), apps: [altstore, delta]) + AppsEntry(date: Date(), apps: [altstore]) - AppsEntry(date: Date(), apps: []) - AppsEntry(date: Date(), apps: [], isPlaceholder: true) + AppsEntry(date: Date(), apps: []) + AppsEntry(date: Date(), apps: [], isPlaceholder: true) } diff --git a/AltWidget/Widgets/AppDetailWidget.swift b/AltWidget/Widgets/AppDetailWidget.swift index cee091b2..67cc0080 100644 --- a/AltWidget/Widgets/AppDetailWidget.swift +++ b/AltWidget/Widgets/AppDetailWidget.swift @@ -39,7 +39,7 @@ struct AppDetailWidget: Widget private struct AppDetailWidgetView: View { - var entry: AppsEntry + var entry: AppsEntry var body: some View { Group { @@ -200,11 +200,11 @@ private extension AppDetailWidgetView } timeline: { let expiredDate = Date().addingTimeInterval(1 * 60 * 60 * 24 * 7) let (altstore, _, _, longAltStore, _, _) = AppSnapshot.makePreviewSnapshots() - AppsEntry(date: Date(), apps: [altstore]) - AppsEntry(date: Date(), apps: [longAltStore]) + AppsEntry(date: Date(), apps: [altstore]) + AppsEntry(date: Date(), apps: [longAltStore]) - AppsEntry(date: expiredDate, apps: [altstore]) + AppsEntry(date: expiredDate, apps: [altstore]) - AppsEntry(date: Date(), apps: []) - AppsEntry(date: Date(), apps: [], isPlaceholder: true) + AppsEntry(date: Date(), apps: []) + AppsEntry(date: Date(), apps: [], isPlaceholder: true) } diff --git a/AltWidget/Widgets/LockScreenWidget.swift b/AltWidget/Widgets/LockScreenWidget.swift index b1ca5866..68cbea41 100644 --- a/AltWidget/Widgets/LockScreenWidget.swift +++ b/AltWidget/Widgets/LockScreenWidget.swift @@ -70,7 +70,7 @@ extension ComplicationView @available(iOS 16, *) private struct ComplicationView: View { - let entry: AppsEntry + let entry: AppsEntry let style: Style var body: some View { @@ -144,10 +144,10 @@ private let widgetFamily = if #available(iOS 16, *) { WidgetFamily.accessoryCirc let expiredDate = Date().addingTimeInterval(1 * 60 * 60 * 24 * 7) let (altstore, _, _, longAltStore, _, _) = AppSnapshot.makePreviewSnapshots() - AppsEntry(date: Date(), apps: [altstore]) - AppsEntry(date: Date(), apps: [longAltStore]) + AppsEntry(date: Date(), apps: [altstore]) + AppsEntry(date: Date(), apps: [longAltStore]) - AppsEntry(date: expiredDate, apps: [altstore]) + AppsEntry(date: expiredDate, apps: [altstore]) } @available(iOS 17, *) @@ -157,8 +157,8 @@ private let widgetFamily = if #available(iOS 16, *) { WidgetFamily.accessoryCirc let expiredDate = Date().addingTimeInterval(1 * 60 * 60 * 24 * 7) let (altstore, _, _, longAltStore, _, _) = AppSnapshot.makePreviewSnapshots() - AppsEntry(date: Date(), apps: [altstore]) - AppsEntry(date: Date(), apps: [longAltStore]) + AppsEntry(date: Date(), apps: [altstore]) + AppsEntry(date: Date(), apps: [longAltStore]) - AppsEntry(date: expiredDate, apps: [altstore]) + AppsEntry(date: expiredDate, apps: [altstore]) } diff --git a/SideStore/Utils/datastructures/SingletonGenericMap.swift b/SideStore/Utils/datastructures/SingletonGenericMap.swift new file mode 100644 index 00000000..067e8a0d --- /dev/null +++ b/SideStore/Utils/datastructures/SingletonGenericMap.swift @@ -0,0 +1,30 @@ +// +// SingletonGenericMap.swift +// SideStore +// +// Created by Magesh K on 10/01/25. +// Copyright © 2025 SideStore. All rights reserved. +// + +class SingletonGenericMap{ + static var shared = SingletonGenericMap() + private var pageInfoMap: [AnyHashable: Any] = [:] + + private init() {} + + func setPageInfo(for key: T, value: U?) { + pageInfoMap[key] = value + } + + func getPageInfo(for key: T) -> U? { + return pageInfoMap[key] as? U + } + + func popPageInfo(for key: T) -> U? { + return pageInfoMap.removeValue(forKey: key) as? U + } + + func clearAll() { + pageInfoMap.removeAll() + } +}