diff --git a/Nextcloud.xcodeproj/project.pbxproj b/Nextcloud.xcodeproj/project.pbxproj index b7eca39393..c417bfcbcf 100644 --- a/Nextcloud.xcodeproj/project.pbxproj +++ b/Nextcloud.xcodeproj/project.pbxproj @@ -6618,7 +6618,7 @@ CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; COPY_PHASE_STRIP = NO; - CURRENT_PROJECT_VERSION = 3; + CURRENT_PROJECT_VERSION = 4; DEAD_CODE_STRIPPING = YES; DEBUG_INFORMATION_FORMAT = dwarf; DEVELOPMENT_TEAM = NKUJUXUJ3B; @@ -6685,7 +6685,7 @@ CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; COPY_PHASE_STRIP = NO; - CURRENT_PROJECT_VERSION = 3; + CURRENT_PROJECT_VERSION = 4; DEAD_CODE_STRIPPING = YES; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEVELOPMENT_TEAM = NKUJUXUJ3B; diff --git a/Widget/Dashboard/DashboardData.swift b/Widget/Dashboard/DashboardData.swift index 59da003dce..aacf86c022 100644 --- a/Widget/Dashboard/DashboardData.swift +++ b/Widget/Dashboard/DashboardData.swift @@ -159,12 +159,7 @@ func getDashboardDataEntry(configuration: DashboardIntent, displaySize: CGSize) let title = module?.title ?? moduleId let baseURL = URL(string: account.urlBase) let actions = (moduleButtons ?? []).compactMap { button -> DashboardAction? in - switch (moduleId, button.type) { - case ("notes", "new"), ("notes", "more"), ("circles", "setup"): - return nil - default: - break - } + if moduleId == "circles", button.type == "setup" { return nil } let isMore = button.type == "more" let url: URL? @@ -174,19 +169,22 @@ func getDashboardDataEntry(configuration: DashboardIntent, displaySize: CGSize) components.host = "openFavorites" components.queryItems = [URLQueryItem(name: "account", value: account.account)] url = components.url + } else if moduleId == "notes", button.type == "new" || isMore { + url = dashboardWebURL(button.link, relativeTo: baseURL).flatMap(dashboardBrowserDeepLink(for:)) } else { url = dashboardWebURL(button.link, relativeTo: baseURL) } guard let url else { return nil } - let hidesWhenAllRowsFit = isMore && moduleId != "files-favorites" && moduleId != "circles" + let hidesWhenAllRowsFit = isMore && !["files-favorites", "circles", "notes"].contains(moduleId) return DashboardAction(id: button.index, title: button.text, url: url, hidesWhenAllRowsFit: hidesWhenAllRowsFit) } let titleImage: UIImage? + let iconSize = CGSize(width: DashboardWidgetLayout.iconSize, height: DashboardWidgetLayout.iconSize) if let iconClass = module?.iconClass { let fileSystem = NCUtilityFileSystem() let path = fileSystem.createServerUrl(serverUrl: fileSystem.directoryUserData, fileName: iconClass + ".png") - titleImage = UIImage(contentsOfFile: path) + titleImage = UIImage.thumbnail(imageAt: URL(fileURLWithPath: path), to: iconSize, scale: 3) } else { titleImage = nil } @@ -236,8 +234,11 @@ func getDashboardDataEntry(configuration: DashboardIntent, displaySize: CGSize) isRound = false } else if iconURL.pathComponents.contains("getCalendarDotSvg") { calendarColor = UIColor(hex: (iconURL.lastPathComponent as NSString).deletingPathExtension) - } else if let data = await utility.downloadDashboardIcon(from: iconURL, account: account.account) { - icon = UIImage(data: data) + } else { + let result = await NextcloudKit.shared.downloadPreviewAsync(url: iconURL, account: account.account) + if result.error == .success, let data = result.responseData?.data { + icon = UIImage.thumbnail(from: data, to: iconSize, scale: 3) + } } } @@ -311,6 +312,14 @@ private func getDashboardModuleItems(_ moduleId: String, return (payload.ocs.data[moduleId]?.items ?? [], .success) } +func dashboardBrowserDeepLink(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 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) diff --git a/Widget/Dashboard/DashboardWidgetView.swift b/Widget/Dashboard/DashboardWidgetView.swift index a6a813e518..ec74aca665 100644 --- a/Widget/Dashboard/DashboardWidgetView.swift +++ b/Widget/Dashboard/DashboardWidgetView.swift @@ -49,7 +49,7 @@ struct DashboardWidgetView: View { VStack(alignment: .leading, spacing: DashboardWidgetLayout.sectionSpacing) { header - if let webURL = entry.webURL, let browserURL = browserDeepLink(for: webURL) { + if let webURL = entry.webURL, let browserURL = dashboardBrowserDeepLink(for: webURL) { VStack(spacing: 10) { Text(NSLocalizedString("_widget_dashboard_available_on_web_", value: "Available on the web", comment: "")) .font(.subheadline) @@ -97,14 +97,6 @@ struct DashboardWidgetView: View { .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) diff --git a/Widget/Files/FilesData.swift b/Widget/Files/FilesData.swift index fdcf4d26f5..c684185ad8 100644 --- a/Widget/Files/FilesData.swift +++ b/Widget/Files/FilesData.swift @@ -5,6 +5,7 @@ import UIKit import WidgetKit import Intents +import ImageIO import NextcloudKit struct FilesDataEntry: TimelineEntry { @@ -172,30 +173,7 @@ func getFilesDataEntry(configuration: AccountIntent, displaySize: CGSize) async ] guard let url = components.url else { continue } - // IMAGE - image = utility.getImage(ocId: file.ocId, - etag: file.etag, - ext: NCGlobal.shared.previewExt512, - userId: activeTableAccount.userId, - urlBase: activeTableAccount.urlBase) - if image == nil, file.hasPreview { - let result = await NextcloudKit.shared.downloadPreviewAsync(fileId: file.fileId, - etag: file.etag, - account: activeTableAccount.account, - options: options) - if result.error == .success, let data = result.responseData?.data { - utility.createImageFileFrom(data: data, - ocId: file.ocId, - etag: file.etag, - userId: activeTableAccount.userId, - urlBase: activeTableAccount.urlBase) - image = utility.getImage(ocId: file.ocId, - etag: file.etag, - ext: NCGlobal.shared.previewExt256, - userId: activeTableAccount.userId, - urlBase: activeTableAccount.urlBase) - } - } + image = await loadFilesWidgetPreview(for: file, account: activeTableAccount, fileSystem: utilityFileSystem, options: options) if image == nil { image = utility.loadImage(named: file.iconName, useTypeIconFile: true, account: file.account) useTypeIconFile = true @@ -217,3 +195,49 @@ func getFilesDataEntry(configuration: AccountIntent, displaySize: CGSize) async return(FilesDataEntry(date: Date(), datas: datas, isPlaceholder: false, isEmpty: datas.isEmpty, allowsRefresh: true, footerImage: "checkmark.icloud", footerText: footerText)) } } + +private func loadFilesWidgetPreview(for file: NKFile, + account: tableAccount, + fileSystem: NCUtilityFileSystem, + options: NKRequestOptions) async -> UIImage? { + let thumbnailSize = NCGlobal.shared.size256 + let thumbnailPath = fileSystem.getDirectoryProviderStorageImageOcId(file.ocId, + etag: file.etag, + ext: NCGlobal.shared.previewExt256, + userId: account.userId, + urlBase: account.urlBase) + let thumbnailURL = URL(fileURLWithPath: thumbnailPath) + if let image = UIImage.thumbnail(imageAt: thumbnailURL, to: thumbnailSize, scale: 1) { + return image + } + + let largerPath = fileSystem.getDirectoryProviderStorageImageOcId(file.ocId, + etag: file.etag, + ext: NCGlobal.shared.previewExt512, + userId: account.userId, + urlBase: account.urlBase) + if let image = UIImage.thumbnail(imageAt: URL(fileURLWithPath: largerPath), to: thumbnailSize, scale: 1) { + return image + } + + let result = await NextcloudKit.shared.downloadPreviewAsync(fileId: file.fileId, + width: Int(thumbnailSize.width), + height: Int(thumbnailSize.height), + etag: file.etag, + account: account.account, + options: options) + guard result.error == .success, + let data = result.responseData?.data else { return nil } + + let sourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary + guard let source = CGImageSourceCreateWithData(data as CFData, sourceOptions) else { return nil } + + let thumbnailOptions = [ + kCGImageSourceCreateThumbnailFromImageAlways: true, + kCGImageSourceCreateThumbnailWithTransform: true, + kCGImageSourceThumbnailMaxPixelSize: Int(thumbnailSize.width) + ] as CFDictionary + guard let thumbnail = CGImageSourceCreateThumbnailAtIndex(source, 0, thumbnailOptions) else { return nil } + // The shared preview cache expects all three sizes. Use this thumbnail only for the widget entry. + return UIImage(cgImage: thumbnail) +} diff --git a/iOSClient/Extensions/UIImage+Extension.swift b/iOSClient/Extensions/UIImage+Extension.swift index c3b6094eea..c1aef55d5b 100644 --- a/iOSClient/Extensions/UIImage+Extension.swift +++ b/iOSClient/Extensions/UIImage+Extension.swift @@ -163,25 +163,29 @@ extension UIImage { return newImage } - /// Downsamles a image using ImageIO. Has better memory perfomance than redrawing using UIKit + /// Creates a thumbnail from an image file using Image I/O. /// /// - [Source](https://swiftsenpai.com/development/reduce-uiimage-memory-footprint/) /// - [Original Source, WWDC18](https://developer.apple.com/videos/play/wwdc2018/416/?time=1352) /// - Parameters: /// - imageURL: The URL path of the image /// - pointSize: The target point size - /// - scale: The point to pixel scale (Pixeld per point) - /// - Returns: The downsampled image, if successful - static func downsample(imageAt imageURL: URL, to pointSize: CGSize, scale: CGFloat) -> UIImage? { - - // Create an CGImageSource that represent an image + /// - scale: The number of pixels per point + /// - Returns: The thumbnail, if successful + static func thumbnail(imageAt imageURL: URL, to pointSize: CGSize, scale: CGFloat) -> UIImage? { let imageSourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary guard let imageSource = CGImageSourceCreateWithURL(imageURL as CFURL, imageSourceOptions) else { return nil } + return thumbnail(from: imageSource, to: pointSize, scale: scale) + } - // Calculate the desired dimension - let maxDimensionInPixels = max(pointSize.width, pointSize.height) * scale + static func thumbnail(from data: Data, to pointSize: CGSize, scale: CGFloat) -> UIImage? { + let imageSourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary + guard let imageSource = CGImageSourceCreateWithData(data as CFData, imageSourceOptions) else { return nil } + return thumbnail(from: imageSource, to: pointSize, scale: scale) + } - // Perform downsampling + private static func thumbnail(from imageSource: CGImageSource, to pointSize: CGSize, scale: CGFloat) -> UIImage? { + let maxDimensionInPixels = max(pointSize.width, pointSize.height) * scale let downsampleOptions = [ kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceShouldCacheImmediately: true, @@ -190,7 +194,6 @@ extension UIImage { ] as CFDictionary guard let downsampledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, downsampleOptions) else { return nil } - // Return the downsampled image as UIImage return UIImage(cgImage: downsampledImage) } diff --git a/iOSClient/Main/Create/NCCreateFormUploadConflict.swift b/iOSClient/Main/Create/NCCreateFormUploadConflict.swift index 59d55f3918..32275b2d75 100644 --- a/iOSClient/Main/Create/NCCreateFormUploadConflict.swift +++ b/iOSClient/Main/Create/NCCreateFormUploadConflict.swift @@ -445,7 +445,7 @@ extension NCCreateFormUploadConflict: UITableViewDataSource { do { if metadataNewFile.classFile == NKTypeClassFile.image.rawValue { // preserver memory especially for very large files in Share extension - if let image = UIImage.downsample( + if let image = UIImage.thumbnail( imageAt: URL(fileURLWithPath: filePathNewFile), to: cell.imageNewFile.frame.size, scale: cell.imageNewFile.traitCollection.displayScale diff --git a/iOSClient/Networking/NCService.swift b/iOSClient/Networking/NCService.swift index c2727eaee0..189ad38a3d 100644 --- a/iOSClient/Networking/NCService.swift +++ b/iOSClient/Networking/NCService.swift @@ -123,9 +123,9 @@ class NCService: NSObject { dashboardWidgets: dashboardWidgets, preferredItemAPIVersions: catalog?.preferredItemAPIVersions ?? [:]) for widget in dashboardWidgets { - guard let url = URL(string: widget.iconUrl), - let fileName = widget.iconClass, - let data = await utility.downloadDashboardIcon(from: url, account: account) else { continue } + guard let url = URL(string: widget.iconUrl), let fileName = widget.iconClass else { continue } + let result = await NextcloudKit.shared.downloadPreviewAsync(url: url, account: account) + guard result.error == .success, let data = result.responseData?.data else { continue } let size = CGSize(width: 256, height: 256) let image: UIImage? diff --git a/iOSClient/Utility/NCUtility+Image.swift b/iOSClient/Utility/NCUtility+Image.swift index b715e7196a..94e9dc459d 100644 --- a/iOSClient/Utility/NCUtility+Image.swift +++ b/iOSClient/Utility/NCUtility+Image.swift @@ -5,44 +5,12 @@ 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,