From 83f63c61cce39997944ea164544abadbb63404cc Mon Sep 17 00:00:00 2001 From: Marino Faggiana Date: Mon, 16 Nov 2026 09:42:56 +0100 Subject: [PATCH 1/7] fix: highlight pending folder selections in share extension Signed-off-by: Marino Faggiana --- Share/Model/NCShareViewModel+Folders.swift | 5 +++++ Share/Model/NCShareViewModel.swift | 2 ++ Share/View/NCShareView.swift | 10 +++++++--- 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/Share/Model/NCShareViewModel+Folders.swift b/Share/Model/NCShareViewModel+Folders.swift index 515a6d31b9..b0db54e14a 100644 --- a/Share/Model/NCShareViewModel+Folders.swift +++ b/Share/Model/NCShareViewModel+Folders.swift @@ -24,6 +24,7 @@ extension NCShareViewModel { func resetFolderBrowser(preservingContent: Bool = false) { folderBrowserID = UUID() folderSelectionTask?.cancel() + pendingFolderSelection = nil for task in folderTasks.values { task.cancel() } for request in folderRequests.values { request.cancel() } folderTasks.removeAll() @@ -117,12 +118,16 @@ extension NCShareViewModel { let session = sessionStore.getSession() let browserID = folderBrowserID isLoading = true + if !automatically { + pendingFolderSelection = (folder.serverUrl, fromRecents) + } folderSelectionTask = Task { @MainActor in defer { if isCurrentBrowser(browserID, account: session.account) { if automatically, isAuthenticated, selectedFolder == nil { selectedFolder = rootFolder } + pendingFolderSelection = nil isLoading = false } } diff --git a/Share/Model/NCShareViewModel.swift b/Share/Model/NCShareViewModel.swift index d407b67590..1be2ed3bb4 100644 --- a/Share/Model/NCShareViewModel.swift +++ b/Share/Model/NCShareViewModel.swift @@ -21,6 +21,7 @@ final class NCShareViewModel: NSObject, ObservableObject { @Published var recentFolders: [NCShareFolderItem] = [] @Published var selectedFolder: NCShareFolderItem? @Published var isRecentFolderSelected = false + @Published var pendingFolderSelection: (serverUrl: String, fromRecents: Bool)? @Published var folderScrollTarget: String? @Published var folderChildren: [String: [NCShareFolderItem]] = [:] @Published var expandedFolderURLs: Set = [] @@ -335,6 +336,7 @@ final class NCShareViewModel: NSObject, ObservableObject { func cancel(with error: NCShareRequestError? = nil) { guard !isClosing else { return } isClosing = true + pendingFolderSelection = nil alertDismissAction = nil stopRequestWork() thumbnailRequests.removeAll() diff --git a/Share/View/NCShareView.swift b/Share/View/NCShareView.swift index 6ceb3955e4..3d1897387c 100644 --- a/Share/View/NCShareView.swift +++ b/Share/View/NCShareView.swift @@ -231,7 +231,11 @@ struct NCShareView: View { } private func folderRow(_ folder: NCShareFolderItem, depth: Int?) -> some View { - let isSelected = model.selectedFolder?.serverUrl == folder.serverUrl && model.isRecentFolderSelected == (depth == nil) + let fromRecents = depth == nil + let isSelected = model.selectedFolder?.serverUrl == folder.serverUrl && model.isRecentFolderSelected == fromRecents + let isPending = model.pendingFolderSelection?.serverUrl == folder.serverUrl && + model.pendingFolderSelection?.fromRecents == fromRecents + let highlightOpacity: Double = isSelected ? 0.1 : (isPending ? 0.05 : 0) return HStack(spacing: 4) { if let depth { Button { @@ -253,7 +257,7 @@ struct NCShareView: View { .accessibilityHidden(true) } Button { - model.selectFolder(folder, fromRecents: depth == nil) + model.selectFolder(folder, fromRecents: fromRecents) } label: { HStack(spacing: 8) { if let image = folder.image { @@ -310,7 +314,7 @@ struct NCShareView: View { .disabled(!model.canUseFolderBrowser) .background { RoundedRectangle(cornerRadius: 8) - .fill(Color.accentColor.opacity(isSelected ? 0.1 : 0)) + .fill(Color.accentColor.opacity(highlightOpacity)) .padding(.horizontal, 5) } .listRowSeparator(.hidden) From adcba93d15343b22a86ba9a3d3a7effa2406686d Mon Sep 17 00:00:00 2001 From: Marino Faggiana Date: Mon, 16 Nov 2026 11:18:56 +0100 Subject: [PATCH 2/7] feat: refresh recent files widget and improve file opening Adapt file rows to widget size, add manual refresh and update timestamps, and simplify the layout. Handle widget file links across app launch and passcode unlock with validated account matching. Signed-off-by: Marino Faggiana --- Widget/Files/FilesData.swift | 88 ++--- Widget/Files/FilesWidgetProvider.swift | 40 ++- Widget/Files/FilesWidgetView.swift | 309 ++++++++---------- Widget/Widget.swift | 4 +- iOSClient/SceneDelegate.swift | 168 ++++++---- .../en.lproj/Localizable.strings | 6 +- 6 files changed, 324 insertions(+), 291 deletions(-) diff --git a/Widget/Files/FilesData.swift b/Widget/Files/FilesData.swift index 654b22d22f..fdcf4d26f5 100644 --- a/Widget/Files/FilesData.swift +++ b/Widget/Files/FilesData.swift @@ -12,10 +12,7 @@ struct FilesDataEntry: TimelineEntry { let datas: [FilesData] let isPlaceholder: Bool let isEmpty: Bool - let userId: String - let url: String - let account: String - let tile: String + let allowsRefresh: Bool let footerImage: String let footerText: String } @@ -25,61 +22,37 @@ struct FilesData: Identifiable, Hashable { var image: UIImage var title: String var subTitle: String - var url: URL + var url: URL? var useTypeIconFile: Bool = false } -let filesDatasTest: [FilesData] = [ - .init(id: "0", image: UIImage(systemName: "circle.fill")!, title: "title1", subTitle: "subTitle-description1", url: URL(string: "https://nextcloud.com/")!), - .init(id: "1", image: UIImage(systemName: "circle.fill")!, title: "title2", subTitle: "subTitle-description2", url: URL(string: "https://nextcloud.com/")!), - .init(id: "2", image: UIImage(systemName: "circle.fill")!, title: "title3", subTitle: "subTitle-description3", url: URL(string: "https://nextcloud.com/")!), - .init(id: "3", image: UIImage(systemName: "circle.fill")!, title: "title4", subTitle: "subTitle-description4", url: URL(string: "https://nextcloud.com/")!), - .init(id: "4", image: UIImage(systemName: "circle.fill")!, title: "title4", subTitle: "subTitle-description4", url: URL(string: "https://nextcloud.com/")!), - .init(id: "5", image: UIImage(systemName: "circle.fill")!, title: "title4", subTitle: "subTitle-description4", url: URL(string: "https://nextcloud.com/")!), - .init(id: "6", image: UIImage(systemName: "circle.fill")!, title: "title4", subTitle: "subTitle-description4", url: URL(string: "https://nextcloud.com/")!), - .init(id: "7", image: UIImage(systemName: "circle.fill")!, title: "title4", subTitle: "subTitle-description4", url: URL(string: "https://nextcloud.com/")!), - .init(id: "8", image: UIImage(systemName: "circle.fill")!, title: "title4", subTitle: "subTitle-description4", url: URL(string: "https://nextcloud.com/")!), - .init(id: "9", image: UIImage(systemName: "circle.fill")!, title: "title4", subTitle: "subTitle-description4", url: URL(string: "https://nextcloud.com/")!) -] - -func getTitleFilesWidget(tableAccount: tableAccount?) -> String { - let hour = Calendar.current.component(.hour, from: Date()) - var good = "" - - switch hour { - case 6..<12: good = NSLocalizedString("_good_morning_", value: "Good morning", comment: "") - case 12: good = NSLocalizedString("_good_day_", value: "Good day", comment: "") - case 13..<17: good = NSLocalizedString("_good_afternoon_", value: "Good afternoon", comment: "") - case 17..<22: good = NSLocalizedString("_good_evening_", value: "Good evening", comment: "") - default: good = NSLocalizedString("_good_night_", value: "Good night", comment: "") - } - - if let tableAccount { - return good + ", " + tableAccount.displayName - } else { - return good +func filesWidgetSampleRows(count: Int) -> [FilesData] { + let image = UIImage(systemName: "doc") ?? UIImage() + return (0.. FilesDataEntry { +func getFilesDataEntry(configuration: AccountIntent, displaySize: CGSize) async -> FilesDataEntry { let utilityFileSystem = NCUtilityFileSystem() let utility = NCUtility() - let maxItems = 5 - let datasPlaceholder = Array(filesDatasTest[0...maxItems - 1]) + let maxItems = FilesWidgetLayout.rowCount(for: displaySize.height) + let datasPlaceholder = filesWidgetSampleRows(count: maxItems) var activeTableAccount: tableAccount? let versionApp = NCUtility().getVersionMaintenance() if let groupDefaults = UserDefaults(suiteName: NCBrandOptions.shared.capabilitiesGroup), let lastVersion = groupDefaults.string(forKey: NCGlobal.shared.udLastVersion), lastVersion != versionApp { - return (FilesDataEntry(date: Date(), datas: datasPlaceholder, isPlaceholder: true, isEmpty: false, userId: "", url: "", account: "", tile: getTitleFilesWidget(tableAccount: nil), footerImage: "checkmark.icloud", footerText: NSLocalizedString("_version_mismatch_error_", comment: ""))) + return (FilesDataEntry(date: Date(), datas: datasPlaceholder, isPlaceholder: true, isEmpty: false, allowsRefresh: true, footerImage: "checkmark.icloud", footerText: NSLocalizedString("_version_mismatch_error_", comment: ""))) } - if isPreview { - return (FilesDataEntry(date: Date(), datas: datasPlaceholder, isPlaceholder: true, isEmpty: false, userId: "", url: "", account: "", tile: getTitleFilesWidget(tableAccount: nil), footerImage: "checkmark.icloud", footerText: NCBrandOptions.shared.brand + " files")) - } - - let accountIdentifier: String = configuration?.accounts?.identifier ?? "active" + let accountIdentifier: String = configuration.accounts?.identifier ?? "active" if accountIdentifier == "active" { activeTableAccount = NCManageDatabase.shared.getActiveTableAccount() } else { @@ -87,7 +60,7 @@ func getFilesDataEntry(configuration: AccountIntent?, isPreview: Bool, displaySi } guard let activeTableAccount else { - return (FilesDataEntry(date: Date(), datas: datasPlaceholder, isPlaceholder: true, isEmpty: false, userId: "", url: "", account: "", tile: getTitleFilesWidget(tableAccount: nil), footerImage: "xmark.icloud", footerText: NSLocalizedString("_no_active_account_", value: "No account found", comment: ""))) + return (FilesDataEntry(date: Date(), datas: datasPlaceholder, isPlaceholder: true, isEmpty: false, allowsRefresh: true, footerImage: "xmark.icloud", footerText: NSLocalizedString("_no_active_account_", value: "No account found", comment: ""))) } NextcloudKit.shared.setup(groupIdentifier: NCBrandOptions.shared.capabilitiesGroup, delegate: NCNetworking.shared) @@ -174,10 +147,11 @@ func getFilesDataEntry(configuration: AccountIntent?, isPreview: Bool, displaySi let results = await NextcloudKit.shared.searchBodyRequestAsync(serverUrl: activeTableAccount.urlBase, requestBody: requestBody, showHiddenFiles: showHiddenFiles, account: activeTableAccount.account, options: options) var datas: [FilesData] = [] - let title = getTitleFilesWidget(tableAccount: activeTableAccount) let files = results.files?.sorted(by: { ($0.date as Date) > ($1.date as Date) }) ?? [] for file in files { + guard datas.count < maxItems else { break } + var useTypeIconFile = false var image: UIImage? @@ -188,12 +162,15 @@ func getFilesDataEntry(configuration: AccountIntent?, isPreview: Bool, displaySi // SUBTITLE let subTitle = utility.getRelativeDateTitle(file.date as Date) + " ยท " + utilityFileSystem.transformedSize(file.size) - // URL: nextcloud://open-file?path=Talk/IMG_0000123.jpg&user=marinofaggiana&link=https://cloud.nextcloud.com/f/123 - guard var path = utilityFileSystem.getPath(path: file.path, user: file.user, fileName: file.fileName).urlEncoded else { continue } - if path.first == "/" { path = String(path.dropFirst())} - let link = file.urlBase + "/f/" + file.fileId - let urlString = "nextcloud://open-file?path=\(path)&user=\(file.userId)&link=\(link)&account=\(file.account)" - guard let url = URL(string: urlString) else { continue } + var components = URLComponents() + components.scheme = NCGlobal.shared.appScheme + components.host = "open-file" + components.queryItems = [ + URLQueryItem(name: "user", value: file.userId), + URLQueryItem(name: "link", value: file.urlBase + "/f/" + file.fileId), + URLQueryItem(name: "account", value: file.account) + ] + guard let url = components.url else { continue } // IMAGE image = utility.getImage(ocId: file.ocId, @@ -229,17 +206,14 @@ func getFilesDataEntry(configuration: AccountIntent?, isPreview: Bool, displaySi // DATA let data = FilesData(id: metadata.ocId, image: image ?? UIImage(), title: metadata.fileNameView, subTitle: subTitle, url: url, useTypeIconFile: useTypeIconFile) datas.append(data) - if datas.count == maxItems { - break - } } let alias = (activeTableAccount.alias.isEmpty) ? "" : (" (" + activeTableAccount.alias + ")") - let footerText = "Files " + NSLocalizedString("_of_", comment: "") + " " + activeTableAccount.displayName + alias + let footerText = activeTableAccount.displayName + alias if results.error != .success { - return(FilesDataEntry(date: Date(), datas: datasPlaceholder, isPlaceholder: true, isEmpty: false, userId: activeTableAccount.userId, url: activeTableAccount.urlBase, account: activeTableAccount.account, tile: title, footerImage: "xmark.icloud", footerText: results.error.localizedGenericMessage)) + return(FilesDataEntry(date: Date(), datas: datasPlaceholder, isPlaceholder: true, isEmpty: false, allowsRefresh: true, footerImage: "xmark.icloud", footerText: results.error.localizedGenericMessage)) } else { - return(FilesDataEntry(date: Date(), datas: datas, isPlaceholder: false, isEmpty: datas.isEmpty, userId: activeTableAccount.userId, url: activeTableAccount.urlBase, account: activeTableAccount.account, tile: title, footerImage: "checkmark.icloud", footerText: footerText)) + return(FilesDataEntry(date: Date(), datas: datas, isPlaceholder: false, isEmpty: datas.isEmpty, allowsRefresh: true, footerImage: "checkmark.icloud", footerText: footerText)) } } diff --git a/Widget/Files/FilesWidgetProvider.swift b/Widget/Files/FilesWidgetProvider.swift index 4ccce19047..ad8a5ea0e1 100644 --- a/Widget/Files/FilesWidgetProvider.swift +++ b/Widget/Files/FilesWidgetProvider.swift @@ -2,33 +2,55 @@ // SPDX-FileCopyrightText: 2022 Marino Faggiana // SPDX-License-Identifier: GPL-3.0-or-later -import UIKit +import AppIntents import WidgetKit import Intents -import SwiftUI struct FilesWidgetProvider: IntentTimelineProvider { typealias Entry = FilesDataEntry typealias Intent = AccountIntent func placeholder(in context: Context) -> Entry { - let datasPlaceholder = Array(filesDatasTest[0...4]) - let title = getTitleFilesWidget(tableAccount: nil) - return Entry(date: Date(), datas: datasPlaceholder, isPlaceholder: true, isEmpty: false, userId: "", url: "", account: "", tile: title, footerImage: "checkmark.icloud", footerText: NCBrandOptions.shared.brand + " files") + Entry(date: Date(), + datas: filesWidgetSampleRows(count: FilesWidgetLayout.rowCount(for: context.displaySize.height)), + isPlaceholder: true, + isEmpty: false, + allowsRefresh: false, + footerImage: "checkmark.icloud", + footerText: NCBrandOptions.shared.brand) } func getSnapshot(for configuration: AccountIntent, in context: Context, completion: @escaping (Entry) -> Void) { + guard !context.isPreview else { + completion(placeholder(in: context)) + return + } + Task { - let entry = await getFilesDataEntry(configuration: configuration, isPreview: false, displaySize: context.displaySize) + let entry = await getFilesDataEntry(configuration: configuration, displaySize: context.displaySize) completion(entry) } } func getTimeline(for configuration: AccountIntent, in context: Context, completion: @escaping (Timeline) -> Void) { + guard !context.isPreview else { + completion(Timeline(entries: [placeholder(in: context)], policy: .never)) + return + } + Task { - let entry = await getFilesDataEntry(configuration: configuration, isPreview: context.isPreview, displaySize: context.displaySize) - let timeLine = Timeline(entries: [entry], policy: .atEnd) - completion(timeLine) + let entry = await getFilesDataEntry(configuration: configuration, displaySize: context.displaySize) + completion(Timeline(entries: [entry], policy: .atEnd)) } } } + +struct RefreshFilesWidgetIntent: AppIntent { + static let title: LocalizedStringResource = "Refresh recent files" + static let openAppWhenRun = false + + func perform() async throws -> some IntentResult { + // WidgetKit reloads this widget's timeline after its button intent completes. + return .result() + } +} diff --git a/Widget/Files/FilesWidgetView.swift b/Widget/Files/FilesWidgetView.swift index a595b4d681..97afb68c38 100644 --- a/Widget/Files/FilesWidgetView.swift +++ b/Widget/Files/FilesWidgetView.swift @@ -2,176 +2,152 @@ // SPDX-FileCopyrightText: 2022 Marino Faggiana // SPDX-License-Identifier: GPL-3.0-or-later +import AppIntents import SwiftUI import WidgetKit +nonisolated enum FilesWidgetLayout { + static let padding: CGFloat = 12 + static let sectionSpacing: CGFloat = 4 + static let headerHeight: CGFloat = 22 + static let footerHeight: CGFloat = 44 + static let rowHeight: CGFloat = 44 + static let thumbnailSize: CGFloat = 32 + static let rowSpacing: CGFloat = 10 + + static func rowCount(for height: CGFloat) -> Int { + guard height.isFinite else { return 0 } + let reservedHeight = 2 * padding + 2 * sectionSpacing + headerHeight + footerHeight + // The WebDAV search returns at most 50 results. + let rows = (height - reservedHeight) / rowHeight + return Int(min(50, max(0, rows))) + } +} + struct FilesWidgetView: View { - var entry: FilesDataEntry + let entry: FilesDataEntry + var body: some View { - let parameterLink = "&user=\(entry.userId)&url=\(entry.url)" - let linkNoAction: URL = URL(string: NCGlobal.shared.widgetActionNoAction + parameterLink) != nil ? URL(string: NCGlobal.shared.widgetActionNoAction + parameterLink)! : URL(string: NCGlobal.shared.widgetActionNoAction)! - let linkActionUploadAsset: URL = URL(string: NCGlobal.shared.widgetActionUploadAsset + parameterLink) != nil ? URL(string: NCGlobal.shared.widgetActionUploadAsset + parameterLink)! : URL(string: NCGlobal.shared.widgetActionUploadAsset)! - let linkActionScanDocument: URL = URL(string: NCGlobal.shared.widgetActionScanDocument + parameterLink) != nil ? URL(string: NCGlobal.shared.widgetActionScanDocument + parameterLink)! : URL(string: NCGlobal.shared.widgetActionScanDocument)! - let linkActionTextDocument: URL = URL(string: NCGlobal.shared.widgetActionTextDocument + parameterLink) != nil ? URL(string: NCGlobal.shared.widgetActionTextDocument + parameterLink)! : URL(string: NCGlobal.shared.widgetActionTextDocument)! - let linkActionVoiceMemo: URL = URL(string: NCGlobal.shared.widgetActionVoiceMemo + parameterLink) != nil ? URL(string: NCGlobal.shared.widgetActionVoiceMemo + parameterLink)! : URL(string: NCGlobal.shared.widgetActionVoiceMemo)! - - GeometryReader { geo in - if entry.isEmpty { - VStack(alignment: .center) { - Image(systemName: "checkmark") - .resizable() - .scaledToFit() - .font(Font.system(.body).weight(.light)) - .frame(width: 50, height: 50) - Text(NSLocalizedString("_no_items_", comment: "")) - .font(.system(size: 25)) - .padding() - Text(NSLocalizedString("_check_back_later_", comment: "")) - .font(.system(size: 15)) - } - .frame(width: geo.size.width, height: geo.size.height) - } + GeometryReader { geometry in + let files = entry.datas.prefix(FilesWidgetLayout.rowCount(for: geometry.size.height)) - ZStack(alignment: .topLeading) { - HStack { - Text(entry.tile) - .font(.system(size: 12)) - .fontWeight(.bold) - .multilineTextAlignment(.center) - .textCase(.uppercase) - .lineLimit(1) - } - .frame(width: geo.size.width - 20) - .padding([.top, .leading, .trailing], 10) - - if !entry.isEmpty { - VStack(alignment: .leading) { - VStack(spacing: 0) { - ForEach(entry.datas, id: \.id) { element in - Link(destination: element.url) { - HStack(spacing: 10) { - Group { - if element.useTypeIconFile { - Image(uiImage: element.image) - .resizable() - .renderingMode(.template) - .foregroundColor(Color(NCBrandColor.shared.iconImageColor2)) - .scaledToFit() - .frame(width: 35, height: 35) - } else { - Image(uiImage: element.image) - .resizable() - .frame(width: 35, height: 35) - .background(Color(.secondarySystemBackground)) - .clipShape(RoundedRectangle(cornerRadius: 5, style: .continuous)) - } - } - - VStack(alignment: .leading, spacing: 2) { - FilesWidgetBidiFilename(filename: element.title) - .lineLimit(1) - Text(element.subTitle) - .font(.system(size: 10)) - .foregroundColor(Color(NCBrandColor.shared.iconImageColor2)) - .lineLimit(1) - .truncationMode(.tail) - } - Spacer(minLength: 0) + VStack(alignment: .leading, spacing: FilesWidgetLayout.sectionSpacing) { + Text(NSLocalizedString("_widget_recent_files_", value: "Recent files", comment: "")) + .font(.system(size: 16, weight: .semibold)) + .lineLimit(1) + .frame(height: FilesWidgetLayout.headerHeight) + .accessibilityAddTraits(.isHeader) + + if entry.isEmpty { + Label { + Text(NSLocalizedString("_widget_no_recent_files_", value: "No recent files", comment: "")) + } icon: { + Image(systemName: "clock") + } + .font(.subheadline) + .foregroundStyle(.secondary) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else { + VStack(spacing: 0) { + ForEach(files) { file in + fileRow(file) + .overlay(alignment: .bottomLeading) { + if file.id != files.last?.id { + Divider() + .padding(.leading, FilesWidgetLayout.thumbnailSize + FilesWidgetLayout.rowSpacing) } - .padding(.horizontal, 10) - .frame(height: 44) } - if element != entry.datas.last { - Divider() - .padding(.leading, 52) - } - } } } - .padding(.top, 30) .redacted(reason: entry.isPlaceholder ? .placeholder : []) + .frame(maxHeight: .infinity, alignment: .top) } - HStack(spacing: 10) { - let buttonSize: CGFloat = 40 - - Link(destination: entry.isPlaceholder ? linkNoAction : linkActionUploadAsset) { - Image(systemName: "photo.badge.plus") - .resizable() - .renderingMode(.template) - .scaledToFit() - .foregroundColor(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getText(account: entry.account))) - .frame(width: 18, height: 18) - .padding(11) - .background(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getElement(account: entry.account))) - .clipShape(Circle()) - .frame(width: buttonSize, height: buttonSize) - } - .frame(maxWidth: .infinity) - - Link(destination: entry.isPlaceholder ? linkNoAction : linkActionScanDocument) { - Image(systemName: "doc.text.viewfinder") - .resizable() - .renderingMode(.template) - .scaledToFit() - .foregroundColor(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getText(account: entry.account))) - .frame(width: 18, height: 18) - .padding(11) - .background(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getElement(account: entry.account))) - .clipShape(Circle()) - .frame(width: buttonSize, height: buttonSize) - } - .frame(maxWidth: .infinity) - - Link(destination: entry.isPlaceholder ? linkNoAction : linkActionTextDocument) { - Image("note.text") - .resizable() - .renderingMode(.template) - .scaledToFit() - .foregroundColor(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getText(account: entry.account))) - .frame(width: 18, height: 18) - .padding(11) - .background(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getElement(account: entry.account))) - .clipShape(Circle()) - .frame(width: buttonSize, height: buttonSize) - } - .frame(maxWidth: .infinity) - - Link(destination: entry.isPlaceholder ? linkNoAction : linkActionVoiceMemo) { - Image(systemName: "mic.fill") - .resizable() - .renderingMode(.template) - .scaledToFit() - .foregroundColor(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getText(account: entry.account))) - .frame(width: 18, height: 18) - .padding(11) - .background(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getElement(account: entry.account))) - .clipShape(Circle()) - .frame(width: buttonSize, height: buttonSize) - } - .frame(maxWidth: .infinity) + footer + } + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) + .padding(FilesWidgetLayout.padding) + } + .containerBackground(.background, for: .widget) + } + + private var footer: some View { + HStack(spacing: 8) { + if entry.allowsRefresh { + Button(intent: RefreshFilesWidgetIntent()) { + Image(systemName: "arrow.clockwise") + .font(.system(size: 19, weight: .semibold)) + .foregroundStyle(.tint) + .frame(width: FilesWidgetLayout.footerHeight, height: FilesWidgetLayout.footerHeight) + .contentShape(Rectangle()) } - .padding(.horizontal, 10) - .frame(maxWidth: .infinity, maxHeight: geo.size.height - 25, alignment: .bottom) - .redacted(reason: entry.isPlaceholder ? .placeholder : []) - - HStack { - Image(systemName: entry.footerImage) - .resizable() - .scaledToFit() - .frame(width: 15, height: 15) - .font(Font.system(.body).weight(.light)) - .foregroundColor(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getElement(account: entry.account))) - - Text(entry.footerText) - .font(.caption2) - .lineLimit(1) - .foregroundColor(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getElement(account: entry.account))) + .buttonStyle(.plain) + .accessibilityLabel(Text(NSLocalizedString("_widget_refresh_files_", value: "Refresh recent files", comment: ""))) + } + + VStack(alignment: .leading, spacing: 2) { + Label(entry.footerText, systemImage: entry.footerImage) + .truncationMode(.middle) + + if !entry.isPlaceholder { + let updated = entry.date.formatted(.dateTime.day().month(.abbreviated).hour().minute()) + Text(String.localizedStringWithFormat( + NSLocalizedString("_widget_files_updated_at_", value: "Updated %@", comment: ""), + updated + )) + .invalidatableContent() } - .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottom) } + .font(.system(size: 11)) + .foregroundStyle(.secondary) + .lineLimit(1) } - .containerBackground(.background, for: .widget) + .frame(maxWidth: .infinity, alignment: .leading) + .frame(height: FilesWidgetLayout.footerHeight) + } + + @ViewBuilder + private func fileRow(_ file: FilesData) -> some View { + if let url = file.url { + Link(destination: url) { + rowContent(file) + } + } else { + rowContent(file) + } + } + + private func rowContent(_ file: FilesData) -> some View { + HStack(spacing: FilesWidgetLayout.rowSpacing) { + thumbnail(file) + .accessibilityHidden(true) + + VStack(alignment: .leading, spacing: 2) { + FilesWidgetBidiFilename(filename: file.title) + .font(.system(size: 13, weight: .medium)) + .foregroundStyle(.primary) + .lineLimit(1) + + Text(file.subTitle) + .font(.system(size: 11)) + .foregroundStyle(.secondary) + .lineLimit(1) + } + } + .frame(maxWidth: .infinity, alignment: .leading) + .frame(height: FilesWidgetLayout.rowHeight) + .contentShape(Rectangle()) + .accessibilityElement(children: .combine) + } + + private func thumbnail(_ file: FilesData) -> some View { + Image(uiImage: file.image) + .renderingMode(file.useTypeIconFile ? .template : .original) + .resizable() + .aspectRatio(contentMode: file.useTypeIconFile ? .fit : .fill) + .foregroundStyle(.secondary) + .frame(width: FilesWidgetLayout.thumbnailSize, height: FilesWidgetLayout.thumbnailSize) + .clipShape(RoundedRectangle(cornerRadius: 6)) } } @@ -179,32 +155,37 @@ private struct FilesWidgetBidiFilename: View { let filename: String var body: some View { - let nsName = filename as NSString - let ext = nsName.pathExtension - let base = nsName.deletingPathExtension + let name = filename as NSString + let ext = name.pathExtension + let base = name.deletingPathExtension if ext.isEmpty || base.isEmpty { Text(filename) - .font(.system(size: 12)) + .truncationMode(.middle) } else { HStack(spacing: 0) { Text(base) - .font(.system(size: 12)) - .lineLimit(1) .truncationMode(.middle) Text("." + ext) - .font(.system(size: 12)) - .lineLimit(1) .fixedSize(horizontal: true, vertical: false) } + .accessibilityLabel(Text(filename)) } } } struct FilesWidget_Previews: PreviewProvider { static var previews: some View { - let datas = Array(filesDatasTest[0...4]) - let entry = FilesDataEntry(date: Date(), datas: datas, isPlaceholder: false, isEmpty: false, userId: "", url: "", account: "", tile: "Good afternoon, Marino Faggiana", footerImage: "checkmark.icloud", footerText: "Nextcloud files") - FilesWidgetView(entry: entry).previewContext(WidgetPreviewContext(family: .systemLarge)) + let entry = FilesDataEntry( + date: Date(), + datas: filesWidgetSampleRows(count: 8), + isPlaceholder: false, + isEmpty: false, + allowsRefresh: true, + footerImage: "checkmark.icloud", + footerText: "Nextcloud (Personal)" + ) + FilesWidgetView(entry: entry) + .previewContext(WidgetPreviewContext(family: .systemLarge)) } } diff --git a/Widget/Widget.swift b/Widget/Widget.swift index 469b8339d3..726508be02 100644 --- a/Widget/Widget.swift +++ b/Widget/Widget.swift @@ -42,10 +42,8 @@ struct FilesWidget: Widget { } .supportedFamilies([.systemLarge]) .configurationDisplayName("Files") - .description(NSLocalizedString("_description_fileswidget_", comment: "")) -#if !targetEnvironment(simulator) + .description(NSLocalizedString("_widget_recent_files_description_", value: "View and open your recent files.", comment: "")) .contentMarginsDisabled() -#endif } } diff --git a/iOSClient/SceneDelegate.swift b/iOSClient/SceneDelegate.swift index ca659ef31f..42e8edc394 100644 --- a/iOSClient/SceneDelegate.swift +++ b/iOSClient/SceneDelegate.swift @@ -16,6 +16,8 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { private let appDelegate = UIApplication.shared.delegate as? AppDelegate private var privacyProtectionWindow: UIWindow? private var passcodeWindow: NCPasscodeWindow? + private var pendingWidgetFileURL: URL? + private var widgetFileOpenTask: Task? private let global = NCGlobal.shared private let alreadyMigratedMultiDomains = UserDefaults.standard.bool(forKey: NCGlobal.shared.udMigrationMultiDomains) @@ -23,6 +25,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { guard let windowScene = (scene as? UIWindowScene) else { return } + pendingWidgetFileURL = connectionOptions.urlContexts.map(\.url).first(where: isWidgetFileURL) NotificationCenter.default.removeObserver(self, name: NCPasscodeModel.lockoutNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(passcodeLockoutStarted), name: NCPasscodeModel.lockoutNotification, object: nil) @@ -195,6 +198,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { if activateSceneForAccount { self.activateSceneForAccount(scene, account: activeTblAccount.account, controller: controller) } + openPendingWidgetFile(in: scene) } // Clean orphaned FP Domains @@ -206,6 +210,9 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { func sceneDidDisconnect(_ scene: UIScene) { guard let windowScene = scene as? UIWindowScene else { return } + widgetFileOpenTask?.cancel() + pendingWidgetFileURL = nil + passcodeWindow?.hide() passcodeWindow = nil hidePrivacyProtectionWindow() @@ -227,6 +234,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { func sceneDidBecomeActive(_ scene: UIScene) { hidePrivacyProtectionWindow() + openPendingWidgetFile(in: scene) if !NextcloudKit.shared.isNetworkReachable(), let windowScenee = SceneManager.shared.getWindow(scene: scene)?.windowScene { @@ -314,8 +322,16 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { } func scene(_ scene: UIScene, openURLContexts URLContexts: Set) { - guard let controller = SceneManager.shared.getController(scene: scene), - let url = URLContexts.first?.url else { return } + guard let url = URLContexts.first?.url else { return } + + if isWidgetFileURL(url) { + widgetFileOpenTask?.cancel() + pendingWidgetFileURL = url + openPendingWidgetFile(in: scene) + return + } + + guard let controller = SceneManager.shared.getController(scene: scene) else { return } let scheme = url.scheme let action = url.host let versionApp = NCUtility().getVersionMaintenance() @@ -327,13 +343,13 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { return } - func getMatchedAccount(user: String, url: String, account: String? = nil) async -> tableAccount? { + func getMatchedAccount(user: String, url: String) async -> tableAccount? { let tblAccounts = await NCManageDatabase.shared.getAllTableAccountAsync() for tblAccount in tblAccounts { let host = URL(string: tblAccount.urlBase)?.host() ?? "" - if (account == tblAccount.account) || (url.contains(host) && user == tblAccount.userId) { + if url.contains(host), user == tblAccount.userId { await NCAccount().changeAccount(tblAccount.account, userProfile: nil, controller: controller) // wait switch account try? await Task.sleep(for: .seconds(1)) @@ -442,57 +458,6 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { } } } - } - - /* - Example: nextcloud://open-file?path=Talk/IMG_0000123.jpg&user=marinofaggiana&link=https://cloud.nextcloud.com/f/123 - */ - - else if scheme == self.global.appScheme && action == "open-file" { - if let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) { - let queryItems = urlComponents.queryItems - guard let userScheme = queryItems?.filter({ $0.name == "user" }).first?.value, - // let pathScheme = queryItems?.filter({ $0.name == "path" }).first?.value, - let linkScheme = queryItems?.filter({ $0.name == "link" }).first?.value else { - return - } - let domain = URL(string: linkScheme)?.host ?? "" - let accountScheme = queryItems?.filter({ $0.name == "account" }).first?.value - - Task { - guard let tblAccount = await getMatchedAccount(user: userScheme, url: linkScheme, account: accountScheme) else { - - let message = String(format: NSLocalizedString("_account_not_available_", comment: ""), userScheme, domain) - let alertController = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: message, preferredStyle: .alert) - alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in })) - - controller.present(alertController, animated: true) - return - } - - let results = await NextcloudKit.shared.getFileFromFileIdAsync(link: linkScheme, - account: tblAccount.account) - if results.error == .success, let file = results.file { - let metadata = await NCManageDatabaseCreateMetadata().convertFileToMetadataAsync(file) - await NCManageDatabase.shared.addMetadataAsync(metadata) - if metadata.hasPreview { - let results = await NextcloudKit.shared.downloadPreviewAsync(fileId: metadata.fileId, etag: metadata.etag, account: metadata.account) - if results.error == .success, - let data = results.responseData?.data { - NCUtility().createImageFileFrom(data: data, metadata: metadata) - } - } - await NCNetworking.shared.openFileView(serverUrl: metadata.serverUrl, - metadata: metadata, - sceneIdentifier: controller.sceneIdentifier) - } - } - } - - /* - Example: nextcloud://open-and-switch-account?user=marinofaggiana&url=https://cloud.nextcloud.com - */ - } else if scheme == self.global.appScheme && action == "open-and-switch-account" { guard let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return @@ -515,6 +480,89 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { } } + private func isWidgetFileURL(_ url: URL) -> Bool { + url.scheme == global.appScheme && url.host == "open-file" + } + + private func openPendingWidgetFile(in scene: UIScene) { + guard let url = pendingWidgetFileURL, + passcodeWindow == nil, + scene.activationState == .foregroundActive, + let controller = window?.rootViewController as? NCMainTabBarController else { return } + + pendingWidgetFileURL = nil + widgetFileOpenTask = Task { @MainActor in + await openWidgetFile(url, scene: scene, controller: controller) + } + } + + private func openWidgetFile(_ url: URL, scene: UIScene, controller: NCMainTabBarController) async { + guard let queryItems = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems, + let user = queryItems.first(where: { $0.name == "user" })?.value, + let link = queryItems.first(where: { $0.name == "link" })?.value, + let fileURL = URL(string: link) else { return } + + let account = queryItems.first(where: { $0.name == "account" })?.value + let fileId = fileURL.lastPathComponent + guard !fileId.isEmpty, fileId.allSatisfy({ $0.isASCII && $0.isNumber }) else { return } + + let accounts = await NCManageDatabase.shared.getAllTableAccountAsync() + guard !Task.isCancelled, window?.rootViewController === controller else { return } + if passcodeWindow != nil || scene.activationState != .foregroundActive { + pendingWidgetFileURL = url + return + } + + guard let target = accounts.first(where: { candidate in + (account == nil || candidate.account == account) + && candidate.userId == user + && URL(string: candidate.urlBase + "/f/" + fileId) == fileURL + }) else { + let message = String(format: NSLocalizedString("_account_not_available_", comment: ""), user, fileURL.host ?? "") + let alert = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: message, preferredStyle: .alert) + alert.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default)) + controller.present(alert, animated: true) + return + } + + if controller.account != target.account { + await NCAccount().changeAccount(target.account, userProfile: nil, controller: controller) + } + guard !Task.isCancelled, controller.account == target.account else { return } + + let result = await NextcloudKit.shared.getFileFromFileIdAsync(fileId: fileId, account: target.account) + guard !Task.isCancelled, window?.rootViewController === controller, + controller.account == target.account else { return } + if passcodeWindow != nil || scene.activationState != .foregroundActive { + pendingWidgetFileURL = url + return + } + + if result.error != .success { + await showErrorBanner(windowScene: scene as? UIWindowScene, error: result.error) + return + } + guard let file = result.file else { + await showErrorBanner(windowScene: scene as? UIWindowScene, text: "_error_not_found_") + return + } + + let metadata = await NCManageDatabaseCreateMetadata().convertFileToMetadataAsync(file) + await NCManageDatabase.shared.addMetadataAsync(metadata) + + guard !Task.isCancelled, window?.rootViewController === controller, + controller.account == target.account else { return } + + if passcodeWindow != nil || scene.activationState != .foregroundActive { + pendingWidgetFileURL = url + return + } + + await NCNetworking.shared.openFileView(serverUrl: metadata.serverUrl, + metadata: metadata, + sceneIdentifier: controller.sceneIdentifier) + } + private func showPrivacyProtectionWindow() { guard privacyProtectionWindow == nil, let windowScene = self.window?.windowScene else { @@ -559,13 +607,17 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { self.passcodeWindow = nil switch result { case .authenticated: - if NCPreferences().accountRequest, + if self.pendingWidgetFileURL != nil, let scene = self.window?.windowScene { + self.openPendingWidgetFile(in: scene) + } else if NCPreferences().accountRequest, let controller, self.window?.rootViewController === controller, NCManageDatabase.shared.getTableAccount(account: controller.account) != nil { self.requestedAccount(controller: controller) } case .reset: + self.widgetFileOpenTask?.cancel() + self.pendingWidgetFileURL = nil self.appDelegate?.resetApplication() case .cancelled, .configured, .disabled: break @@ -590,7 +642,9 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { return } - if !requestPasscodeIfNeeded(controller: controller), NCPreferences().accountRequest { + if !requestPasscodeIfNeeded(controller: controller), + pendingWidgetFileURL == nil, + NCPreferences().accountRequest { requestedAccount(controller: controller) } diff --git a/iOSClient/Supporting Files/en.lproj/Localizable.strings b/iOSClient/Supporting Files/en.lproj/Localizable.strings index 9253621922..eb582eb9ca 100644 --- a/iOSClient/Supporting Files/en.lproj/Localizable.strings +++ b/iOSClient/Supporting Files/en.lproj/Localizable.strings @@ -520,7 +520,11 @@ "_select_color_" = "Select the color"; "_change_color_" = "Change color"; "_description_dashboardwidget_" = "Having the Dashboard always at your fingertips has never been easier."; -"_description_fileswidget_" = "View your recent files and use the toolbar to speed up your operations."; +"_widget_recent_files_" = "Recent files"; +"_widget_no_recent_files_" = "No recent files"; +"_widget_recent_files_description_" = "View and open your recent files."; +"_widget_refresh_files_" = "Refresh recent files"; +"_widget_files_updated_at_" = "Updated %@"; "_description_toolbarwidget_" = "A toolbar to speed up your operations."; "_title_lockscreenwidget_" = "Status"; "_description_lockscreenwidget_" = "Keep an eye on available space and recent activity"; From 595377c8afde6b294fe6e203a416440640d11f4c Mon Sep 17 00:00:00 2001 From: Marino Faggiana Date: Mon, 16 Nov 2026 11:52:39 +0100 Subject: [PATCH 3/7] feat: refresh dashboard widgets and remove toolbar widget Support dashboard item API versions, updated layouts and refresh actions. Handle widget links after unlocking, including account-aware favorites navigation. Signed-off-by: Marino Faggiana --- Brand/Database.swift | 2 +- Nextcloud.xcodeproj/project.pbxproj | 20 - Widget/Dashboard/DashboardData.swift | 414 +++++++++++------- .../Dashboard/DashboardWidgetProvider.swift | 41 +- Widget/Dashboard/DashboardWidgetView.swift | 352 +++++++++------ Widget/Files/FilesWidgetView.swift | 2 +- Widget/Lockscreen/LockscreenData.swift | 97 ++-- .../Lockscreen/LockscreenWidgetProvider.swift | 4 +- Widget/Lockscreen/LockscreenWidgetView.swift | 4 +- Widget/Toolbar/ToolbarData.swift | 46 -- Widget/Toolbar/ToolbarWidgetProvider.swift | 28 -- Widget/Toolbar/ToolbarWidgetView.swift | 109 ----- Widget/Widget.swift | 19 - .../NCManageDatabase+DashboardWidget.swift | 12 +- iOSClient/NCGlobal.swift | 8 - iOSClient/Networking/NCService.swift | 40 +- iOSClient/SceneDelegate.swift | 105 +++-- .../en.lproj/Localizable.strings | 6 +- 18 files changed, 708 insertions(+), 601 deletions(-) delete mode 100644 Widget/Toolbar/ToolbarData.swift delete mode 100644 Widget/Toolbar/ToolbarWidgetProvider.swift delete mode 100644 Widget/Toolbar/ToolbarWidgetView.swift diff --git a/Brand/Database.swift b/Brand/Database.swift index 1ffb5a9bf2..019fbc8762 100644 --- a/Brand/Database.swift +++ b/Brand/Database.swift @@ -8,4 +8,4 @@ import Foundation // let databaseName = "nextcloud.realm" let tableAccountBackup = "tableAccountBackup.json" -let databaseSchemaVersion: UInt64 = 424 +let databaseSchemaVersion: UInt64 = 425 diff --git a/Nextcloud.xcodeproj/project.pbxproj b/Nextcloud.xcodeproj/project.pbxproj index 77b9b47e1f..242fca58e1 100644 --- a/Nextcloud.xcodeproj/project.pbxproj +++ b/Nextcloud.xcodeproj/project.pbxproj @@ -733,9 +733,6 @@ F77E8C232E79717D00EAE68F /* NCManageDatabase+LivePhoto.swift in Sources */ = {isa = PBXBuildFile; fileRef = F77E8C1E2E79717D00EAE68F /* NCManageDatabase+LivePhoto.swift */; }; F77E8C242E79717D00EAE68F /* NCManageDatabase+LivePhoto.swift in Sources */ = {isa = PBXBuildFile; fileRef = F77E8C1E2E79717D00EAE68F /* NCManageDatabase+LivePhoto.swift */; }; F77E8C252E79717D00EAE68F /* NCManageDatabase+LivePhoto.swift in Sources */ = {isa = PBXBuildFile; fileRef = F77E8C1E2E79717D00EAE68F /* NCManageDatabase+LivePhoto.swift */; }; - F77ED59128C9CE9D00E24ED0 /* ToolbarData.swift in Sources */ = {isa = PBXBuildFile; fileRef = F77ED59028C9CE9D00E24ED0 /* ToolbarData.swift */; }; - F77ED59328C9CEA000E24ED0 /* ToolbarWidgetProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = F77ED59228C9CEA000E24ED0 /* ToolbarWidgetProvider.swift */; }; - F77ED59528C9CEA400E24ED0 /* ToolbarWidgetView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F77ED59428C9CEA300E24ED0 /* ToolbarWidgetView.swift */; }; F78026102E9CFA3700B63436 /* NCTransfersView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F780260F2E9CF9DE00B63436 /* NCTransfersView.swift */; }; F78026122E9CFA6300B63436 /* NCTransfersModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = F78026112E9CFA6000B63436 /* NCTransfersModel.swift */; }; F7802B322BD5584F00D74270 /* NCMedia+DragDrop.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7802B312BD5584F00D74270 /* NCMedia+DragDrop.swift */; }; @@ -1830,9 +1827,6 @@ F77C97382953131000FDDD09 /* NCCameraRoll.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NCCameraRoll.swift; sourceTree = ""; }; F77DD6A72C5CC093009448FB /* NCSession.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NCSession.swift; sourceTree = ""; }; F77E8C1E2E79717D00EAE68F /* NCManageDatabase+LivePhoto.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "NCManageDatabase+LivePhoto.swift"; sourceTree = ""; }; - F77ED59028C9CE9D00E24ED0 /* ToolbarData.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ToolbarData.swift; sourceTree = ""; }; - F77ED59228C9CEA000E24ED0 /* ToolbarWidgetProvider.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ToolbarWidgetProvider.swift; sourceTree = ""; }; - F77ED59428C9CEA300E24ED0 /* ToolbarWidgetView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ToolbarWidgetView.swift; sourceTree = ""; }; F780260F2E9CF9DE00B63436 /* NCTransfersView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NCTransfersView.swift; sourceTree = ""; }; F78026112E9CFA6000B63436 /* NCTransfersModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NCTransfersModel.swift; sourceTree = ""; }; F7802B312BD5584F00D74270 /* NCMedia+DragDrop.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "NCMedia+DragDrop.swift"; sourceTree = ""; }; @@ -2739,7 +2733,6 @@ F72EA95528B7BAD100C88F0C /* Dashboard */, F72EA95628B7BAE700C88F0C /* Files */, F76DEE9A28F808BC0041B1C9 /* Lockscreen */, - F77ED59628C9CEEE00E24ED0 /* Toolbar */, F75DD764290AB369002EB562 /* Intent */, F7346E2028B0FA3A006CE2D2 /* Widget-Brinding-header.h */, F7346E1528B0EF5C006CE2D2 /* Widget.swift */, @@ -3335,16 +3328,6 @@ path = Test; sourceTree = ""; }; - F77ED59628C9CEEE00E24ED0 /* Toolbar */ = { - isa = PBXGroup; - children = ( - F77ED59028C9CE9D00E24ED0 /* ToolbarData.swift */, - F77ED59228C9CEA000E24ED0 /* ToolbarWidgetProvider.swift */, - F77ED59428C9CEA300E24ED0 /* ToolbarWidgetView.swift */, - ); - path = Toolbar; - sourceTree = ""; - }; F78ACD4721903F850088454D /* Cell */ = { isa = PBXGroup; children = ( @@ -4933,7 +4916,6 @@ F7E0710128B13BB00001B882 /* DashboardData.swift in Sources */, F783030328B4C4DD00B84583 /* ThreadSafeDictionary.swift in Sources */, F7CAFE1E2F17A37C00DB35A5 /* ProgressQuantizer.swift in Sources */, - F77ED59128C9CE9D00E24ED0 /* ToolbarData.swift in Sources */, F78302F728B4C3C900B84583 /* NCManageDatabase.swift in Sources */, F7346E1628B0EF5C006CE2D2 /* Widget.swift in Sources */, F7D61EAA2EBF1694007F865B /* NCManageDatabase+TableCapabilities.swift in Sources */, @@ -4972,9 +4954,7 @@ F763D29E2A249C4500A3C901 /* NCManageDatabase+Capabilities.swift in Sources */, F711A4DD2AF92CAE00095DD8 /* NCUtility+Date.swift in Sources */, F724377C2C10B92200C7C68D /* NCSharePermissions.swift in Sources */, - F77ED59328C9CEA000E24ED0 /* ToolbarWidgetProvider.swift in Sources */, F72A17D828B221E300F3F159 /* DashboardWidgetView.swift in Sources */, - F77ED59528C9CEA400E24ED0 /* ToolbarWidgetView.swift in Sources */, F78302FB28B4C3EE00B84583 /* NCManageDatabase+Video.swift in Sources */, F760A4902FE95D06001B212E /* NCTransferDelegateDispatcher.swift in Sources */, F7C687EA2D22BDE5004757BC /* NCManageDatabase+RecommendedFiles.swift in Sources */, diff --git a/Widget/Dashboard/DashboardData.swift b/Widget/Dashboard/DashboardData.swift index 0a02f54f00..def2e87529 100644 --- a/Widget/Dashboard/DashboardData.swift +++ b/Widget/Dashboard/DashboardData.swift @@ -6,207 +6,311 @@ import UIKit import WidgetKit import Intents import NextcloudKit -import RealmSwift struct DashboardDataEntry: TimelineEntry { let date: Date - let datas: [DashboardData] - let dashboard: tableDashboardWidget? - let buttons: [tableDashboardWidgetButton]? + let rows: [DashboardData] + let totalRows: Int + let buttons: [DashboardAction] + let webURL: URL? let isPlaceholder: Bool - let isEmpty: Bool + let allowsRefresh: Bool let titleImage: UIImage let title: String let footerImage: String let footerText: String - let account: String } -struct DashboardData: Identifiable, Hashable { +struct DashboardData: Identifiable { let id: Int let title: String - let subTitle: String - let link: URL - let icon: UIImage - let circle: Bool - let imageSystem: Bool - let imageColor: UIColor? + let subtitle: String + let link: URL? + let icon: UIImage? + let isRound: Bool + let calendarColor: UIColor? } -let dashboardDatasTest: [DashboardData] = [ - .init(id: 0, title: "title0", subTitle: "subTitle-description0", link: URL(string: "https://nextcloud.com/")!, icon: UIImage(systemName: "document")!, circle: false, imageSystem: true, imageColor: nil), - .init(id: 1, title: "title1", subTitle: "subTitle-description1", link: URL(string: "https://nextcloud.com/")!, icon: UIImage(systemName: "document")!, circle: false, imageSystem: true, imageColor: nil), - .init(id: 2, title: "title2", subTitle: "subTitle-description2", link: URL(string: "https://nextcloud.com/")!, icon: UIImage(systemName: "document")!, circle: true, imageSystem: false, imageColor: nil), - .init(id: 3, title: "title3", subTitle: "subTitle-description3", link: URL(string: "https://nextcloud.com/")!, icon: UIImage(systemName: "document")!, circle: false, imageSystem: false, imageColor: nil), - .init(id: 4, title: "title4", subTitle: "subTitle-description4", link: URL(string: "https://nextcloud.com/")!, icon: UIImage(systemName: "circle.fill")!, circle: false, imageSystem: false, imageColor: nil), - .init(id: 5, title: "title5", subTitle: "subTitle-description5", link: URL(string: "https://nextcloud.com/")!, icon: UIImage(systemName: "circle.fill")!, circle: false, imageSystem: false, imageColor: nil), - .init(id: 6, title: "title6", subTitle: "subTitle-description6", link: URL(string: "https://nextcloud.com/")!, icon: UIImage(systemName: "circle.fill")!, circle: false, imageSystem: false, imageColor: nil), - .init(id: 7, title: "title7", subTitle: "subTitle-description7", link: URL(string: "https://nextcloud.com/")!, icon: UIImage(systemName: "circle.fill")!, circle: false, imageSystem: false, imageColor: nil), - .init(id: 8, title: "title8", subTitle: "subTitle-description8", link: URL(string: "https://nextcloud.com/")!, icon: UIImage(systemName: "circle.fill")!, circle: false, imageSystem: false, imageColor: nil), - .init(id: 9, title: "title9", subTitle: "subTitle-description9", link: URL(string: "https://nextcloud.com/")!, icon: UIImage(systemName: "circle.fill")!, circle: false, imageSystem: false, imageColor: nil) -] - -func getDashboardItems(displaySize: CGSize, withButton: Bool) -> Int { - if withButton { - let items = Int((displaySize.height - 90) / 55) - return items - } else { - let items = Int((displaySize.height - 50) / 55) - return items +struct DashboardAction: Identifiable, Sendable { + let id: String + let title: String + let url: URL + let isMore: Bool +} + +private struct DashboardModuleItem: Decodable { + let title: String? + let subtitle: String? + let link: String? + let iconUrl: String? +} + +private struct DashboardItemsResponse: Decodable { + struct OCS: Decodable { + struct Meta: Decodable { + let statuscode: Int + let message: String? + } + + struct Module: Decodable { + let items: [DashboardModuleItem] + } + + let meta: Meta + let data: [String: Module] + + private enum CodingKeys: String, CodingKey { + case meta, data + } + + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + meta = try container.decode(Meta.self, forKey: .meta) + if !(200..<300).contains(meta.statuscode) { + data = [:] + } else if let modules = try? container.decode([Module].self, forKey: .data), modules.isEmpty { + // OCS may encode an empty module map as a JSON array. + data = [:] + } else { + data = try container.decode([String: Module].self, forKey: .data) + } + } + } + + let ocs: OCS +} + +func dashboardPlaceholder(height: CGFloat, + title: String = "Dashboard", + titleImage: UIImage? = UIImage(systemName: "rectangle.grid.2x2"), + footerText: String = NCBrandOptions.shared.brand, + isError: Bool = false) -> DashboardDataEntry { + let count = DashboardWidgetLayout.rowCount(for: height, hasActions: false) + let rows = (0.. DashboardDataEntry { - let utilityFileSystem = NCUtilityFileSystem() +func getDashboardDataEntry(configuration: DashboardIntent, displaySize: CGSize) async -> DashboardDataEntry { + let height = displaySize.height let utility = NCUtility() - let dashboardItems = getDashboardItems(displaySize: displaySize, withButton: false) - let datasPlaceholder = Array(dashboardDatasTest[0...dashboardItems - 1]) - var activeTableAccount: tableAccount? - let versionApp = NCUtility().getVersionMaintenance() guard let groupDefaults = UserDefaults(suiteName: NCBrandOptions.shared.capabilitiesGroup), - let lastVersion = groupDefaults.string(forKey: NCGlobal.shared.udLastVersion), - lastVersion == versionApp else { - return (DashboardDataEntry(date: Date(), datas: datasPlaceholder, dashboard: nil, buttons: nil, isPlaceholder: true, isEmpty: false, titleImage: UIImage(systemName: "circle.fill") ?? UIImage(), title: "Dashboard", footerImage: "checkmark.icloud", footerText: NSLocalizedString("_version_mismatch_error_", comment: ""), account: "")) + groupDefaults.string(forKey: NCGlobal.shared.udLastVersion) == utility.getVersionMaintenance() else { + return dashboardPlaceholder(height: height, + footerText: NSLocalizedString("_version_mismatch_error_", comment: ""), + isError: true) } - if isPreview, - let image = UIImage(systemName: "circle.fill") { - return (DashboardDataEntry(date: Date(), datas: datasPlaceholder, dashboard: nil, buttons: nil, isPlaceholder: true, isEmpty: false, titleImage: image, title: "Dashboard", footerImage: "checkmark.icloud", footerText: NCBrandOptions.shared.brand + " dashboard", account: "")) - } + let accountIdentifier = configuration.accounts?.identifier ?? "active" + let database = NCManageDatabase.shared + let selectedAccount = accountIdentifier == "active" + ? database.getActiveTableAccount() + : database.getTableAccount(account: accountIdentifier) - let accountIdentifier: String = configuration?.accounts?.identifier ?? "active" - if accountIdentifier == "active" { - activeTableAccount = NCManageDatabase.shared.getActiveTableAccount() - } else { - activeTableAccount = NCManageDatabase.shared.getTableAccount(predicate: NSPredicate(format: "account == %@", accountIdentifier)) + guard let account = selectedAccount else { + return dashboardPlaceholder(height: height, + footerText: NSLocalizedString("_no_active_account_", comment: ""), + isError: true) } - guard let activeTableAccount else { - return (DashboardDataEntry(date: Date(), datas: datasPlaceholder, dashboard: nil, buttons: nil, isPlaceholder: true, isEmpty: false, titleImage: UIImage(systemName: "circle.fill") ?? UIImage(), title: "Dashboard", footerImage: "xmark.icloud", footerText: NSLocalizedString("_no_active_account_", comment: ""), account: "")) - } NextcloudKit.shared.setup(groupIdentifier: NCBrandOptions.shared.capabilitiesGroup, delegate: NCNetworking.shared) - NextcloudKit.shared.appendSession(account: activeTableAccount.account, - urlBase: activeTableAccount.urlBase, - user: activeTableAccount.user, - userId: activeTableAccount.userId, - password: NCPreferences().getPassword(account: activeTableAccount.account), + NextcloudKit.shared.appendSession(account: account.account, + urlBase: account.urlBase, + user: account.user, + userId: account.userId, + password: NCPreferences().getPassword(account: account.account), userAgent: userAgent, httpMaximumConnectionsPerHost: NCBrandOptions.shared.httpMaximumConnectionsPerHost, httpMaximumConnectionsPerHostInDownload: NCBrandOptions.shared.httpMaximumConnectionsPerHostInDownload, httpMaximumConnectionsPerHostInUpload: NCBrandOptions.shared.httpMaximumConnectionsPerHostInUpload, groupIdentifier: NCBrandOptions.shared.capabilitiesGroup) - // LOG - let versionNextcloudiOS = String(format: NCBrandOptions.shared.textCopyrightNextcloudiOS, utility.getVersionBuild()) - NextcloudKit.configureLogger( - logLevel: NCBrandOptions.shared.disable_log ? .disabled : NCPreferences().log, - logDirectory: NCPreferences.sharedLogDirectory - ) + NextcloudKit.configureLogger(logLevel: NCBrandOptions.shared.disable_log ? .disabled : NCPreferences().log, + logDirectory: NCPreferences.sharedLogDirectory) defer { NextcloudKit.flushLogger() } - nkLog(debug: "Start \(NCBrandOptions.shared.brand) dashboard widget session " + versionNextcloudiOS) + let version = String(format: NCBrandOptions.shared.textCopyrightNextcloudiOS, utility.getVersionBuild()) + nkLog(debug: "Start \(NCBrandOptions.shared.brand) dashboard widget session " + version) - // Widget - let widgetApplication = NCManageDatabase.shared.getDashboardWidgetApplications(account: activeTableAccount.account).first - let widgetApplicationId: String = configuration?.applications?.identifier ?? (widgetApplication?.id ?? "recommendations") + let moduleId = configuration.applications?.identifier + ?? database.getDashboardWidgetApplications(account: account.account).first?.id + ?? "recommendations" + let (module, moduleButtons) = database.getDashboardWidget(account: account.account, id: moduleId) + let title = module?.title ?? moduleId + let baseURL = URL(string: account.urlBase) + let actions = (moduleButtons ?? []).compactMap { button -> DashboardAction? in + guard moduleId != "notes" || button.type != "new" else { return nil } - let (tableDashboard, tableButton) = NCManageDatabase.shared.getDashboardWidget(account: activeTableAccount.account, id: widgetApplicationId) - let existsButton = (tableButton?.isEmpty ?? true) ? false : true - let title = tableDashboard?.title ?? widgetApplicationId - - var titleImage: UIImage = UIImage(systemName: "circle.fill") ?? UIImage() - if let fileName = tableDashboard?.iconClass { - let fileNamePath: String = utilityFileSystem.createServerUrl(serverUrl: utilityFileSystem.directoryUserData, fileName: fileName + ".png") - if let image = UIImage(contentsOfFile: fileNamePath) { - titleImage = image.withTintColor(NCBrandColor.shared.iconImageColor, renderingMode: .alwaysOriginal) + let isMore = button.type == "more" + let url: URL? + if moduleId == "files-favorites", isMore { + var components = URLComponents() + components.scheme = NCGlobal.shared.appScheme + components.host = "openFavorites" + components.queryItems = [URLQueryItem(name: "account", value: account.account)] + url = components.url + } else { + url = dashboardWebURL(button.link, relativeTo: baseURL) } + guard let url else { return nil } + return DashboardAction(id: button.index, title: button.text, url: url, isMore: isMore) } + + let titleImage: UIImage? + if let iconClass = module?.iconClass { + let fileSystem = NCUtilityFileSystem() + let path = fileSystem.createServerUrl(serverUrl: fileSystem.directoryUserData, fileName: iconClass + ".png") + titleImage = UIImage(contentsOfFile: path) + } else { + titleImage = nil + } + let moduleImage = titleImage ?? UIImage(systemName: "rectangle.grid.2x2") ?? UIImage() + let roundIcons = module?.itemIconsRound ?? false + + let isOnThisDay = moduleId == "photos-onthisday" + let itemAPIVersion = module?.preferredItemAPIVersion ?? (isOnThisDay ? .unsupported : nil) + let webURL: URL? + if itemAPIVersion == .unsupported { + let defaultURL = isOnThisDay ? account.urlBase + "/index.php/apps/photos/thisday" : nil + webURL = dashboardWebURL(module?.widgetUrl, relativeTo: baseURL) ?? dashboardWebURL(defaultURL, relativeTo: baseURL) + } else { + webURL = nil + } + let options = NKRequestOptions(timeout: 90, queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue) - let resultsDashboardWidget = await NextcloudKit.shared.getDashboardWidgetsApplicationAsync(widgetApplicationId, account: activeTableAccount.account, options: options) - - var datas = [DashboardData]() - var numberItems = 0 - - if resultsDashboardWidget.error == .success, - let dashboardApplications = resultsDashboardWidget.dashboardApplications { - for dashboardApplication in dashboardApplications { - if let items = dashboardApplication.items { - numberItems = dashboardApplication.items?.count ?? 0 - var counter: Int = 0 - let dashboardItems = getDashboardItems(displaySize: displaySize, withButton: existsButton) - for item in items { - counter += 1 - - let title = item.title ?? "" - let subtitle = item.subtitle ?? "" - - var link: URL = URL(string: "https://")! - if let entryLink = item.link, - let url = URL(string: entryLink) { - link = url - } - var iconImage = UIImage(systemName: "document") ?? UIImage() - var imageCircle: Bool = false - var imageColorized: Bool = false - var imageSystem: Bool = false - var imageColor: UIColor? - - if let iconUrl = item.iconUrl, let url = URL(string: iconUrl) { - if let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) { - let path = (urlComponents.path as NSString) - let pathComponents = path.components(separatedBy: "/") - - if pathComponents.contains("avatar") { - imageCircle = true - } else if pathComponents.contains("getCalendarDotSvg") { - imageColorized = true - } - } - // Color - if imageColorized, let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) { - let path = (urlComponents.path as NSString) - let colorString = ((path.lastPathComponent) as NSString).deletingPathExtension - imageColor = UIColor(hex: colorString) - iconImage = UIImage(systemName: "circle.fill") ?? UIImage() - } else { - let results = await NextcloudKit.shared.downloadPreviewAsync(url: url, account: activeTableAccount.account) - if results.error == .success, - let data = results.responseData?.data { - if let image = UIImage(data: data) { - iconImage = image - } else { - imageSystem = true - } - /* NO MEMORY - else if let image = try? await NCSVGRenderer().renderSVGToUIImage(svgData: data) { - iconImage = image - } - */ - } - } - } - - let data = DashboardData(id: counter, title: title, subTitle: subtitle, link: link, icon: iconImage, circle: imageCircle, imageSystem: imageSystem, imageColor: imageColor) - datas.append(data) - - if datas.count == dashboardItems { break } + let result = await getDashboardModuleItems(moduleId, + version: itemAPIVersion, + account: account.account, + options: options) + guard result.error == .success else { + return dashboardPlaceholder(height: height, + title: title, + titleImage: moduleImage, + footerText: result.error.localizedGenericMessage, + isError: true) + } + + let items = result.items + let visibleActions = DashboardWidgetLayout.visibleActions(actions, totalRows: items.count, height: height) + let rowCount = DashboardWidgetLayout.rowCount(for: height, hasActions: !visibleActions.isEmpty) + var rows: [DashboardData] = [] + + for (index, item) in items.prefix(rowCount).enumerated() { + var icon: UIImage? + var isRound = roundIcons + var calendarColor: UIColor? + + if let iconURL = dashboardWebURL(item.iconUrl, relativeTo: baseURL) { + isRound = isRound || iconURL.pathComponents.contains("avatar") + if iconURL.pathComponents.suffix(2).elementsEqual(["filetypes", "folder.svg"]) { + icon = utility.loadImage(named: NKTypeIconFile.directory.rawValue, + size: DashboardWidgetLayout.iconSize, + useTypeIconFile: true, + account: account.account) + isRound = false + } else if iconURL.pathComponents.contains("getCalendarDotSvg") { + calendarColor = UIColor(hex: (iconURL.lastPathComponent as NSString).deletingPathExtension) + } else { + let preview = await NextcloudKit.shared.downloadPreviewAsync(url: iconURL, account: account.account, options: options) + if preview.error == .success, let data = preview.responseData?.data { + icon = UIImage(data: data) } } } + + rows.append(DashboardData(id: index, + title: item.title ?? "", + subtitle: item.subtitle ?? "", + link: dashboardWebURL(item.link, relativeTo: baseURL), + icon: icon, + isRound: isRound, + calendarColor: calendarColor)) + } + + let accountName = account.alias.isEmpty ? account.displayName : "\(account.displayName) (\(account.alias))" + return DashboardDataEntry(date: Date(), + rows: rows, + totalRows: items.count, + buttons: actions, + webURL: webURL, + isPlaceholder: false, + allowsRefresh: webURL == nil, + titleImage: moduleImage, + title: title, + footerImage: "checkmark.icloud", + footerText: accountName) +} + +private func getDashboardModuleItems(_ moduleId: String, + version: DashboardItemAPIVersion?, + account: String, + options: NKRequestOptions) async -> (items: [DashboardModuleItem], error: NKError) { + if version == .unsupported { + return ([], .success) } - var buttons = tableButton - if numberItems == datas.count, let tableButton = tableButton, tableButton.contains(where: { $0.type == "more"}) { - buttons = tableButton.filter(({ $0.type != "more" })) + if version != .v2 { + let result = await NextcloudKit.shared.getDashboardWidgetsApplicationAsync(moduleId, account: account, options: options) + guard result.error == .success else { return ([], result.error) } + + if let items = result.dashboardApplications?.first(where: { $0.application == moduleId })?.items { + return (items.map { DashboardModuleItem(title: $0.title, subtitle: $0.subtitle, link: $0.link, iconUrl: $0.iconUrl) }, .success) + } + if version == .v1 { + return ([], .success) + } } - let alias = (activeTableAccount.alias.isEmpty) ? "" : (" (" + activeTableAccount.alias + ")") - let footerText = "Dashboard " + NSLocalizedString("_of_", comment: "") + " " + activeTableAccount.displayName + alias + // A catalog without version metadata keeps the v1-to-v2 fallback. + var components = URLComponents() + components.path = "ocs/v2.php/apps/dashboard/api/v2/widget-items" + components.queryItems = [ + URLQueryItem(name: "widgets[]", value: moduleId), + URLQueryItem(name: "format", value: "json") + ] + guard let endpoint = components.string else { return ([], .urlError) } - if resultsDashboardWidget.error != .success { - return(DashboardDataEntry(date: Date(), datas: datasPlaceholder, dashboard: tableDashboard, buttons: buttons, isPlaceholder: true, isEmpty: false, titleImage: titleImage, title: title, footerImage: "xmark.icloud", footerText: resultsDashboardWidget.error.localizedGenericMessage, account: activeTableAccount.account)) - } else { - return(DashboardDataEntry(date: Date(), datas: datas, dashboard: tableDashboard, buttons: buttons, isPlaceholder: false, isEmpty: datas.isEmpty, titleImage: titleImage, title: title, footerImage: "checkmark.icloud", footerText: footerText, account: activeTableAccount.account)) + let response = await NextcloudKit.shared.generalWithEndpointAsync(endpoint, account: account, method: "GET", options: options) + if version == nil, response.error.errorCode == 404 { + return ([], .success) } + guard response.error == .success else { return ([], response.error) } + guard let data = response.responseData?.data, + let payload = try? JSONDecoder().decode(DashboardItemsResponse.self, from: data) else { + return ([], .invalidResponseError) + } + + let meta = payload.ocs.meta + guard (200..<300).contains(meta.statuscode) else { + return ([], NKError(errorCode: meta.statuscode, errorDescription: meta.message ?? "")) + } + + return (payload.ocs.data[moduleId]?.items ?? [], .success) +} + +private func dashboardWebURL(_ value: String?, relativeTo baseURL: URL?) -> URL? { + guard let value, !value.isEmpty else { return nil } + let url = value.hasPrefix("/") ? URL(string: value, relativeTo: baseURL)?.absoluteURL : URL(string: value) + guard let url, let scheme = url.scheme?.lowercased(), + scheme == "https" || scheme == "http", + let host = url.host, !host.isEmpty else { return nil } + return url } diff --git a/Widget/Dashboard/DashboardWidgetProvider.swift b/Widget/Dashboard/DashboardWidgetProvider.swift index 60169bbf6c..670dd4fe7c 100644 --- a/Widget/Dashboard/DashboardWidgetProvider.swift +++ b/Widget/Dashboard/DashboardWidgetProvider.swift @@ -2,35 +2,48 @@ // SPDX-FileCopyrightText: 2022 Marino Faggiana // SPDX-License-Identifier: GPL-3.0-or-later -import UIKit +import AppIntents import WidgetKit import Intents -import SwiftUI struct DashboardWidgetProvider: IntentTimelineProvider { typealias Intent = DashboardIntent typealias Entry = DashboardDataEntry func placeholder(in context: Context) -> Entry { - let dashboardItems = getDashboardItems(displaySize: context.displaySize, withButton: false) - let datasPlaceholder = Array(dashboardDatasTest[0...dashboardItems]) - let title = "Dashboard" - let titleImage = UIImage(systemName: "circle.fill") ?? UIImage() - return Entry(date: Date(), datas: datasPlaceholder, dashboard: nil, buttons: nil, isPlaceholder: true, isEmpty: false, titleImage: titleImage, title: title, footerImage: "checkmark.icloud", footerText: NCBrandOptions.shared.brand + " widget", account: "") + dashboardPlaceholder(height: context.displaySize.height) } - func getSnapshot(for configuration: DashboardIntent, in context: Context, completion: @escaping (DashboardDataEntry) -> Void) { + func getSnapshot(for configuration: DashboardIntent, in context: Context, completion: @escaping (Entry) -> Void) { + guard !context.isPreview else { + completion(placeholder(in: context)) + return + } + Task { - let entry = await getDashboardDataEntry(configuration: configuration, isPreview: false, displaySize: context.displaySize) - completion(entry) + completion(await getDashboardDataEntry(configuration: configuration, displaySize: context.displaySize)) } } - func getTimeline(for configuration: DashboardIntent, in context: Context, completion: @escaping (Timeline) -> Void) { + func getTimeline(for configuration: DashboardIntent, in context: Context, completion: @escaping (Timeline) -> Void) { + guard !context.isPreview else { + completion(Timeline(entries: [placeholder(in: context)], policy: .never)) + return + } + Task { - let entry = await getDashboardDataEntry(configuration: configuration, isPreview: context.isPreview, displaySize: context.displaySize) - let timeLine = Timeline(entries: [entry], policy: .atEnd) - completion(timeLine) + let entry = await getDashboardDataEntry(configuration: configuration, displaySize: context.displaySize) + completion(Timeline(entries: [entry], policy: .atEnd)) } } } + +struct RefreshDashboardWidgetIntent: AppIntent { + static let title: LocalizedStringResource = "Refresh Dashboard" + static let openAppWhenRun = false + + func perform() async throws -> some IntentResult { + // WidgetKit reloads this widget's timeline after its button intent completes. + return .result() + } +} diff --git a/Widget/Dashboard/DashboardWidgetView.swift b/Widget/Dashboard/DashboardWidgetView.swift index 3ae749bdd9..c6409549c6 100644 --- a/Widget/Dashboard/DashboardWidgetView.swift +++ b/Widget/Dashboard/DashboardWidgetView.swift @@ -2,161 +2,251 @@ // SPDX-FileCopyrightText: 2022 Marino Faggiana // SPDX-License-Identifier: GPL-3.0-or-later +import AppIntents import SwiftUI import WidgetKit +nonisolated enum DashboardWidgetLayout { + static let padding: CGFloat = 12 + static let sectionSpacing: CGFloat = 4 + static let headerHeight: CGFloat = 22 + static let footerHeight: CGFloat = 44 + static let actionHeight: CGFloat = 36 + static let rowHeight: CGFloat = 44 + static let iconSize: CGFloat = 32 + static let rowSpacing: CGFloat = 10 + + static func rowCount(for height: CGFloat, hasActions: Bool) -> Int { + guard height.isFinite else { return 0 } + let reservedHeight = 2 * padding + 2 * sectionSpacing + headerHeight + footerHeight + let actionSpace = hasActions ? actionHeight + sectionSpacing : 0 + let rows = (height - reservedHeight - actionSpace) / rowHeight + return Int(min(50, max(0, rows))) + } + + static func visibleActions(_ actions: [DashboardAction], + totalRows: Int, + height: CGFloat, + loadedRows: Int = .max) -> [DashboardAction] { + let otherActions = actions.filter { !$0.isMore } + let rowsWithoutMore = rowCount(for: height, hasActions: !otherActions.isEmpty) + return totalRows > min(rowsWithoutMore, loadedRows) ? actions : otherActions + } +} + struct DashboardWidgetView: View { - var entry: DashboardDataEntry + let entry: DashboardDataEntry + var body: some View { - GeometryReader { geo in - if entry.isEmpty { - VStack(alignment: .center) { - Image(systemName: "checkmark") - .resizable() - .scaledToFit() - .font(Font.system(.body).weight(.light)) - .frame(width: 50, height: 50) - Text(NSLocalizedString("_no_items_", comment: "")) - .font(.system(size: 25)) - .padding() - Text(NSLocalizedString("_check_back_later_", comment: "")) - .font(.system(size: 15)) - } - .frame(width: geo.size.width, height: geo.size.height) - } + GeometryReader { geometry in + let height = geometry.size.height + let actions = DashboardWidgetLayout.visibleActions(entry.buttons, + totalRows: entry.totalRows, + height: height, + loadedRows: entry.rows.count) + let rows = entry.rows.prefix(DashboardWidgetLayout.rowCount(for: height, hasActions: !actions.isEmpty)) - ZStack(alignment: .topLeading) { - HStack { - Image(uiImage: entry.titleImage) - .renderingMode(.template) - .resizable() - .scaledToFill() - .frame(width: 20, height: 20) - - Text(entry.title) - .font(.system(size: 15)) - .fontWeight(.bold) - .multilineTextAlignment(.center) - .textCase(.uppercase) - .lineLimit(1) - } - .frame(width: geo.size.width - 20) - .padding([.top, .leading, .trailing], 10) - if !entry.isEmpty { - VStack(alignment: .leading) { - VStack(spacing: 0) { - ForEach(entry.datas, id: \.id) { element in - Link(destination: element.link) { - HStack { - let subTitleColor = Color(white: 0.5) - if entry.isPlaceholder { - Circle() - .fill(Color(.systemGray4)) - .frame(width: 35, height: 35) - } else if let color = element.imageColor { - Image(uiImage: element.icon) - .renderingMode(.template) - .resizable() - .frame(width: 35, height: 35) - .foregroundColor(Color(color)) - .scaleEffect(0.8) - } else if element.imageSystem { - Image(uiImage: element.icon) - .resizable() - .scaledToFit() - .frame(width: 35, height: 35) - .scaleEffect(0.8) - } else { - if entry.dashboard?.itemIconsRound ?? false || element.circle { - Image(uiImage: element.icon) - .resizable() - .scaledToFill() - .frame(width: 35, height: 35) - .clipShape(Circle()) - } else { - Image(uiImage: element.icon) - .resizable() - .scaledToFill() - .frame(width: 35, height: 35) - .clipped() - .cornerRadius(5) - } - } - - VStack(alignment: .leading, spacing: 2) { - - Text(element.title) - .font(.system(size: 12)) - .fontWeight(.regular) - - Text(element.subTitle) - .font(.system(size: CGFloat(10))) - .foregroundColor(subTitleColor) - } - Spacer() + VStack(alignment: .leading, spacing: DashboardWidgetLayout.sectionSpacing) { + header + + if let webURL = entry.webURL, let browserURL = browserDeepLink(for: webURL) { + VStack(spacing: 10) { + Text(NSLocalizedString("_widget_dashboard_available_on_web_", value: "Available on the web", comment: "")) + .font(.subheadline) + .foregroundStyle(.secondary) + + Link(destination: browserURL) { + Label(NSLocalizedString("_widget_dashboard_open_in_browser_", value: "Open in browser", comment: ""), systemImage: "safari") + .font(.system(size: 13, weight: .semibold)) + .padding(.horizontal, 12) + .frame(minHeight: 36) + .background(Color.accentColor.opacity(0.12), in: Capsule()) + } + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else if entry.totalRows == 0, !entry.isPlaceholder { + Text(NSLocalizedString("_no_data_available_", comment: "")) + .font(.subheadline) + .foregroundStyle(.secondary) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else { + VStack(spacing: 0) { + ForEach(rows) { row in + dashboardRow(row) + .overlay(alignment: .bottomLeading) { + if row.id != rows.last?.id { + Divider() + .padding(.leading, DashboardWidgetLayout.iconSize + DashboardWidgetLayout.rowSpacing) } - .padding(.leading, 10) - .frame(height: 50) - } - if element != entry.datas.last { - Divider() - .padding(.leading, 54) } - } } } - .padding(.top, 35) .redacted(reason: entry.isPlaceholder ? .placeholder : []) + .frame(maxHeight: .infinity, alignment: .top) } - if let buttons = entry.buttons, !buttons.isEmpty, !entry.isPlaceholder { - HStack(spacing: 10) { - let brandColor = Color(NCBrandColor.shared.getElement(account: entry.account)) - let brandTextColor = Color(NCBrandColor.shared.getText(account: entry.account)) - - ForEach(buttons, id: \.index) { element in - Link(destination: URL(string: element.link)!, label: { - - Text(element.text) - .font(.system(size: 15)) - .padding(7) - .background(brandColor) - .foregroundColor(brandTextColor) - .border(brandColor, width: 1) - .cornerRadius(.infinity) - }) - } - } - .frame(width: geo.size.width - 10, height: geo.size.height - 25, alignment: .bottomTrailing) + if !actions.isEmpty { + actionRow(actions) + } + + footer + } + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) + .padding(DashboardWidgetLayout.padding) + } + .containerBackground(.background, for: .widget) + } + + private func browserDeepLink(for webURL: URL) -> URL? { + var components = URLComponents() + components.scheme = NCGlobal.shared.appScheme + components.host = "openUrl" + components.queryItems = [URLQueryItem(name: "url", value: webURL.absoluteString)] + return components.url + } + + private var header: some View { + HStack(spacing: 8) { + Image(uiImage: entry.titleImage) + .renderingMode(.template) + .resizable() + .scaledToFit() + .frame(width: 18, height: 18) + .accessibilityHidden(true) + + Text(entry.title) + .font(.system(size: 16, weight: .semibold)) + .lineLimit(1) + .accessibilityAddTraits(.isHeader) + } + .frame(height: DashboardWidgetLayout.headerHeight) + } + + private func actionRow(_ actions: [DashboardAction]) -> some View { + HStack(spacing: 8) { + ForEach(actions) { action in + Link(destination: action.url) { + Text(action.title) + .font(.system(size: 12, weight: .semibold)) + .lineLimit(1) + .padding(.horizontal, 10) + .frame(minHeight: 30) + .background(Color.accentColor.opacity(0.12), in: Capsule()) + } + } + } + .frame(maxWidth: .infinity, alignment: .trailing) + .frame(height: DashboardWidgetLayout.actionHeight) + } + + private var footer: some View { + HStack(spacing: 8) { + if entry.allowsRefresh { + Button(intent: RefreshDashboardWidgetIntent()) { + Image(systemName: "arrow.clockwise") + .font(.system(size: 19, weight: .semibold)) + .foregroundStyle(.tint) + .frame(width: DashboardWidgetLayout.footerHeight, height: DashboardWidgetLayout.footerHeight) + .contentShape(Rectangle()) } + .buttonStyle(.plain) + .accessibilityLabel(Text(NSLocalizedString("_widget_refresh_dashboard_", value: "Refresh Dashboard", comment: ""))) + } - HStack { - Image(systemName: entry.footerImage) - .resizable() - .scaledToFit() - .frame(width: 15, height: 15) - .font(Font.system(.body).weight(.light)) - .foregroundColor(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getElement(account: entry.account))) + VStack(alignment: .leading, spacing: 2) { + Label(entry.footerText, systemImage: entry.footerImage) + .truncationMode(.middle) - Text(entry.footerText) - .font(.caption2) + if !entry.isPlaceholder, entry.webURL == nil { + let updated = entry.date.formatted(.dateTime.day().month(.abbreviated).hour().minute()) + Text(String.localizedStringWithFormat( + NSLocalizedString("_widget_updated_at_", value: "Updated %@", comment: ""), + updated + )) + .invalidatableContent() + } + } + .font(.system(size: 11)) + .foregroundStyle(.secondary) + .lineLimit(1) + } + .frame(maxWidth: .infinity, alignment: .leading) + .frame(height: DashboardWidgetLayout.footerHeight) + } + + @ViewBuilder + private func dashboardRow(_ row: DashboardData) -> some View { + if let link = row.link { + Link(destination: link) { + rowContent(row) + } + } else { + rowContent(row) + } + } + + private func rowContent(_ row: DashboardData) -> some View { + HStack(spacing: DashboardWidgetLayout.rowSpacing) { + rowIcon(row) + .frame(width: DashboardWidgetLayout.iconSize, height: DashboardWidgetLayout.iconSize) + .accessibilityHidden(true) + + VStack(alignment: .leading, spacing: 2) { + Text(row.title) + .font(.system(size: 13, weight: .medium)) + .foregroundStyle(.primary) + .lineLimit(1) + + if !row.subtitle.isEmpty { + Text(row.subtitle) + .font(.system(size: 11)) + .foregroundStyle(.secondary) .lineLimit(1) - .foregroundColor(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getElement(account: entry.account))) } - .padding(.horizontal, 15.0) - .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottom) } } - .containerBackground(.background, for: .widget) + .frame(maxWidth: .infinity, alignment: .leading) + .frame(height: DashboardWidgetLayout.rowHeight) + .contentShape(Rectangle()) + .accessibilityElement(children: .combine) + } + + @ViewBuilder + private func rowIcon(_ row: DashboardData) -> some View { + if let color = row.calendarColor { + Circle() + .fill(Color(color)) + .frame(width: 12, height: 12) + } else if let icon = row.icon { + Image(uiImage: icon) + .resizable() + .scaledToFill() + .frame(width: DashboardWidgetLayout.iconSize, height: DashboardWidgetLayout.iconSize) + .clipShape(RoundedRectangle(cornerRadius: row.isRound ? DashboardWidgetLayout.iconSize / 2 : 6)) + } else { + Image(systemName: "doc") + .font(.system(size: 19)) + .foregroundStyle(.secondary) + } } } struct DashboardWidget_Previews: PreviewProvider { static var previews: some View { - let datas = Array(dashboardDatasTest[0...4]) - let title = "Dashboard" - let titleImage = UIImage(systemName: "circle.fill")! - let entry = DashboardDataEntry(date: Date(), datas: datas, dashboard: nil, buttons: nil, isPlaceholder: false, isEmpty: false, titleImage: titleImage, title: title, footerImage: "checkmark.icloud", footerText: NCBrandOptions.shared.brand + " widget", account: "") - DashboardWidgetView(entry: entry).previewContext(WidgetPreviewContext(family: .systemLarge)) + let sample = dashboardPlaceholder(height: 360) + let entry = DashboardDataEntry(date: Date(), + rows: sample.rows, + totalRows: sample.totalRows, + buttons: [], + webURL: nil, + isPlaceholder: false, + allowsRefresh: true, + titleImage: sample.titleImage, + title: sample.title, + footerImage: sample.footerImage, + footerText: sample.footerText) + + DashboardWidgetView(entry: entry) + .previewContext(WidgetPreviewContext(family: .systemLarge)) } } diff --git a/Widget/Files/FilesWidgetView.swift b/Widget/Files/FilesWidgetView.swift index 97afb68c38..0c06f7a8e6 100644 --- a/Widget/Files/FilesWidgetView.swift +++ b/Widget/Files/FilesWidgetView.swift @@ -92,7 +92,7 @@ struct FilesWidgetView: View { if !entry.isPlaceholder { let updated = entry.date.formatted(.dateTime.day().month(.abbreviated).hour().minute()) Text(String.localizedStringWithFormat( - NSLocalizedString("_widget_files_updated_at_", value: "Updated %@", comment: ""), + NSLocalizedString("_widget_updated_at_", value: "Updated %@", comment: ""), updated )) .invalidatableContent() diff --git a/Widget/Lockscreen/LockscreenData.swift b/Widget/Lockscreen/LockscreenData.swift index 252799d770..e59232f0ec 100644 --- a/Widget/Lockscreen/LockscreenData.swift +++ b/Widget/Lockscreen/LockscreenData.swift @@ -10,27 +10,27 @@ struct LockscreenData: TimelineEntry { let date: Date let isPlaceholder: Bool let activity: String - let link: URL - let quotaRelative: Float + let link: URL? + let quotaRelative: Double let quotaUsed: String let quotaTotal: String let error: Bool + var quotaTotalAccessibilityLabel: String? = nil } func getLockscreenDataEntry(configuration: AccountIntent?, isPreview: Bool, family: WidgetFamily, completion: @escaping (_ entry: LockscreenData) -> Void) { let utilityFileSystem = NCUtilityFileSystem() var activeTableAccount: tableAccount? - var quotaRelative: Float = 0 let versionApp = NCUtility().getVersionMaintenance() if let groupDefaults = UserDefaults(suiteName: NCBrandOptions.shared.capabilitiesGroup), let lastVersion = groupDefaults.string(forKey: NCGlobal.shared.udLastVersion), lastVersion != versionApp { - return completion(LockscreenData(date: Date(), isPlaceholder: true, activity: "", link: URL(string: "https://")!, quotaRelative: 0, quotaUsed: "", quotaTotal: "", error: false)) + return completion(LockscreenData(date: Date(), isPlaceholder: true, activity: "", link: nil, quotaRelative: 0, quotaUsed: "", quotaTotal: "", error: false)) } if isPreview { - return completion(LockscreenData(date: Date(), isPlaceholder: true, activity: "", link: URL(string: "https://")!, quotaRelative: 0, quotaUsed: "", quotaTotal: "", error: false)) + return completion(LockscreenData(date: Date(), isPlaceholder: true, activity: "", link: nil, quotaRelative: 0, quotaUsed: "", quotaTotal: "", error: false)) } let accountIdentifier: String = configuration?.accounts?.identifier ?? "active" @@ -41,7 +41,7 @@ func getLockscreenDataEntry(configuration: AccountIntent?, isPreview: Bool, fami } guard let activeTableAccount else { - return completion(LockscreenData(date: Date(), isPlaceholder: true, activity: "", link: URL(string: "https://")!, quotaRelative: 0, quotaUsed: "", quotaTotal: "", error: false)) + return completion(LockscreenData(date: Date(), isPlaceholder: true, activity: "", link: nil, quotaRelative: 0, quotaUsed: "", quotaTotal: "", error: false)) } // NETWORKING @@ -63,41 +63,66 @@ func getLockscreenDataEntry(configuration: AccountIntent?, isPreview: Bool, fami if family == .accessoryCircular { NextcloudKit.shared.getUserMetadata(account: activeTableAccount.account, userId: activeTableAccount.userId, options: options) { _, userProfile, _, error in - if error == .success, let userProfile = userProfile { - if userProfile.quotaRelative > 0 { - quotaRelative = Float(userProfile.quotaRelative) / 100 - } - let quotaUsed: String = utilityFileSystem.transformedSize(userProfile.quotaUsed) - var quotaTotal: String = "" - - switch userProfile.quotaTotal { - case -1: - quotaTotal = "" - case -2: - quotaTotal = "" - case -3: - quotaTotal = "" - default: - quotaTotal = utilityFileSystem.transformedSize(userProfile.quotaTotal) - } - completion(LockscreenData(date: Date(), isPlaceholder: false, activity: "", link: URL(string: "https://")!, quotaRelative: quotaRelative, quotaUsed: quotaUsed, quotaTotal: quotaTotal, error: false)) - } else { - completion(LockscreenData(date: Date(), isPlaceholder: false, activity: "", link: URL(string: "https://")!, quotaRelative: 0, quotaUsed: "", quotaTotal: "", error: true)) + guard error == .success, let userProfile else { + completion(LockscreenData(date: Date(), isPlaceholder: false, activity: "", link: nil, quotaRelative: 0, quotaUsed: "", quotaTotal: "", error: true)) + return } + + let percentage = userProfile.quotaRelative + let total = userProfile.quotaTotal + let progress = total > 0 && percentage.isFinite ? min(max(percentage / 100, 0), 1) : 0 + let quotaUsed = utilityFileSystem.transformedSize(userProfile.quotaUsed) + let quotaTotal: String + let quotaTotalAccessibilityLabel: String? + + switch total { + case -3: + quotaTotal = "โˆž" + quotaTotalAccessibilityLabel = NSLocalizedString("_quota_space_unlimited_", comment: "") + case -1: + quotaTotal = utilityFileSystem.transformedSize(0) + quotaTotalAccessibilityLabel = nil + case ..<0: + quotaTotal = "โ€”" + quotaTotalAccessibilityLabel = NSLocalizedString("_quota_space_unknown_", comment: "") + default: + quotaTotal = utilityFileSystem.transformedSize(total) + quotaTotalAccessibilityLabel = nil + } + + completion(LockscreenData(date: Date(), + isPlaceholder: false, + activity: "", + link: nil, + quotaRelative: progress, + quotaUsed: quotaUsed, + quotaTotal: quotaTotal, + error: false, + quotaTotalAccessibilityLabel: quotaTotalAccessibilityLabel)) } } else if family == .accessoryRectangular { + let baseURL = URL(string: activeTableAccount.urlBase) NextcloudKit.shared.getDashboardWidgetsApplication("activity", account: activeTableAccount.account, options: options) { _, results, _, error in - var activity: String = NSLocalizedString("_no_data_available_", comment: "") - var link = URL(string: "https://")! - if error == .success, let result = results?.first { - if let item = result.items?.first { - if let title = item.title { activity = title } - if let itemLink = item.link, let url = URL(string: itemLink) { link = url } - } - completion(LockscreenData(date: Date(), isPlaceholder: false, activity: activity, link: link, quotaRelative: 0, quotaUsed: "", quotaTotal: "", error: false)) - } else { - completion(LockscreenData(date: Date(), isPlaceholder: false, activity: "", link: URL(string: "https://")!, quotaRelative: 0, quotaUsed: "", quotaTotal: "", error: true)) + guard error == .success else { + completion(LockscreenData(date: Date(), isPlaceholder: false, activity: "", link: nil, quotaRelative: 0, quotaUsed: "", quotaTotal: "", error: true)) + return } + + let item = results?.first(where: { $0.application == "activity" })?.items?.first + let activity = item?.title ?? NSLocalizedString("_no_data_available_", comment: "") + let link = activityURL(item?.link, relativeTo: baseURL) + completion(LockscreenData(date: Date(), isPlaceholder: false, activity: activity, link: link, quotaRelative: 0, quotaUsed: "", quotaTotal: "", error: false)) } + } else { + completion(LockscreenData(date: Date(), isPlaceholder: true, activity: "", link: nil, quotaRelative: 0, quotaUsed: "", quotaTotal: "", error: false)) } } + +private func activityURL(_ value: String?, relativeTo baseURL: URL?) -> URL? { + guard let value, !value.isEmpty else { return nil } + let url = value.hasPrefix("/") ? URL(string: value, relativeTo: baseURL)?.absoluteURL : URL(string: value) + guard let url, let scheme = url.scheme?.lowercased(), + scheme == "http" || scheme == "https", + let host = url.host, !host.isEmpty else { return nil } + return url +} diff --git a/Widget/Lockscreen/LockscreenWidgetProvider.swift b/Widget/Lockscreen/LockscreenWidgetProvider.swift index ee5c7effcb..db467a489b 100644 --- a/Widget/Lockscreen/LockscreenWidgetProvider.swift +++ b/Widget/Lockscreen/LockscreenWidgetProvider.swift @@ -12,11 +12,11 @@ struct LockscreenWidgetProvider: IntentTimelineProvider { typealias Intent = AccountIntent func placeholder(in context: Context) -> Entry { - return Entry(date: Date(), isPlaceholder: true, activity: "", link: URL(string: "https://")!, quotaRelative: 0, quotaUsed: "", quotaTotal: "", error: false) + return Entry(date: Date(), isPlaceholder: true, activity: "", link: nil, quotaRelative: 0, quotaUsed: "", quotaTotal: "", error: false) } func getSnapshot(for configuration: AccountIntent, in context: Context, completion: @escaping (Entry) -> Void) { - getLockscreenDataEntry(configuration: configuration, isPreview: false, family: context.family) { entry in + getLockscreenDataEntry(configuration: configuration, isPreview: context.isPreview, family: context.family) { entry in completion(entry) } } diff --git a/Widget/Lockscreen/LockscreenWidgetView.swift b/Widget/Lockscreen/LockscreenWidgetView.swift index a013844ab7..6aafa0b1f2 100644 --- a/Widget/Lockscreen/LockscreenWidgetView.swift +++ b/Widget/Lockscreen/LockscreenWidgetView.swift @@ -29,6 +29,7 @@ struct LockscreenWidgetView: View { label: { Text(" " + entry.quotaTotal + " ") .font(.system(size: 8.0)) + .accessibilityLabel(Text(entry.quotaTotalAccessibilityLabel ?? entry.quotaTotal)) }, currentValueLabel: { Text(entry.quotaUsed) @@ -59,6 +60,7 @@ struct LockscreenWidgetView: View { } else { Text(entry.activity) .font(.system(size: 12)).bold() + .privacySensitive() } } .widgetURL(entry.link) @@ -72,7 +74,7 @@ struct LockscreenWidgetView: View { struct LockscreenWidgetView_Previews: PreviewProvider { static var previews: some View { - let entry = LockscreenData(date: Date(), isPlaceholder: false, activity: "Alba Mayoral changed Marketing / Regional Marketing / Agenda Meetings / Q4 2022 / OCTOBER / 13.11 Afrah Kahlid.md", link: URL(string: "https://")!, quotaRelative: 0.5, quotaUsed: "999 GB", quotaTotal: "999 GB", error: false) + let entry = LockscreenData(date: Date(), isPlaceholder: false, activity: "Alex updated Documents / Meeting notes.pdf", link: nil, quotaRelative: 0.5, quotaUsed: "5 GB", quotaTotal: "10 GB", error: false) LockscreenWidgetView(entry: entry).previewContext(WidgetPreviewContext(family: .accessoryRectangular)).previewDisplayName("Rectangular") LockscreenWidgetView(entry: entry).previewContext(WidgetPreviewContext(family: .accessoryCircular)).previewDisplayName("Circular") } diff --git a/Widget/Toolbar/ToolbarData.swift b/Widget/Toolbar/ToolbarData.swift deleted file mode 100644 index 0306f1d911..0000000000 --- a/Widget/Toolbar/ToolbarData.swift +++ /dev/null @@ -1,46 +0,0 @@ -// SPDX-FileCopyrightText: Nextcloud GmbH -// SPDX-FileCopyrightText: 2022 Marino Faggiana -// SPDX-License-Identifier: GPL-3.0-or-later - -import UIKit -import WidgetKit -import NextcloudKit - -struct ToolbarDataEntry: TimelineEntry { - let date: Date - let isPlaceholder: Bool - let userId: String - let url: String - let account: String - let footerImage: String - let footerText: String -} - -func getToolbarDataEntry(isPreview: Bool, completion: @escaping (_ entry: ToolbarDataEntry) -> Void) { - var userId = "" - var url = "" - var account = "" - let versionApp = NCUtility().getVersionMaintenance() - - if let groupDefaults = UserDefaults(suiteName: NCBrandOptions.shared.capabilitiesGroup), - let lastVersion = groupDefaults.string(forKey: NCGlobal.shared.udLastVersion), - lastVersion != versionApp { - return completion(ToolbarDataEntry(date: Date(), isPlaceholder: true, userId: userId, url: url, account: account, footerImage: "xmark.icloud", footerText: NSLocalizedString("_version_mismatch_error_", comment: ""))) - } - - if isPreview { - return completion(ToolbarDataEntry(date: Date(), isPlaceholder: true, userId: userId, url: url, account: account, footerImage: "checkmark.icloud", footerText: NCBrandOptions.shared.brand + " toolbar")) - } - - if let activeTableAccount = NCManageDatabase.shared.getActiveTableAccount() { - userId = activeTableAccount.userId - url = activeTableAccount.urlBase - account = activeTableAccount.account - } - - if NCManageDatabase.shared.getActiveTableAccount() == nil { - return completion(ToolbarDataEntry(date: Date(), isPlaceholder: true, userId: userId, url: url, account: account, footerImage: "xmark.icloud", footerText: NSLocalizedString("_no_active_account_", value: "No account found", comment: ""))) - } - - completion(ToolbarDataEntry(date: Date(), isPlaceholder: false, userId: userId, url: url, account: account, footerImage: "checkmark.icloud", footerText: NCBrandOptions.shared.brand + " toolbar")) -} diff --git a/Widget/Toolbar/ToolbarWidgetProvider.swift b/Widget/Toolbar/ToolbarWidgetProvider.swift deleted file mode 100644 index f9bba1ba47..0000000000 --- a/Widget/Toolbar/ToolbarWidgetProvider.swift +++ /dev/null @@ -1,28 +0,0 @@ -// SPDX-FileCopyrightText: Nextcloud GmbH -// SPDX-FileCopyrightText: 2022 Marino Faggiana -// SPDX-License-Identifier: GPL-3.0-or-later - -import UIKit -import WidgetKit -import SwiftUI - -struct ToolbarWidgetProvider: TimelineProvider { - typealias Entry = ToolbarDataEntry - - func placeholder(in context: Context) -> Entry { - return Entry(date: Date(), isPlaceholder: true, userId: "", url: "", account: "", footerImage: "checkmark.icloud", footerText: NCBrandOptions.shared.brand + " toolbar") - } - - func getSnapshot(in context: Context, completion: @escaping (Entry) -> Void) { - getToolbarDataEntry(isPreview: false) { entry in - completion(entry) - } - } - - func getTimeline(in context: Context, completion: @escaping (Timeline) -> Void) { - getToolbarDataEntry(isPreview: context.isPreview) { entry in - let timeLine = Timeline(entries: [entry], policy: .atEnd) - completion(timeLine) - } - } -} diff --git a/Widget/Toolbar/ToolbarWidgetView.swift b/Widget/Toolbar/ToolbarWidgetView.swift deleted file mode 100644 index f45da7637f..0000000000 --- a/Widget/Toolbar/ToolbarWidgetView.swift +++ /dev/null @@ -1,109 +0,0 @@ -// SPDX-FileCopyrightText: Nextcloud GmbH -// SPDX-FileCopyrightText: 2022 Marino Faggiana -// SPDX-License-Identifier: GPL-3.0-or-later - -import SwiftUI -import WidgetKit - -struct ToolbarWidgetView: View { - var entry: ToolbarDataEntry - - @ViewBuilder - var body: some View { - mainContent - .containerBackground(Color.black, for: .widget) - } - - private var mainContent: some View { - let parameterLink = "&user=\(entry.userId)&url=\(entry.url)" - let safeUrl = { (base: String) in - URL(string: base + parameterLink) ?? URL(string: base)! - } - let linkNoAction = safeUrl(NCGlobal.shared.widgetActionNoAction) - let linkActionUploadAsset = safeUrl(NCGlobal.shared.widgetActionUploadAsset) - let linkActionScanDocument = safeUrl(NCGlobal.shared.widgetActionScanDocument) - let linkActionTextDocument = safeUrl(NCGlobal.shared.widgetActionTextDocument) - let linkActionVoiceMemo = safeUrl(NCGlobal.shared.widgetActionVoiceMemo) - let sizeButton: CGFloat = 65 - - return GeometryReader { geo in - ZStack(alignment: .topLeading) { - HStack(spacing: 0) { - Link(destination: entry.isPlaceholder ? linkNoAction : linkActionUploadAsset, label: { - Image(systemName: "photo.badge.plus") - .resizable() - .renderingMode(.template) - .foregroundColor(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getText(account: entry.account))) - .padding() - .background(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getElement(account: entry.account))) - .clipShape(Circle()) - .scaledToFit() - .frame(width: geo.size.width / 4, height: sizeButton) - }) - - Link(destination: entry.isPlaceholder ? linkNoAction : linkActionScanDocument, label: { - Image(systemName: "doc.text.viewfinder") - .resizable() - .renderingMode(.template) - .font(Font.system(.body).weight(.light)) - .foregroundColor(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getText(account: entry.account))) - .padding() - .background(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getElement(account: entry.account))) - .clipShape(Circle()) - .scaledToFit() - .frame(width: geo.size.width / 4, height: sizeButton) - }) - - Link(destination: entry.isPlaceholder ? linkNoAction : linkActionTextDocument, label: { - Image("note.text") - .resizable() - .renderingMode(.template) - .foregroundColor(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getText(account: entry.account))) - .padding() - .background(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getElement(account: entry.account))) - .clipShape(Circle()) - .scaledToFit() - .frame(width: geo.size.width / 4, height: sizeButton) - }) - - Link(destination: entry.isPlaceholder ? linkNoAction : linkActionVoiceMemo, label: { - Image(systemName: "mic.fill") - .resizable() - .renderingMode(.template) - .scaledToFit() - .foregroundColor(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getText(account: entry.account))) - .frame(width: sizeButton - 32, height: sizeButton - 32) - .padding(16) - .background(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getElement(account: entry.account))) - .clipShape(Circle()) - .frame(width: geo.size.width / 4, height: sizeButton) - }) - } - .frame(width: geo.size.width, height: geo.size.height, alignment: .center) - .redacted(reason: entry.isPlaceholder ? .placeholder : []) - - HStack { - Image(systemName: entry.footerImage) - .resizable() - .font(Font.system(.body).weight(.light)) - .scaledToFit() - .frame(width: 15, height: 15) - .foregroundColor(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getElement(account: entry.account))) - - Text(entry.footerText) - .font(.caption2) - .padding(.trailing, 13.0) - .foregroundColor(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getElement(account: entry.account))) - } - .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottom) - } - } - } -} - -struct ToolbarWidget_Previews: PreviewProvider { - static var previews: some View { - let entry = ToolbarDataEntry(date: Date(), isPlaceholder: false, userId: "", url: "", account: "", footerImage: "checkmark.icloud", footerText: NCBrandOptions.shared.brand + " toolbar") - ToolbarWidgetView(entry: entry).previewContext(WidgetPreviewContext(family: .systemMedium)) - } -} diff --git a/Widget/Widget.swift b/Widget/Widget.swift index 726508be02..a81463be27 100644 --- a/Widget/Widget.swift +++ b/Widget/Widget.swift @@ -12,7 +12,6 @@ struct NextcloudWidgetBundle: WidgetBundle { var body: some Widget { DashboardWidget() FilesWidget() - ToolbarWidget() LockscreenWidget() } } @@ -27,9 +26,7 @@ struct DashboardWidget: Widget { .supportedFamilies([.systemLarge]) .configurationDisplayName("Dashboard") .description(NSLocalizedString("_description_dashboardwidget_", comment: "")) -#if !targetEnvironment(simulator) .contentMarginsDisabled() -#endif } } @@ -47,22 +44,6 @@ struct FilesWidget: Widget { } } -struct ToolbarWidget: Widget { - let kind: String = "ToolbarWidget" - - var body: some WidgetConfiguration { - StaticConfiguration(kind: kind, provider: ToolbarWidgetProvider()) { entry in - ToolbarWidgetView(entry: entry) - } - .supportedFamilies([.systemMedium]) - .configurationDisplayName("Toolbar") - .description(NSLocalizedString("_description_toolbarwidget_", comment: "")) -#if !targetEnvironment(simulator) - .contentMarginsDisabled() -#endif - } -} - struct LockscreenWidget: Widget { let kind: String = "LockscreenWidget" diff --git a/iOSClient/Data/NCManageDatabase+DashboardWidget.swift b/iOSClient/Data/NCManageDatabase+DashboardWidget.swift index fb8714c5ca..30c7abac28 100644 --- a/iOSClient/Data/NCManageDatabase+DashboardWidget.swift +++ b/iOSClient/Data/NCManageDatabase+DashboardWidget.swift @@ -7,6 +7,12 @@ import UIKit import RealmSwift import NextcloudKit +enum DashboardItemAPIVersion: Int, PersistableEnum { + case unsupported = 0 + case v1 = 1 + case v2 = 2 +} + class tableDashboardWidget: Object { @Persisted(primaryKey: true) var index = "" @Persisted var account = "" @@ -17,6 +23,7 @@ class tableDashboardWidget: Object { @Persisted var iconUrl: String? @Persisted var widgetUrl: String? @Persisted var itemIconsRound: Bool = false + @Persisted var preferredItemAPIVersion: DashboardItemAPIVersion? } class tableDashboardWidgetButton: Object { @@ -32,7 +39,9 @@ extension NCManageDatabase { // MARK: - Realm Write - func addDashboardWidgetAsync(account: String, dashboardWidgets: [NCCDashboardWidget]) async { + func addDashboardWidgetAsync(account: String, + dashboardWidgets: [NCCDashboardWidget], + preferredItemAPIVersions: [String: DashboardItemAPIVersion]) async { await core.performRealmWriteAsync { realm in // Remove existing widgets for the account realm.delete(realm.objects(tableDashboardWidget.self).filter("account == %@", account)) @@ -50,6 +59,7 @@ extension NCManageDatabase { widgetObject.iconUrl = widget.iconUrl widgetObject.widgetUrl = widget.widgetUrl widgetObject.itemIconsRound = widget.itemIconsRound + widgetObject.preferredItemAPIVersion = preferredItemAPIVersions[widget.id] realm.add(widgetObject, update: .all) diff --git a/iOSClient/NCGlobal.swift b/iOSClient/NCGlobal.swift index 3bdc3d9405..4c5ffed945 100644 --- a/iOSClient/NCGlobal.swift +++ b/iOSClient/NCGlobal.swift @@ -305,14 +305,6 @@ final class NCGlobal: Sendable { let actionTextDocument = "create-text-document" let actionVoiceMemo = "create-voice-memo" - // WIDGET ACTION - // - let widgetActionNoAction = "nextcloud://open-action?action=no-action" - let widgetActionUploadAsset = "nextcloud://open-action?action=upload-asset" - let widgetActionScanDocument = "nextcloud://open-action?action=add-scan-document" - let widgetActionTextDocument = "nextcloud://open-action?action=create-text-document" - let widgetActionVoiceMemo = "nextcloud://open-action?action=create-voice-memo" - // APPCONFIG // let configuration_brand = "brand" diff --git a/iOSClient/Networking/NCService.swift b/iOSClient/Networking/NCService.swift index 0f252a11ce..54e8ae4a98 100644 --- a/iOSClient/Networking/NCService.swift +++ b/iOSClient/Networking/NCService.swift @@ -116,7 +116,12 @@ class NCService: NSObject { let resultsDashboardWidget = await NextcloudKit.shared.getDashboardWidgetAsync(account: account) if resultsDashboardWidget.error == .success, let dashboardWidgets = resultsDashboardWidget.dashboardWidgets { - await NCManageDatabase.shared.addDashboardWidgetAsync(account: account, dashboardWidgets: dashboardWidgets) + let catalog = resultsDashboardWidget.responseData?.data.flatMap { + try? JSONDecoder().decode(DashboardCatalogResponse.self, from: $0) + } + await NCManageDatabase.shared.addDashboardWidgetAsync(account: account, + dashboardWidgets: dashboardWidgets, + preferredItemAPIVersions: catalog?.preferredItemAPIVersions ?? [:]) for widget in dashboardWidgets { if let url = URL(string: widget.iconUrl), let fileName = widget.iconClass { @@ -394,3 +399,36 @@ class NCService: NSObject { } } } + +private struct DashboardCatalogResponse: Decodable { + struct OCS: Decodable { + struct Module: Decodable { + let id: String? + let itemAPIVersions: [Int]? + + private enum CodingKeys: String, CodingKey { + case id + case itemAPIVersions = "item_api_versions" + } + + var preferredItemAPIVersion: DashboardItemAPIVersion? { + guard let itemAPIVersions else { return nil } + if itemAPIVersions.contains(DashboardItemAPIVersion.v2.rawValue) { return .v2 } + if itemAPIVersions.contains(DashboardItemAPIVersion.v1.rawValue) { return .v1 } + return .unsupported + } + } + + let data: [String: Module] + } + + let ocs: OCS + + var preferredItemAPIVersions: [String: DashboardItemAPIVersion] { + ocs.data.values.reduce(into: [:]) { versions, module in + if let id = module.id { + versions[id] = module.preferredItemAPIVersion + } + } + } +} diff --git a/iOSClient/SceneDelegate.swift b/iOSClient/SceneDelegate.swift index 42e8edc394..43294a619b 100644 --- a/iOSClient/SceneDelegate.swift +++ b/iOSClient/SceneDelegate.swift @@ -16,8 +16,8 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { private let appDelegate = UIApplication.shared.delegate as? AppDelegate private var privacyProtectionWindow: UIWindow? private var passcodeWindow: NCPasscodeWindow? - private var pendingWidgetFileURL: URL? - private var widgetFileOpenTask: Task? + private var pendingWidgetURL: URL? + private var widgetOpenTask: Task? private let global = NCGlobal.shared private let alreadyMigratedMultiDomains = UserDefaults.standard.bool(forKey: NCGlobal.shared.udMigrationMultiDomains) @@ -25,7 +25,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { guard let windowScene = (scene as? UIWindowScene) else { return } - pendingWidgetFileURL = connectionOptions.urlContexts.map(\.url).first(where: isWidgetFileURL) + pendingWidgetURL = connectionOptions.urlContexts.map(\.url).first(where: isWidgetURL) NotificationCenter.default.removeObserver(self, name: NCPasscodeModel.lockoutNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(passcodeLockoutStarted), name: NCPasscodeModel.lockoutNotification, object: nil) @@ -198,7 +198,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { if activateSceneForAccount { self.activateSceneForAccount(scene, account: activeTblAccount.account, controller: controller) } - openPendingWidgetFile(in: scene) + openPendingWidgetURL(in: scene) } // Clean orphaned FP Domains @@ -210,8 +210,8 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { func sceneDidDisconnect(_ scene: UIScene) { guard let windowScene = scene as? UIWindowScene else { return } - widgetFileOpenTask?.cancel() - pendingWidgetFileURL = nil + widgetOpenTask?.cancel() + pendingWidgetURL = nil passcodeWindow?.hide() passcodeWindow = nil @@ -234,7 +234,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { func sceneDidBecomeActive(_ scene: UIScene) { hidePrivacyProtectionWindow() - openPendingWidgetFile(in: scene) + openPendingWidgetURL(in: scene) if !NextcloudKit.shared.isNetworkReachable(), let windowScenee = SceneManager.shared.getWindow(scene: scene)?.windowScene { @@ -324,10 +324,10 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { func scene(_ scene: UIScene, openURLContexts URLContexts: Set) { guard let url = URLContexts.first?.url else { return } - if isWidgetFileURL(url) { - widgetFileOpenTask?.cancel() - pendingWidgetFileURL = url - openPendingWidgetFile(in: scene) + if isWidgetURL(url) { + widgetOpenTask?.cancel() + pendingWidgetURL = url + openPendingWidgetURL(in: scene) return } @@ -480,20 +480,73 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { } } - private func isWidgetFileURL(_ url: URL) -> Bool { - url.scheme == global.appScheme && url.host == "open-file" + private func isWidgetURL(_ url: URL) -> Bool { + guard url.scheme == global.appScheme else { return false } + + switch url.host { + case "open-file", DeepLink.openFavorites.rawValue, DeepLink.openUrl.rawValue: + return true + default: + return false + } } - private func openPendingWidgetFile(in scene: UIScene) { - guard let url = pendingWidgetFileURL, + private func openPendingWidgetURL(in scene: UIScene) { + guard let url = pendingWidgetURL, passcodeWindow == nil, scene.activationState == .foregroundActive, let controller = window?.rootViewController as? NCMainTabBarController else { return } - pendingWidgetFileURL = nil - widgetFileOpenTask = Task { @MainActor in - await openWidgetFile(url, scene: scene, controller: controller) + pendingWidgetURL = nil + widgetOpenTask = Task { @MainActor in + guard !Task.isCancelled else { return } + + switch url.host { + case DeepLink.openFavorites.rawValue: + await openWidgetFavorites(url, scene: scene, controller: controller) + case DeepLink.openUrl.rawValue: + NCDeepLinkHandler().parseDeepLink(url, controller: controller) + case "open-file": + await openWidgetFile(url, scene: scene, controller: controller) + default: + break + } + } + } + + private func openWidgetFavorites(_ url: URL, scene: UIScene, controller: NCMainTabBarController) async { + let account = URLComponents(url: url, resolvingAgainstBaseURL: false)? + .queryItems?.first(where: { $0.name == "account" })?.value + + if let account, account != controller.account { + let target = await NCManageDatabase.shared.getTableAccountAsync(account: account) + guard !Task.isCancelled, window?.rootViewController === controller else { return } + if passcodeWindow != nil || scene.activationState != .foregroundActive { + pendingWidgetURL = url + return + } + + guard target != nil else { + let message = String(format: NSLocalizedString("_account_does_not_exist_", comment: ""), account) + let alert = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: message, preferredStyle: .alert) + alert.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default)) + controller.present(alert, animated: true) + return + } + + await NCAccount().changeAccount(account, userProfile: nil, controller: controller) + } + + guard !Task.isCancelled, window?.rootViewController === controller, + account == nil || controller.account == account else { return } + + if passcodeWindow != nil || scene.activationState != .foregroundActive { + pendingWidgetURL = url + return } + + NCDeepLinkHandler().handleDeepLink(.openFavorites, controller: controller) + (controller.selectedViewController as? UINavigationController)?.popToRootViewController(animated: false) } private func openWidgetFile(_ url: URL, scene: UIScene, controller: NCMainTabBarController) async { @@ -509,7 +562,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { let accounts = await NCManageDatabase.shared.getAllTableAccountAsync() guard !Task.isCancelled, window?.rootViewController === controller else { return } if passcodeWindow != nil || scene.activationState != .foregroundActive { - pendingWidgetFileURL = url + pendingWidgetURL = url return } @@ -534,7 +587,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { guard !Task.isCancelled, window?.rootViewController === controller, controller.account == target.account else { return } if passcodeWindow != nil || scene.activationState != .foregroundActive { - pendingWidgetFileURL = url + pendingWidgetURL = url return } @@ -554,7 +607,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { controller.account == target.account else { return } if passcodeWindow != nil || scene.activationState != .foregroundActive { - pendingWidgetFileURL = url + pendingWidgetURL = url return } @@ -607,8 +660,8 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { self.passcodeWindow = nil switch result { case .authenticated: - if self.pendingWidgetFileURL != nil, let scene = self.window?.windowScene { - self.openPendingWidgetFile(in: scene) + if self.pendingWidgetURL != nil, let scene = self.window?.windowScene { + self.openPendingWidgetURL(in: scene) } else if NCPreferences().accountRequest, let controller, self.window?.rootViewController === controller, @@ -616,8 +669,8 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { self.requestedAccount(controller: controller) } case .reset: - self.widgetFileOpenTask?.cancel() - self.pendingWidgetFileURL = nil + self.widgetOpenTask?.cancel() + self.pendingWidgetURL = nil self.appDelegate?.resetApplication() case .cancelled, .configured, .disabled: break @@ -643,7 +696,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { } if !requestPasscodeIfNeeded(controller: controller), - pendingWidgetFileURL == nil, + pendingWidgetURL == nil, NCPreferences().accountRequest { requestedAccount(controller: controller) } diff --git a/iOSClient/Supporting Files/en.lproj/Localizable.strings b/iOSClient/Supporting Files/en.lproj/Localizable.strings index eb582eb9ca..cd77e60250 100644 --- a/iOSClient/Supporting Files/en.lproj/Localizable.strings +++ b/iOSClient/Supporting Files/en.lproj/Localizable.strings @@ -524,8 +524,10 @@ "_widget_no_recent_files_" = "No recent files"; "_widget_recent_files_description_" = "View and open your recent files."; "_widget_refresh_files_" = "Refresh recent files"; -"_widget_files_updated_at_" = "Updated %@"; -"_description_toolbarwidget_" = "A toolbar to speed up your operations."; +"_widget_refresh_dashboard_" = "Refresh Dashboard"; +"_widget_dashboard_available_on_web_" = "Available on the web"; +"_widget_dashboard_open_in_browser_" = "Open in browser"; +"_widget_updated_at_" = "Updated %@"; "_title_lockscreenwidget_" = "Status"; "_description_lockscreenwidget_" = "Keep an eye on available space and recent activity"; From 45dc76230e9a1e33b7c8b182bd67ce80918624ce Mon Sep 17 00:00:00 2001 From: Marino Faggiana Date: Mon, 16 Nov 2026 11:58:47 +0100 Subject: [PATCH 4/7] fix: hide unsupported Notes and Circles dashboard actions Signed-off-by: Marino Faggiana --- Widget/Dashboard/DashboardData.swift | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Widget/Dashboard/DashboardData.swift b/Widget/Dashboard/DashboardData.swift index def2e87529..241a9b234f 100644 --- a/Widget/Dashboard/DashboardData.swift +++ b/Widget/Dashboard/DashboardData.swift @@ -157,7 +157,12 @@ func getDashboardDataEntry(configuration: DashboardIntent, displaySize: CGSize) let title = module?.title ?? moduleId let baseURL = URL(string: account.urlBase) let actions = (moduleButtons ?? []).compactMap { button -> DashboardAction? in - guard moduleId != "notes" || button.type != "new" else { return nil } + switch (moduleId, button.type) { + case ("notes", "new"), ("notes", "more"), ("circles", "setup"): + return nil + default: + break + } let isMore = button.type == "more" let url: URL? From 100ed9a42c65762934d92273526cf2a64a28baaa Mon Sep 17 00:00:00 2001 From: Marino Faggiana Date: Mon, 16 Nov 2026 12:08:10 +0100 Subject: [PATCH 5/7] fix: secure dashboard icon downloads and correct widget actions Restrict icon requests and redirects to the account server. Preserve Favorites and Circles actions when all rows fit, respect the selected account for default modules, and remove unused widget assets. Signed-off-by: Marino Faggiana --- Nextcloud.xcodeproj/project.pbxproj | 4 -- .../AccentColor.colorset/Contents.json | 11 ----- .../AppIcon.imageset/Contents.json | 11 ----- Widget/Assets.xcassets/Contents.json | 6 --- .../WidgetBackground.colorset/Contents.json | 11 ----- .../activity.imageset/Contents.json | 12 ----- .../activity.imageset/activity.png | Bin 18754 -> 0 bytes Widget/Dashboard/DashboardData.swift | 12 +++-- Widget/Dashboard/DashboardWidgetView.swift | 2 +- .../IntentHandler.swift | 41 ++++++++---------- iOSClient/Networking/NCService.swift | 40 ++++++++--------- iOSClient/Utility/NCUtility+Image.swift | 32 ++++++++++++++ 12 files changed, 73 insertions(+), 109 deletions(-) delete mode 100644 Widget/Assets.xcassets/AccentColor.colorset/Contents.json delete mode 100644 Widget/Assets.xcassets/AppIcon.imageset/Contents.json delete mode 100644 Widget/Assets.xcassets/Contents.json delete mode 100644 Widget/Assets.xcassets/WidgetBackground.colorset/Contents.json delete mode 100644 Widget/Assets.xcassets/activity.imageset/Contents.json delete mode 100644 Widget/Assets.xcassets/activity.imageset/activity.png diff --git a/Nextcloud.xcodeproj/project.pbxproj b/Nextcloud.xcodeproj/project.pbxproj index 242fca58e1..eb8d5a9f73 100644 --- a/Nextcloud.xcodeproj/project.pbxproj +++ b/Nextcloud.xcodeproj/project.pbxproj @@ -385,7 +385,6 @@ F733598125C1C188002ABA72 /* NCAskAuthorization.swift in Sources */ = {isa = PBXBuildFile; fileRef = F733598025C1C188002ABA72 /* NCAskAuthorization.swift */; }; F7346E1628B0EF5C006CE2D2 /* Widget.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7346E1528B0EF5C006CE2D2 /* Widget.swift */; }; F7346E1C28B0EF5E006CE2D2 /* Widget.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = F7346E1028B0EF5B006CE2D2 /* Widget.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; - F7346E2328B0FEBA006CE2D2 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = F7346E2228B0FEBA006CE2D2 /* Assets.xcassets */; }; F734B06628E75C0100E180D5 /* TLPhotoPicker in Frameworks */ = {isa = PBXBuildFile; productRef = F734B06528E75C0100E180D5 /* TLPhotoPicker */; }; F7362A1F220C853A005101B5 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = F7362A1E220C853A005101B5 /* LaunchScreen.storyboard */; }; F7381EE1218218C9000B1560 /* NCOffline.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7381EDA218218C9000B1560 /* NCOffline.swift */; }; @@ -1593,7 +1592,6 @@ F7346E1028B0EF5B006CE2D2 /* Widget.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = Widget.appex; sourceTree = BUILT_PRODUCTS_DIR; }; F7346E1528B0EF5C006CE2D2 /* Widget.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Widget.swift; sourceTree = ""; }; F7346E2028B0FA3A006CE2D2 /* Widget-Brinding-header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Widget-Brinding-header.h"; sourceTree = ""; }; - F7346E2228B0FEBA006CE2D2 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; F7362A1E220C853A005101B5 /* LaunchScreen.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; path = LaunchScreen.storyboard; sourceTree = ""; }; F7381EDA218218C9000B1560 /* NCOffline.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NCOffline.swift; sourceTree = ""; }; F7381EDE218218C9000B1560 /* NCOffline.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; path = NCOffline.storyboard; sourceTree = ""; }; @@ -2729,7 +2727,6 @@ F7346E1428B0EF5B006CE2D2 /* Widget */ = { isa = PBXGroup; children = ( - F7346E2228B0FEBA006CE2D2 /* Assets.xcassets */, F72EA95528B7BAD100C88F0C /* Dashboard */, F72EA95628B7BAE700C88F0C /* Files */, F76DEE9A28F808BC0041B1C9 /* Lockscreen */, @@ -4478,7 +4475,6 @@ F7C7B25028B8AD4500E7115D /* Localizable.strings in Resources */, F7E4022A2BA85D1D007E5609 /* PrivacyInfo.xcprivacy in Resources */, AA517B832D660EFE00F8D37C /* Localizable.stringsdict in Resources */, - F7346E2328B0FEBA006CE2D2 /* Assets.xcassets in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/Widget/Assets.xcassets/AccentColor.colorset/Contents.json b/Widget/Assets.xcassets/AccentColor.colorset/Contents.json deleted file mode 100644 index eb87897008..0000000000 --- a/Widget/Assets.xcassets/AccentColor.colorset/Contents.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "colors" : [ - { - "idiom" : "universal" - } - ], - "info" : { - "author" : "xcode", - "version" : 1 - } -} diff --git a/Widget/Assets.xcassets/AppIcon.imageset/Contents.json b/Widget/Assets.xcassets/AppIcon.imageset/Contents.json deleted file mode 100644 index 6fe332016d..0000000000 --- a/Widget/Assets.xcassets/AppIcon.imageset/Contents.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal" - } - ], - "info" : { - "author" : "xcode", - "version" : 1 - } -} diff --git a/Widget/Assets.xcassets/Contents.json b/Widget/Assets.xcassets/Contents.json deleted file mode 100644 index 73c00596a7..0000000000 --- a/Widget/Assets.xcassets/Contents.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "info" : { - "author" : "xcode", - "version" : 1 - } -} diff --git a/Widget/Assets.xcassets/WidgetBackground.colorset/Contents.json b/Widget/Assets.xcassets/WidgetBackground.colorset/Contents.json deleted file mode 100644 index eb87897008..0000000000 --- a/Widget/Assets.xcassets/WidgetBackground.colorset/Contents.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "colors" : [ - { - "idiom" : "universal" - } - ], - "info" : { - "author" : "xcode", - "version" : 1 - } -} diff --git a/Widget/Assets.xcassets/activity.imageset/Contents.json b/Widget/Assets.xcassets/activity.imageset/Contents.json deleted file mode 100644 index e507da5dc6..0000000000 --- a/Widget/Assets.xcassets/activity.imageset/Contents.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "images" : [ - { - "filename" : "activity.png", - "idiom" : "universal" - } - ], - "info" : { - "author" : "xcode", - "version" : 1 - } -} diff --git a/Widget/Assets.xcassets/activity.imageset/activity.png b/Widget/Assets.xcassets/activity.imageset/activity.png deleted file mode 100644 index 8c2efb61510c977abf6524f8a2a006823cf65fed..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 18754 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 MHrtxJ#pU<^59gg26aWAK diff --git a/Widget/Dashboard/DashboardData.swift b/Widget/Dashboard/DashboardData.swift index 241a9b234f..08ef931fcc 100644 --- a/Widget/Dashboard/DashboardData.swift +++ b/Widget/Dashboard/DashboardData.swift @@ -35,7 +35,7 @@ struct DashboardAction: Identifiable, Sendable { let id: String let title: String let url: URL - let isMore: Bool + let hidesWhenAllRowsFit: Bool } private struct DashboardModuleItem: Decodable { @@ -176,7 +176,8 @@ func getDashboardDataEntry(configuration: DashboardIntent, displaySize: CGSize) url = dashboardWebURL(button.link, relativeTo: baseURL) } guard let url else { return nil } - return DashboardAction(id: button.index, title: button.text, url: url, isMore: isMore) + let hidesWhenAllRowsFit = isMore && moduleId != "files-favorites" && moduleId != "circles" + return DashboardAction(id: button.index, title: button.text, url: url, hidesWhenAllRowsFit: hidesWhenAllRowsFit) } let titleImage: UIImage? @@ -233,11 +234,8 @@ func getDashboardDataEntry(configuration: DashboardIntent, displaySize: CGSize) isRound = false } else if iconURL.pathComponents.contains("getCalendarDotSvg") { calendarColor = UIColor(hex: (iconURL.lastPathComponent as NSString).deletingPathExtension) - } else { - let preview = await NextcloudKit.shared.downloadPreviewAsync(url: iconURL, account: account.account, options: options) - if preview.error == .success, let data = preview.responseData?.data { - icon = UIImage(data: data) - } + } else if let data = await utility.downloadDashboardIcon(from: iconURL, account: account.account) { + icon = UIImage(data: data) } } diff --git a/Widget/Dashboard/DashboardWidgetView.swift b/Widget/Dashboard/DashboardWidgetView.swift index c6409549c6..105d73f154 100644 --- a/Widget/Dashboard/DashboardWidgetView.swift +++ b/Widget/Dashboard/DashboardWidgetView.swift @@ -28,7 +28,7 @@ nonisolated enum DashboardWidgetLayout { totalRows: Int, height: CGFloat, loadedRows: Int = .max) -> [DashboardAction] { - let otherActions = actions.filter { !$0.isMore } + let otherActions = actions.filter { !$0.hidesWhenAllRowsFit } let rowsWithoutMore = rowCount(for: height, hasActions: !otherActions.isEmpty) return totalRows > min(rowsWithoutMore, loadedRows) ? actions : otherActions } diff --git a/WidgetDashboardIntentHandler/IntentHandler.swift b/WidgetDashboardIntentHandler/IntentHandler.swift index 53462da12a..dc4fe5df0f 100644 --- a/WidgetDashboardIntentHandler/IntentHandler.swift +++ b/WidgetDashboardIntentHandler/IntentHandler.swift @@ -41,37 +41,30 @@ class IntentHandler: INExtension, DashboardIntentHandling, AccountIntentHandling // Application func provideApplicationsOptionsCollection(for intent: DashboardIntent, with completion: @escaping (INObjectCollection?, Error?) -> Void) { - var applications: [Applications] = [] - var activeTableAccount: tableAccount? - - let accountIdentifier: String = intent.accounts?.identifier ?? "active" - if accountIdentifier == "active" { - activeTableAccount = NCManageDatabase.shared.getActiveTableAccount() - } else { - activeTableAccount = NCManageDatabase.shared.getTableAccount(predicate: NSPredicate(format: "account == %@", accountIdentifier)) + guard let account = dashboardAccount(for: intent) else { + completion(nil, nil) + return } - guard let activeTableAccount else { - return completion(nil, nil) + let applications = NCManageDatabase.shared.getDashboardWidgetApplications(account: account.account).map { + Applications(identifier: $0.id, display: $0.title) } - - let results = NCManageDatabase.shared.getDashboardWidgetApplications(account: activeTableAccount.account) - for result in results { - let application = Applications(identifier: result.id, display: result.title) - applications.append(application) - } - completion(INObjectCollection(items: applications), nil) } func defaultApplications(for intent: DashboardIntent) -> Applications? { - guard let account = NCManageDatabase.shared.getActiveTableAccount() else { - return nil - } - if let result = NCManageDatabase.shared.getDashboardWidgetApplications(account: account.account).first { - return Applications(identifier: result.id, display: result.title) - } - return nil + guard let account = dashboardAccount(for: intent), + let module = NCManageDatabase.shared.getDashboardWidgetApplications(account: account.account).first else { return nil } + + return Applications(identifier: module.id, display: module.title) + } + + private func dashboardAccount(for intent: DashboardIntent) -> tableAccount? { + let database = NCManageDatabase.shared + let accountIdentifier = intent.accounts?.identifier ?? "active" + return accountIdentifier == "active" + ? database.getActiveTableAccount() + : database.getTableAccount(account: accountIdentifier) } // Account diff --git a/iOSClient/Networking/NCService.swift b/iOSClient/Networking/NCService.swift index 54e8ae4a98..c2727eaee0 100644 --- a/iOSClient/Networking/NCService.swift +++ b/iOSClient/Networking/NCService.swift @@ -123,28 +123,24 @@ class NCService: NSObject { dashboardWidgets: dashboardWidgets, preferredItemAPIVersions: catalog?.preferredItemAPIVersions ?? [:]) for widget in dashboardWidgets { - if let url = URL(string: widget.iconUrl), - let fileName = widget.iconClass { - let resultsDownloadPreview = await NextcloudKit.shared.downloadPreviewAsync(url: url, account: account) - if resultsDownloadPreview.error == .success, - let data = resultsDownloadPreview.responseData?.data { - var image: UIImage? - let size = CGSize(width: 256, height: 256) - - if let uiImage = UIImage(data: data)?.resizeImage(size: size) { - image = uiImage - } else if let svgImage = try? await NCSVGRenderer().renderSVGToUIImage(svgData: data, size: size) { - image = svgImage - } - - if let image { - let filePath = (self.utilityFileSystem.directoryUserData as NSString).appendingPathComponent(fileName + ".png") - do { - try image.pngData()?.write(to: URL(fileURLWithPath: filePath), options: .atomic) - } catch { - print("Failed to write image to disk: \(error.localizedDescription)") - } - } + guard let url = URL(string: widget.iconUrl), + let fileName = widget.iconClass, + let data = await utility.downloadDashboardIcon(from: url, account: account) else { continue } + + let size = CGSize(width: 256, height: 256) + let image: UIImage? + if let raster = UIImage(data: data)?.resizeImage(size: size) { + image = raster + } else { + image = try? await NCSVGRenderer().renderSVGToUIImage(svgData: data, size: size) + } + + if let image { + let filePath = (utilityFileSystem.directoryUserData as NSString).appendingPathComponent(fileName + ".png") + do { + try image.pngData()?.write(to: URL(fileURLWithPath: filePath), options: .atomic) + } catch { + print("Failed to write image to disk: \(error.localizedDescription)") } } } diff --git a/iOSClient/Utility/NCUtility+Image.swift b/iOSClient/Utility/NCUtility+Image.swift index 94e9dc459d..b715e7196a 100644 --- a/iOSClient/Utility/NCUtility+Image.swift +++ b/iOSClient/Utility/NCUtility+Image.swift @@ -5,12 +5,44 @@ import Foundation import UIKit import NextcloudKit +import Alamofire import PDFKit import Accelerate import CoreMedia import Photos extension NCUtility { + func downloadDashboardIcon(from url: URL, account: String) async -> Data? { + let networking = NextcloudKit.shared.nkCommonInstance + guard let session = networking.nksessions.session(forAccount: account), + let serverURL = URL(string: session.urlBase), + Self.isDashboardIconOnServer(url, serverURL: serverURL), + let headers = networking.getStandardHeaders(account: account) else { return nil } + + let redirector = Redirector(behavior: .modify { _, request, _ in + guard let destination = request.url, + Self.isDashboardIconOnServer(destination, serverURL: serverURL) else { return nil } + return request + }) + + return try? await session.sessionData.request(url, headers: headers) + .redirect(using: redirector) + .validate(statusCode: 200..<300) + .serializingData() + .value + } + + private nonisolated static func isDashboardIconOnServer(_ url: URL, serverURL: URL) -> Bool { + guard let scheme = url.scheme?.lowercased(), scheme == "http" || scheme == "https", + scheme == serverURL.scheme?.lowercased(), + let host = url.host?.lowercased(), !host.isEmpty, + host == serverURL.host?.lowercased(), + url.user == nil, url.password == nil else { return false } + + let defaultPort = scheme == "https" ? 443 : 80 + return (url.port ?? defaultPort) == (serverURL.port ?? defaultPort) + } + func loadImage(named imageName: String, colors: [UIColor]? = nil, size: CGFloat? = nil, From dcd905495cdc51be86dc4f4cb456674c1620cf1b Mon Sep 17 00:00:00 2001 From: Marino Faggiana Date: Mon, 16 Nov 2026 12:13:00 +0100 Subject: [PATCH 6/7] chore: clean up widget configuration and refresh package resolution Remove widget color settings and asset license annotations, and simplify the lock screen accessibility property declaration. Switch the OpenSSL pin to OpenSSL-Package and remove obsolete dependency pins. Signed-off-by: Marino Faggiana --- Nextcloud.xcodeproj/project.pbxproj | 4 -- .../xcshareddata/swiftpm/Package.resolved | 44 ++----------------- REUSE.toml | 4 +- Widget/Lockscreen/LockscreenData.swift | 2 +- 4 files changed, 7 insertions(+), 47 deletions(-) diff --git a/Nextcloud.xcodeproj/project.pbxproj b/Nextcloud.xcodeproj/project.pbxproj index 725552202c..b7eca39393 100644 --- a/Nextcloud.xcodeproj/project.pbxproj +++ b/Nextcloud.xcodeproj/project.pbxproj @@ -6267,8 +6267,6 @@ isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = YES; - ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; - ASSETCATALOG_COMPILER_WIDGET_BACKGROUND_COLOR_NAME = WidgetBackground; CLANG_ANALYZER_NONNULL = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; @@ -6301,8 +6299,6 @@ isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = YES; - ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; - ASSETCATALOG_COMPILER_WIDGET_BACKGROUND_COLOR_NAME = WidgetBackground; CLANG_ANALYZER_NONNULL = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; diff --git a/Nextcloud.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Nextcloud.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index 10fc3fdd33..c60b8ec71d 100644 --- a/Nextcloud.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/Nextcloud.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -1,5 +1,5 @@ { - "originHash" : "7880536aedfe5f5b326df402ac666a6126ac1b325106ab3eb7b6c78a6ef725ff", + "originHash" : "5236b0018852b3d5fa374f118d9825d5acd8f4ce80430d339706d09182995ba2", "pins" : [ { "identity" : "abseil-cpp-binary", @@ -209,11 +209,11 @@ } }, { - "identity" : "openssl", + "identity" : "openssl-package", "kind" : "remoteSourceControl", - "location" : "https://github.com/krzyzanowskim/OpenSSL", + "location" : "https://github.com/krzyzanowskim/OpenSSL-Package", "state" : { - "revision" : "0a6149bff4fb00921ce0ec1811f726b166638095", + "revision" : "4ac3f9a68731cb3cf736a591814bad9a7a2008c8", "version" : "3.6.5000" } }, @@ -262,15 +262,6 @@ "version" : "20.0.6" } }, - { - "identity" : "swift-atomics", - "kind" : "remoteSourceControl", - "location" : "https://github.com/apple/swift-atomics.git", - "state" : { - "revision" : "0442cb5a3f98ab802acb777929fdb446bda11a34", - "version" : "1.3.1" - } - }, { "identity" : "swift-collections", "kind" : "remoteSourceControl", @@ -280,33 +271,6 @@ "version" : "1.7.6" } }, - { - "identity" : "swift-nio", - "kind" : "remoteSourceControl", - "location" : "https://github.com/apple/swift-nio.git", - "state" : { - "revision" : "2f58d8ef84438d6517fc78bcea2f8527e3c72936", - "version" : "2.105.0" - } - }, - { - "identity" : "swift-nio-ssl", - "kind" : "remoteSourceControl", - "location" : "https://github.com/apple/swift-nio-ssl", - "state" : { - "revision" : "322f3c2a4a21df31c84ca416bf65ee5e9059e440", - "version" : "2.37.5" - } - }, - { - "identity" : "swift-system", - "kind" : "remoteSourceControl", - "location" : "https://github.com/apple/swift-system.git", - "state" : { - "revision" : "640e5755b5826f4437eaeedd366fd776737db62c", - "version" : "1.9.0" - } - }, { "identity" : "swifter", "kind" : "remoteSourceControl", diff --git a/REUSE.toml b/REUSE.toml index 976a6d6713..86072d894e 100644 --- a/REUSE.toml +++ b/REUSE.toml @@ -30,7 +30,7 @@ SPDX-FileCopyrightText = "2016-2026 Nextcloud GmbH and Nextcloud contributors" SPDX-License-Identifier = "GPL-3.0-or-later" [[annotations]] -path = ["iOSClient/Images.xcassets/**", "Widget/Assets.xcassets/**", "Action Assistant/Images.xcassets/**"] +path = ["iOSClient/Images.xcassets/**", "Action Assistant/Images.xcassets/**"] precedence = "aggregate" SPDX-FileCopyrightText = "2016-2026 Nextcloud GmbH and Nextcloud contributors" SPDX-License-Identifier = "GPL-3.0-or-later" @@ -56,7 +56,7 @@ SPDX-License-Identifier = "GPL-3.0-or-later" # The Nextcloud name and logo are trademarks; see LICENSES/LicenseRef-NextcloudTrademarks.txt [[annotations]] -path = ["AppIcon.icon/**", "Brand/Custom.xcassets/AppIcon.appiconset/**", "Brand/Custom.xcassets/logo.imageset/**", "Action Assistant/Images.xcassets/AppIcon.appiconset/**", "Widget/Assets.xcassets/AppIcon.imageset/**", "iOSClient/Images.xcassets/logo.imageset/**"] +path = ["AppIcon.icon/**", "Brand/Custom.xcassets/AppIcon.appiconset/**", "Brand/Custom.xcassets/logo.imageset/**", "Action Assistant/Images.xcassets/AppIcon.appiconset/**", "iOSClient/Images.xcassets/logo.imageset/**"] precedence = "aggregate" SPDX-FileCopyrightText = "Nextcloud GmbH" SPDX-License-Identifier = "LicenseRef-NextcloudTrademarks" diff --git a/Widget/Lockscreen/LockscreenData.swift b/Widget/Lockscreen/LockscreenData.swift index e59232f0ec..33ff454973 100644 --- a/Widget/Lockscreen/LockscreenData.swift +++ b/Widget/Lockscreen/LockscreenData.swift @@ -15,7 +15,7 @@ struct LockscreenData: TimelineEntry { let quotaUsed: String let quotaTotal: String let error: Bool - var quotaTotalAccessibilityLabel: String? = nil + var quotaTotalAccessibilityLabel: String? } func getLockscreenDataEntry(configuration: AccountIntent?, isPreview: Bool, family: WidgetFamily, completion: @escaping (_ entry: LockscreenData) -> Void) { From 26951315b210eb268509eed0f51ef39be2377723 Mon Sep 17 00:00:00 2001 From: Marino Faggiana Date: Mon, 16 Nov 2026 12:16:40 +0100 Subject: [PATCH 7/7] fix: show sample content in widget previews Use non-placeholder sample entries for dashboard, files, and lock screen previews without fetching account data. Signed-off-by: Marino Faggiana --- Widget/Dashboard/DashboardData.swift | 16 +++++++++------- Widget/Dashboard/DashboardWidgetProvider.swift | 7 ++++--- Widget/Dashboard/DashboardWidgetView.swift | 2 +- Widget/Files/FilesWidgetProvider.swift | 10 +++++++--- Widget/Lockscreen/LockscreenData.swift | 6 +----- .../Lockscreen/LockscreenWidgetProvider.swift | 17 +++++++++++++++-- Widget/Lockscreen/LockscreenWidgetView.swift | 2 +- 7 files changed, 38 insertions(+), 22 deletions(-) diff --git a/Widget/Dashboard/DashboardData.swift b/Widget/Dashboard/DashboardData.swift index 08ef931fcc..59da003dce 100644 --- a/Widget/Dashboard/DashboardData.swift +++ b/Widget/Dashboard/DashboardData.swift @@ -80,15 +80,17 @@ private struct DashboardItemsResponse: Decodable { let ocs: OCS } -func dashboardPlaceholder(height: CGFloat, +func dashboardSampleEntry(height: CGFloat, title: String = "Dashboard", titleImage: UIImage? = UIImage(systemName: "rectangle.grid.2x2"), footerText: String = NCBrandOptions.shared.brand, - isError: Bool = false) -> DashboardDataEntry { + isError: Bool = false, + isPlaceholder: Bool = true) -> DashboardDataEntry { let count = DashboardWidgetLayout.rowCount(for: height, hasActions: false) + let examples = ["Project plan", "Meeting notes", "Design review", "Team agenda", "Travel itinerary"] let rows = (0.. Entry { - dashboardPlaceholder(height: context.displaySize.height) + dashboardSampleEntry(height: context.displaySize.height) } func getSnapshot(for configuration: DashboardIntent, in context: Context, completion: @escaping (Entry) -> Void) { guard !context.isPreview else { - completion(placeholder(in: context)) + completion(dashboardSampleEntry(height: context.displaySize.height, isPlaceholder: false)) return } @@ -27,7 +27,8 @@ struct DashboardWidgetProvider: IntentTimelineProvider { func getTimeline(for configuration: DashboardIntent, in context: Context, completion: @escaping (Timeline) -> Void) { guard !context.isPreview else { - completion(Timeline(entries: [placeholder(in: context)], policy: .never)) + let entry = dashboardSampleEntry(height: context.displaySize.height, isPlaceholder: false) + completion(Timeline(entries: [entry], policy: .never)) return } diff --git a/Widget/Dashboard/DashboardWidgetView.swift b/Widget/Dashboard/DashboardWidgetView.swift index 105d73f154..a6a813e518 100644 --- a/Widget/Dashboard/DashboardWidgetView.swift +++ b/Widget/Dashboard/DashboardWidgetView.swift @@ -233,7 +233,7 @@ struct DashboardWidgetView: View { struct DashboardWidget_Previews: PreviewProvider { static var previews: some View { - let sample = dashboardPlaceholder(height: 360) + let sample = dashboardSampleEntry(height: 360) let entry = DashboardDataEntry(date: Date(), rows: sample.rows, totalRows: sample.totalRows, diff --git a/Widget/Files/FilesWidgetProvider.swift b/Widget/Files/FilesWidgetProvider.swift index ad8a5ea0e1..24372bb7c8 100644 --- a/Widget/Files/FilesWidgetProvider.swift +++ b/Widget/Files/FilesWidgetProvider.swift @@ -11,9 +11,13 @@ struct FilesWidgetProvider: IntentTimelineProvider { typealias Intent = AccountIntent func placeholder(in context: Context) -> Entry { + sampleEntry(in: context, isPlaceholder: true) + } + + private func sampleEntry(in context: Context, isPlaceholder: Bool) -> Entry { Entry(date: Date(), datas: filesWidgetSampleRows(count: FilesWidgetLayout.rowCount(for: context.displaySize.height)), - isPlaceholder: true, + isPlaceholder: isPlaceholder, isEmpty: false, allowsRefresh: false, footerImage: "checkmark.icloud", @@ -22,7 +26,7 @@ struct FilesWidgetProvider: IntentTimelineProvider { func getSnapshot(for configuration: AccountIntent, in context: Context, completion: @escaping (Entry) -> Void) { guard !context.isPreview else { - completion(placeholder(in: context)) + completion(sampleEntry(in: context, isPlaceholder: false)) return } @@ -34,7 +38,7 @@ struct FilesWidgetProvider: IntentTimelineProvider { func getTimeline(for configuration: AccountIntent, in context: Context, completion: @escaping (Timeline) -> Void) { guard !context.isPreview else { - completion(Timeline(entries: [placeholder(in: context)], policy: .never)) + completion(Timeline(entries: [sampleEntry(in: context, isPlaceholder: false)], policy: .never)) return } diff --git a/Widget/Lockscreen/LockscreenData.swift b/Widget/Lockscreen/LockscreenData.swift index 33ff454973..2c919c3af7 100644 --- a/Widget/Lockscreen/LockscreenData.swift +++ b/Widget/Lockscreen/LockscreenData.swift @@ -18,7 +18,7 @@ struct LockscreenData: TimelineEntry { var quotaTotalAccessibilityLabel: String? } -func getLockscreenDataEntry(configuration: AccountIntent?, isPreview: Bool, family: WidgetFamily, completion: @escaping (_ entry: LockscreenData) -> Void) { +func getLockscreenDataEntry(configuration: AccountIntent?, family: WidgetFamily, completion: @escaping (_ entry: LockscreenData) -> Void) { let utilityFileSystem = NCUtilityFileSystem() var activeTableAccount: tableAccount? let versionApp = NCUtility().getVersionMaintenance() @@ -29,10 +29,6 @@ func getLockscreenDataEntry(configuration: AccountIntent?, isPreview: Bool, fami return completion(LockscreenData(date: Date(), isPlaceholder: true, activity: "", link: nil, quotaRelative: 0, quotaUsed: "", quotaTotal: "", error: false)) } - if isPreview { - return completion(LockscreenData(date: Date(), isPlaceholder: true, activity: "", link: nil, quotaRelative: 0, quotaUsed: "", quotaTotal: "", error: false)) - } - let accountIdentifier: String = configuration?.accounts?.identifier ?? "active" if accountIdentifier == "active" { activeTableAccount = NCManageDatabase.shared.getActiveTableAccount() diff --git a/Widget/Lockscreen/LockscreenWidgetProvider.swift b/Widget/Lockscreen/LockscreenWidgetProvider.swift index db467a489b..56d8228672 100644 --- a/Widget/Lockscreen/LockscreenWidgetProvider.swift +++ b/Widget/Lockscreen/LockscreenWidgetProvider.swift @@ -16,15 +16,28 @@ struct LockscreenWidgetProvider: IntentTimelineProvider { } func getSnapshot(for configuration: AccountIntent, in context: Context, completion: @escaping (Entry) -> Void) { - getLockscreenDataEntry(configuration: configuration, isPreview: context.isPreview, family: context.family) { entry in + if context.isPreview { + completion(Self.previewEntry()) + return + } + getLockscreenDataEntry(configuration: configuration, family: context.family) { entry in completion(entry) } } func getTimeline(for configuration: AccountIntent, in context: Context, completion: @escaping (Timeline) -> Void) { - getLockscreenDataEntry(configuration: configuration, isPreview: context.isPreview, family: context.family) { entry in + if context.isPreview { + completion(Timeline(entries: [Self.previewEntry()], policy: .never)) + return + } + getLockscreenDataEntry(configuration: configuration, family: context.family) { entry in let timeLine = Timeline(entries: [entry], policy: .atEnd) completion(timeLine) } } + + static func previewEntry() -> Entry { + Entry(date: Date(), isPlaceholder: false, activity: "Alex updated Documents / Meeting notes.pdf", + link: nil, quotaRelative: 0.5, quotaUsed: "5 GB", quotaTotal: "10 GB", error: false) + } } diff --git a/Widget/Lockscreen/LockscreenWidgetView.swift b/Widget/Lockscreen/LockscreenWidgetView.swift index 6aafa0b1f2..7ae8b7c7bd 100644 --- a/Widget/Lockscreen/LockscreenWidgetView.swift +++ b/Widget/Lockscreen/LockscreenWidgetView.swift @@ -74,7 +74,7 @@ struct LockscreenWidgetView: View { struct LockscreenWidgetView_Previews: PreviewProvider { static var previews: some View { - let entry = LockscreenData(date: Date(), isPlaceholder: false, activity: "Alex updated Documents / Meeting notes.pdf", link: nil, quotaRelative: 0.5, quotaUsed: "5 GB", quotaTotal: "10 GB", error: false) + let entry = LockscreenWidgetProvider.previewEntry() LockscreenWidgetView(entry: entry).previewContext(WidgetPreviewContext(family: .accessoryRectangular)).previewDisplayName("Rectangular") LockscreenWidgetView(entry: entry).previewContext(WidgetPreviewContext(family: .accessoryCircular)).previewDisplayName("Circular") }