diff --git a/.claude/settings.local.json b/.claude/settings.local.json index b8b258661..205b61aae 100644 --- a/.claude/settings.local.json +++ b/.claude/settings.local.json @@ -68,7 +68,8 @@ "Bash(echo:*)", "Bash(done)", "Bash(# Show files touched by state restoration related commits echo \"\"=== Files changed in state restoration commits ===\"\" for commit in 04e98a47d 89b31858c d788af388 1d49b9328 236943f82 38d6b11c5 3be027699 16c66513c 1ef2aa162 6ce3bdadc 1954f5b65 55b7da75d 20b3bda94 4bf57afc1 e0074d70b 616b9deeb f6bca9ee8 ea6eedb86 380617920 d68106ac0 d30c62757 813f0706b 2ea00619c; do git diff-tree --no-commit-id --name-only -r \"\"$commit\"\" done)", - "Bash(swiftlint version:*)" + "Bash(swiftlint version:*)", + "Bash(swiftlint:*)" ], "deny": [], "ask": [] diff --git a/.swiftlint.yml b/.swiftlint.yml index 63b33d8bb..0872a68f2 100644 --- a/.swiftlint.yml +++ b/.swiftlint.yml @@ -3,6 +3,9 @@ identifier_name: max_length: 50 allowed_symbols: "_" +type_name: + max_length: 50 + # line_length: # warning: 200 # error: 300 @@ -10,8 +13,8 @@ identifier_name: # ignores_urls: true large_tuple: - warning: 4 - error: 5 + warning: 5 + error: 6 disabled_rules: - todo @@ -27,6 +30,7 @@ disabled_rules: - line_length - operator_whitespace - nesting + - class_delegate_protocol excluded: - ".build" diff --git a/Intents/AddWebFeedIntentHandler.swift b/Intents/AddWebFeedIntentHandler.swift index 401434cc6..f87259ea5 100644 --- a/Intents/AddWebFeedIntentHandler.swift +++ b/Intents/AddWebFeedIntentHandler.swift @@ -37,7 +37,7 @@ public class AddWebFeedIntentHandler: NSObject, AddWebFeedIntentHandling { guard let extensionContainers = await ExtensionContainersFile.read() else { throw AddWebFeedIntentHandlerError.communicationFailure } - + let accountNames = extensionContainers.accounts.map { $0.name } return accountNames } @@ -46,7 +46,7 @@ public class AddWebFeedIntentHandler: NSObject, AddWebFeedIntentHandling { guard let accountName = intent.accountName else { return .notRequired() } - + guard let extensionContainers = await ExtensionContainersFile.read() else { return .unsupported(forReason: .communication) } diff --git a/Mac/AppDefaults.swift b/Mac/AppDefaults.swift index 2b8050e12..b2ae98c1e 100644 --- a/Mac/AppDefaults.swift +++ b/Mac/AppDefaults.swift @@ -65,7 +65,7 @@ final class AppDefaults: Sendable { }() let isFirstRun: Bool = { - if let _ = UserDefaults.standard.object(forKey: Key.firstRunDate) as? Date { + if UserDefaults.standard.object(forKey: Key.firstRunDate) is Date { return false } firstRunDate = Date() @@ -117,8 +117,7 @@ final class AppDefaults: Sendable { if let appGroupID = Bundle.main.object(forInfoDictionaryKey: "AppGroup") as? String, let appGroupDefaults = UserDefaults(suiteName: appGroupID) { return appGroupDefaults - } - else { + } else { return UserDefaults.standard } } @@ -324,7 +323,7 @@ final class AppDefaults: Sendable { let showDebugMenu = false #endif - let defaults: [String : Any] = [ + let defaults: [String: Any] = [ Key.sidebarFontSize: FontSize.medium.rawValue, Key.timelineFontSize: FontSize.medium.rawValue, Key.detailFontSize: FontSize.medium.rawValue, @@ -428,7 +427,7 @@ private extension AppDefaults { UserDefaults.standard.set(date, forKey: key) } - static func sortDirection(for key:String) -> ComparisonResult { + static func sortDirection(for key: String) -> ComparisonResult { let rawInt = int(for: key) if rawInt == ComparisonResult.orderedAscending.rawValue { return .orderedAscending @@ -439,8 +438,7 @@ private extension AppDefaults { static func setSortDirection(for key: String, _ value: ComparisonResult) { if value == .orderedAscending { setInt(for: key, ComparisonResult.orderedAscending.rawValue) - } - else { + } else { setInt(for: key, ComparisonResult.orderedDescending.rawValue) } } diff --git a/Mac/CrashReporter/CrashReportWindowController.swift b/Mac/CrashReporter/CrashReportWindowController.swift index b0d155d43..0e73c106f 100644 --- a/Mac/CrashReporter/CrashReportWindowController.swift +++ b/Mac/CrashReporter/CrashReportWindowController.swift @@ -59,4 +59,3 @@ final class CrashReportWindowController: NSWindowController { close() } } - diff --git a/Mac/CrashReporter/CrashReporter.swift b/Mac/CrashReporter/CrashReporter.swift index 8ba518ad5..03f09db8c 100644 --- a/Mac/CrashReporter/CrashReporter.swift +++ b/Mac/CrashReporter/CrashReporter.swift @@ -52,7 +52,7 @@ import CrashReporter let boundary = "0xKhTmLbOuNdArY" let contentType = "multipart/form-data; boundary=\(boundary)" - request.setValue(contentType, forHTTPHeaderField:HTTPRequestHeader.contentType) + request.setValue(contentType, forHTTPHeaderField: HTTPRequestHeader.contentType) let formString = "--\(boundary)\r\nContent-Disposition: form-data; name=\"crashlog\"\r\n\r\n\(crashLogText)\r\n--\(boundary)--\r\n" let formData = formString.data(using: .utf8, allowLossyConversion: true) diff --git a/Mac/Inspector/BuiltinSmartFeedInspectorViewController.swift b/Mac/Inspector/BuiltinSmartFeedInspectorViewController.swift index 90876796a..71d3a9243 100644 --- a/Mac/Inspector/BuiltinSmartFeedInspectorViewController.swift +++ b/Mac/Inspector/BuiltinSmartFeedInspectorViewController.swift @@ -31,7 +31,7 @@ final class BuiltinSmartFeedInspectorViewController: NSViewController, Inspector func canInspect(_ objects: [Any]) -> Bool { - guard let _ = singleSmartFeed(from: objects) else { + guard singleSmartFeed(from: objects) != nil else { return false } return true diff --git a/Mac/Inspector/FeedInspectorViewController.swift b/Mac/Inspector/FeedInspectorViewController.swift index bc369450e..d7181182d 100644 --- a/Mac/Inspector/FeedInspectorViewController.swift +++ b/Mac/Inspector/FeedInspectorViewController.swift @@ -63,7 +63,7 @@ final class FeedInspectorViewController: NSViewController, Inspector { // MARK: Actions @IBAction func isNotifyAboutNewArticlesChanged(_ sender: Any) { - guard authorizationStatus != nil else { + guard authorizationStatus != nil else { DispatchQueue.main.async { self.isNotifyAboutNewArticlesCheckBox.setNextState() } @@ -85,7 +85,7 @@ final class FeedInspectorViewController: NSViewController, Inspector { self.feed?.isNotifyAboutNewArticles = (self.isNotifyAboutNewArticlesCheckBox?.state ?? .off) == .on ? true : false } } else { - UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert]) { (granted, error) in + UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert]) { granted, _ in Task { @MainActor in self.updateNotificationSettings() if granted { diff --git a/Mac/Inspector/FolderInspectorViewController.swift b/Mac/Inspector/FolderInspectorViewController.swift index 840e4896d..d7d50bbd9 100644 --- a/Mac/Inspector/FolderInspectorViewController.swift +++ b/Mac/Inspector/FolderInspectorViewController.swift @@ -35,8 +35,7 @@ final class FolderInspectorViewController: NSViewController, Inspector { var windowTitle: String = NSLocalizedString("Folder Inspector", comment: "Folder Inspector window title") func canInspect(_ objects: [Any]) -> Bool { - - guard let _ = singleFolder(from: objects) else { + guard singleFolder(from: objects) != nil else { return false } return true diff --git a/Mac/Inspector/InspectorWindowController.swift b/Mac/Inspector/InspectorWindowController.swift index 5837b128a..1ebbd6fa0 100644 --- a/Mac/Inspector/InspectorWindowController.swift +++ b/Mac/Inspector/InspectorWindowController.swift @@ -25,7 +25,7 @@ final class InspectorWindowController: NSWindowController { var objects: [Any]? { didSet { - let _ = window + _ = window currentInspector = inspector(for: objects) } } @@ -64,8 +64,7 @@ final class InspectorWindowController: NSWindowController { if let savedOrigin = originFromDefaults() { window?.setFlippedOriginAdjustingForScreen(savedOrigin) - } - else { + } else { window?.flippedOrigin = NSPoint(x: 256, y: 256) } } @@ -77,8 +76,7 @@ final class InspectorWindowController: NSWindowController { for inspector in inspectors { if inspector.isFallbackInspector { fallbackInspector = inspector - } - else if let objects = objects, inspector.canInspect(objects) { + } else if let objects = objects, inspector.canInspect(objects) { return inspector } } @@ -110,7 +108,7 @@ private extension InspectorWindowController { DispatchQueue.main.async { window.title = inspector.windowTitle - } + } let flippedOrigin = window.flippedOrigin diff --git a/Mac/Inspector/NothingInspectorViewController.swift b/Mac/Inspector/NothingInspectorViewController.swift index 376e6a594..f23ad9b64 100644 --- a/Mac/Inspector/NothingInspectorViewController.swift +++ b/Mac/Inspector/NothingInspectorViewController.swift @@ -39,8 +39,7 @@ private extension NothingInspectorViewController { if let objects = objects, objects.count > 1 { nothingTextField?.isHidden = true multipleTextField?.isHidden = false - } - else { + } else { nothingTextField?.isHidden = false multipleTextField?.isHidden = true } diff --git a/Mac/MainWindow/AddFeed/AddFeedWindowController.swift b/Mac/MainWindow/AddFeed/AddFeedWindowController.swift index d69a2103e..cbfa2d890 100644 --- a/Mac/MainWindow/AddFeed/AddFeedWindowController.swift +++ b/Mac/MainWindow/AddFeed/AddFeedWindowController.swift @@ -18,8 +18,7 @@ import Account func addFeedWindowControllerUserDidCancel(_: AddFeedWindowController) } -final class AddFeedWindowController : NSWindowController { - +final class AddFeedWindowController: NSWindowController { @IBOutlet var urlTextField: NSTextField! @IBOutlet var nameTextField: NSTextField! @IBOutlet var addButton: NSButton! @@ -97,7 +96,7 @@ final class AddFeedWindowController : NSWindowController { if normalizedURLString.isEmpty { cancelSheet() - return; + return } guard let url = URL(string: normalizedURLString) else { cancelSheet() diff --git a/Mac/MainWindow/Detail/DetailContainerView.swift b/Mac/MainWindow/Detail/DetailContainerView.swift index f51ec96ef..f52a747b2 100644 --- a/Mac/MainWindow/Detail/DetailContainerView.swift +++ b/Mac/MainWindow/Detail/DetailContainerView.swift @@ -38,7 +38,7 @@ final class DetailContainerView: NSView { override func draw(_ dirtyRect: NSRect) { NSColor.controlBackgroundColor.set() - let r = NSIntersectionRect(dirtyRect, bounds) + let r = dirtyRect.intersection(bounds) r.fill() } } diff --git a/Mac/MainWindow/Detail/DetailStatusBarView.swift b/Mac/MainWindow/Detail/DetailStatusBarView.swift index 62577648a..0d110e798 100644 --- a/Mac/MainWindow/Detail/DetailStatusBarView.swift +++ b/Mac/MainWindow/Detail/DetailStatusBarView.swift @@ -25,8 +25,7 @@ final class DetailStatusBarView: NSView { if let link = linkForDisplay { urlLabel.stringValue = link self.isHidden = false - } - else { + } else { urlLabel.stringValue = "" self.isHidden = true } @@ -68,8 +67,7 @@ private extension DetailStatusBarView { func updateLinkForDisplay() { if let mouseoverLink = mouseoverLink, !mouseoverLink.isEmpty { linkForDisplay = mouseoverLink.strippingHTTPOrHTTPSScheme - } - else { + } else { linkForDisplay = nil } } diff --git a/Mac/MainWindow/Detail/DetailWebView.swift b/Mac/MainWindow/Detail/DetailWebView.swift index 58922083f..95709089c 100644 --- a/Mac/MainWindow/Detail/DetailWebView.swift +++ b/Mac/MainWindow/Detail/DetailWebView.swift @@ -89,4 +89,3 @@ private extension DetailWebView { return false } } - diff --git a/Mac/MainWindow/Detail/DetailWebViewController.swift b/Mac/MainWindow/Detail/DetailWebViewController.swift index e02be2ff9..b002d48b6 100644 --- a/Mac/MainWindow/Detail/DetailWebViewController.swift +++ b/Mac/MainWindow/Detail/DetailWebViewController.swift @@ -68,7 +68,7 @@ final class DetailWebViewController: NSViewController { private var isShowingExtractedArticle: Bool { switch state { - case .extracted(_, _, _): + case .extracted: return true default: return false @@ -208,7 +208,7 @@ extension DetailWebViewController: WKNavigationDelegate, WKUIDelegate { decisionHandler(.cancel) return } - + decisionHandler(.allow) } @@ -269,7 +269,7 @@ private extension DetailWebViewController { } func reloadHTMLMaintainingScrollPosition() { - fetchScrollInfo() { scrollInfo in + fetchScrollInfo { scrollInfo in self.windowScrollY = scrollInfo?.offsetY self.reloadHTML() } @@ -319,7 +319,7 @@ private extension DetailWebViewController { private func fetchScrollInfo(_ completion: @escaping (ScrollInfo?) -> Void) { let javascriptString = "var x = {contentHeight: document.body.scrollHeight, offsetY: document.body.scrollTop}; x" - webView.evaluateJavaScript(javascriptString) { (info, error) in + webView.evaluateJavaScript(javascriptString) { (info, _) in guard let info = info as? [String: Any] else { completion(nil) return diff --git a/Mac/MainWindow/IconView.swift b/Mac/MainWindow/IconView.swift index 6163fbb3c..0795d8025 100644 --- a/Mac/MainWindow/IconView.swift +++ b/Mac/MainWindow/IconView.swift @@ -79,7 +79,7 @@ final class IconView: NSView { } override func layout() { - resizeSubviews(withOldSize: NSZeroSize) + resizeSubviews(withOldSize: NSSize.zero) } override func resizeSubviews(withOldSize oldSize: NSSize) { @@ -106,7 +106,7 @@ private extension IconView { func rectForImageView() -> NSRect { guard !(iconImage?.isSymbol ?? false) else { - return NSMakeRect(0.0, 0.0, bounds.size.width, bounds.size.height) + return NSRect(x: 0.0, y: 0.0, width: bounds.size.width, height: bounds.size.height) } guard let image = iconImage?.image else { @@ -118,21 +118,21 @@ private extension IconView { if imageSize.height == imageSize.width { if imageSize.height >= viewSize.height * 0.75 { // Close enough to viewSize to scale up the image. - return NSMakeRect(0.0, 0.0, viewSize.width, viewSize.height) + return NSRect(x: 0.0, y: 0.0, width: viewSize.width, height: viewSize.height) } let offset = floor((viewSize.height - imageSize.height) / 2.0) - return NSMakeRect(offset, offset, imageSize.width, imageSize.height) + return NSRect(x: offset, y: offset, width: imageSize.width, height: imageSize.height) } else if imageSize.height > imageSize.width { let factor = viewSize.height / imageSize.height let width = imageSize.width * factor let originX = floor((viewSize.width - width) / 2.0) - return NSMakeRect(originX, 0.0, width, viewSize.height) + return NSRect(x: originX, y: 0.0, width: width, height: viewSize.height) } // Wider than tall: imageSize.width > imageSize.height let factor = viewSize.width / imageSize.width let height = imageSize.height * factor let originY = floor((viewSize.height - height) / 2.0) - return NSMakeRect(0.0, originY, viewSize.width, height) + return NSRect(x: 0.0, y: originY, width: viewSize.width, height: height) } } diff --git a/Mac/MainWindow/Keyboard/MainWindowKeyboardHandler.swift b/Mac/MainWindow/Keyboard/MainWindowKeyboardHandler.swift index 0b781a7d9..d7fa85c56 100644 --- a/Mac/MainWindow/Keyboard/MainWindowKeyboardHandler.swift +++ b/Mac/MainWindow/Keyboard/MainWindowKeyboardHandler.swift @@ -30,4 +30,3 @@ import RSCore return true } } - diff --git a/Mac/MainWindow/MainWindowController.swift b/Mac/MainWindow/MainWindowController.swift index c47b1f1ae..2dea53d48 100644 --- a/Mac/MainWindow/MainWindowController.swift +++ b/Mac/MainWindow/MainWindowController.swift @@ -336,7 +336,7 @@ final class MainWindowController: NSWindowController, NSUserInterfaceValidations @IBAction func openArticleInBrowser(_ sender: Any?) { if let link = currentLink { Browser.open(link, invertPreference: NSApp.currentEvent?.modifierFlags.contains(.shift) ?? false) - } + } } @IBAction func openInBrowser(_ sender: Any?) { @@ -370,8 +370,7 @@ final class MainWindowController: NSWindowController, NSUserInterfaceValidations // TODO: handle search mode if timelineViewController.canGoToNextUnread(wrappingToTop: false) { goToNextUnreadInTimeline(wrappingToTop: false) - } - else if sidebarViewController.canGoToNextUnread(wrappingToTop: true) { + } else if sidebarViewController.canGoToNextUnread(wrappingToTop: true) { sidebarViewController.goToNextUnread(wrappingToTop: true) // If we ended up on the same timelineViewController, we may need to wrap @@ -444,7 +443,7 @@ final class MainWindowController: NSWindowController, NSUserInterfaceValidations } @IBAction func markAllAsReadAndGoToNextUnread(_ sender: Any?) { - currentTimelineViewController?.markAllAsRead() { + currentTimelineViewController?.markAllAsRead { self.nextUnread(sender) } } @@ -981,7 +980,7 @@ private extension MainWindowController { let splitViewWidths: [Int] if let splitView = splitViewController?.splitView { - splitViewWidths = splitView.arrangedSubviews.map{ Int(floor($0.frame.width)) } + splitViewWidths = splitView.arrangedSubviews.map { Int(floor($0.frame.width)) } } else { splitViewWidths = [] } @@ -1422,6 +1421,4 @@ private extension MainWindowController { articleThemeMenuToolbarItem.menu = articleThemeMenu articleThemePopUpButton?.menu = articleThemeMenu } - } - diff --git a/Mac/MainWindow/NNW3/NNW3Document.swift b/Mac/MainWindow/NNW3/NNW3Document.swift index 9d7fbed7f..2fb3b4e32 100644 --- a/Mac/MainWindow/NNW3/NNW3Document.swift +++ b/Mac/MainWindow/NNW3/NNW3Document.swift @@ -141,4 +141,3 @@ extension NNW3Feed: OPMLRepresentable { return s } } - diff --git a/Mac/MainWindow/OPML/ExportOPMLWindowController.swift b/Mac/MainWindow/OPML/ExportOPMLWindowController.swift index c2ec4600e..91d365c15 100644 --- a/Mac/MainWindow/OPML/ExportOPMLWindowController.swift +++ b/Mac/MainWindow/OPML/ExportOPMLWindowController.swift @@ -96,8 +96,7 @@ final class ExportOPMLWindowController: NSWindowController { let opmlString = OPMLExporter.OPMLString(with: account, title: filename) do { try opmlString.write(to: url, atomically: true, encoding: String.Encoding.utf8) - } - catch let error as NSError { + } catch let error as NSError { NSApplication.shared.presentError(error) } } diff --git a/Mac/MainWindow/Sidebar/Cell/SidebarCell.swift b/Mac/MainWindow/Sidebar/Cell/SidebarCell.swift index d582caa99..f8ce19696 100644 --- a/Mac/MainWindow/Sidebar/Cell/SidebarCell.swift +++ b/Mac/MainWindow/Sidebar/Cell/SidebarCell.swift @@ -73,7 +73,7 @@ final class SidebarCell: NSTableCellView { }() private let faviconImageView = IconView() - private let unreadCountView = UnreadCountView(frame: NSZeroRect) + private let unreadCountView = UnreadCountView(frame: NSRect.zero) override var backgroundStyle: NSView.BackgroundStyle { didSet { @@ -91,7 +91,7 @@ final class SidebarCell: NSTableCellView { commonInit() } - required init?(coder: NSCoder) { + required init?(coder: NSCoder) { super.init(coder: coder) commonInit() } @@ -100,7 +100,7 @@ final class SidebarCell: NSTableCellView { if let cellAppearance = cellAppearance { titleView.font = cellAppearance.textFieldFont } - resizeSubviews(withOldSize: NSZeroSize) + resizeSubviews(withOldSize: NSSize.zero) } override func resizeSubviews(withOldSize oldSize: NSSize) { diff --git a/Mac/MainWindow/Sidebar/Cell/SidebarCellAppearance.swift b/Mac/MainWindow/Sidebar/Cell/SidebarCellAppearance.swift index 9dce61a40..fdf0dd96e 100644 --- a/Mac/MainWindow/Sidebar/Cell/SidebarCellAppearance.swift +++ b/Mac/MainWindow/Sidebar/Cell/SidebarCellAppearance.swift @@ -32,4 +32,3 @@ struct SidebarCellAppearance: Equatable { self.textFieldFont = NSFont.systemFont(ofSize: textFieldFontSize) } } - diff --git a/Mac/MainWindow/Sidebar/Cell/SidebarCellLayout.swift b/Mac/MainWindow/Sidebar/Cell/SidebarCellLayout.swift index bee49702d..15d0adca4 100644 --- a/Mac/MainWindow/Sidebar/Cell/SidebarCellLayout.swift +++ b/Mac/MainWindow/Sidebar/Cell/SidebarCellLayout.swift @@ -17,7 +17,6 @@ import RSCore let unreadCountRect: CGRect init(appearance: SidebarCellAppearance, cellSize: NSSize, shouldShowImage: Bool, textField: NSTextField, unreadCountView: UnreadCountView) { - let bounds = NSRect(x: 0.0, y: 0.0, width: floor(cellSize.width), height: floor(cellSize.height)) var rFavicon = NSRect.zero @@ -31,7 +30,7 @@ import RSCore var rTextField = NSRect(x: 0.0, y: 0.0, width: textFieldSize.width, height: textFieldSize.height) if shouldShowImage { - rTextField.origin.x = NSMaxX(rFavicon) + appearance.imageMarginRight + rTextField.origin.x = rFavicon.maxX + appearance.imageMarginRight } rTextField = rTextField.centeredVertically(in: bounds) @@ -41,17 +40,17 @@ import RSCore var rUnread = NSRect.zero if !unreadCountIsHidden { rUnread.size = unreadCountSize - rUnread.origin.x = NSMaxX(bounds) - unreadCountSize.width + rUnread.origin.x = bounds.maxX - unreadCountSize.width rUnread = rUnread.centeredVertically(in: bounds) - let textFieldMaxX = NSMinX(rUnread) - appearance.unreadCountMarginLeft - if NSMaxX(rTextField) > textFieldMaxX { - rTextField.size.width = textFieldMaxX - NSMinX(rTextField) + let textFieldMaxX = rUnread.minX - appearance.unreadCountMarginLeft + if rTextField.maxX > textFieldMaxX { + rTextField.size.width = textFieldMaxX - rTextField.minX } } self.unreadCountRect = rUnread - if NSMaxX(rTextField) > NSMaxX(bounds) { - rTextField.size.width = NSMaxX(bounds) - NSMinX(rTextField) + if rTextField.maxX > bounds.maxX { + rTextField.size.width = bounds.maxX - rTextField.minX } self.titleRect = rTextField } diff --git a/Mac/MainWindow/Sidebar/Keyboard/SidebarKeyboardDelegate.swift b/Mac/MainWindow/Sidebar/Keyboard/SidebarKeyboardDelegate.swift index 5bec6043d..ad2dbb73b 100644 --- a/Mac/MainWindow/Sidebar/Keyboard/SidebarKeyboardDelegate.swift +++ b/Mac/MainWindow/Sidebar/Keyboard/SidebarKeyboardDelegate.swift @@ -39,4 +39,3 @@ import RSCore return true } } - diff --git a/Mac/MainWindow/Sidebar/PasteboardFeed.swift b/Mac/MainWindow/Sidebar/PasteboardFeed.swift index 63880f262..50f109889 100644 --- a/Mac/MainWindow/Sidebar/PasteboardFeed.swift +++ b/Mac/MainWindow/Sidebar/PasteboardFeed.swift @@ -76,8 +76,7 @@ struct PasteboardFeed: Hashable { var pasteboardType: NSPasteboard.PasteboardType? if pasteboardItem.types.contains(FeedPasteboardWriter.feedUTIInternalType) { pasteboardType = FeedPasteboardWriter.feedUTIInternalType - } - else if pasteboardItem.types.contains(FeedPasteboardWriter.feedUTIType) { + } else if pasteboardItem.types.contains(FeedPasteboardWriter.feedUTIType) { pasteboardType = FeedPasteboardWriter.feedUTIType } if let foundType = pasteboardType { @@ -91,8 +90,7 @@ struct PasteboardFeed: Hashable { // Check for URL or a string that may be a URL. if pasteboardItem.types.contains(.URL) { pasteboardType = .URL - } - else if pasteboardItem.types.contains(.string) { + } else if pasteboardItem.types.contains(.string) { pasteboardType = .string } if let foundType = pasteboardType { diff --git a/Mac/MainWindow/Sidebar/SidebarOutlineDataSource.swift b/Mac/MainWindow/Sidebar/SidebarOutlineDataSource.swift index 33ad61f87..d31d264b3 100644 --- a/Mac/MainWindow/Sidebar/SidebarOutlineDataSource.swift +++ b/Mac/MainWindow/Sidebar/SidebarOutlineDataSource.swift @@ -64,7 +64,7 @@ import Account func outlineView(_ outlineView: NSOutlineView, validateDrop info: NSDraggingInfo, proposedItem item: Any?, proposedChildIndex index: Int) -> NSDragOperation { let draggedFolders = PasteboardFolder.pasteboardFolders(with: info.draggingPasteboard) let draggedFeeds = PasteboardFeed.pasteboardFeeds(with: info.draggingPasteboard) - if (draggedFolders == nil && draggedFeeds == nil) || (draggedFolders != nil && draggedFeeds != nil) { + if (draggedFolders == nil && draggedFeeds == nil) || (draggedFolders != nil && draggedFeeds != nil) { return SidebarOutlineDataSource.dragOperationNone } let parentNode = nodeForItem(item) @@ -100,7 +100,7 @@ import Account func outlineView(_ outlineView: NSOutlineView, acceptDrop info: NSDraggingInfo, item: Any?, childIndex index: Int) -> Bool { let draggedFolders = PasteboardFolder.pasteboardFolders(with: info.draggingPasteboard) let draggedFeeds = PasteboardFeed.pasteboardFeeds(with: info.draggingPasteboard) - if (draggedFolders == nil && draggedFeeds == nil) || (draggedFolders != nil && draggedFeeds != nil) { + if (draggedFolders == nil && draggedFeeds == nil) || (draggedFolders != nil && draggedFeeds != nil) { return false } let parentNode = nodeForItem(item) @@ -167,8 +167,7 @@ private extension SidebarOutlineDataSource { for feed in draggedFeeds { if feed.isLocalFeed { hasLocalFeed = true - } - else { + } else { hasNonLocalFeed = true } if hasLocalFeed && hasNonLocalFeed { @@ -237,7 +236,7 @@ private extension SidebarOutlineDataSource { return localDragOperation(parentNode: parentNode, draggedFeeds) } - func localDragOperation(parentNode: Node, _ draggedFeeds: Set)-> NSDragOperation { + func localDragOperation(parentNode: Node, _ draggedFeeds: Set) -> NSDragOperation { guard let firstDraggedFeed = draggedFeeds.first else { return .move } if sameAccount(firstDraggedFeed, parentNode) { if NSApplication.shared.currentEvent?.modifierFlags.contains(.option) ?? false { @@ -443,7 +442,7 @@ private extension SidebarOutlineDataSource { Task { @MainActor in do { let destinationFolder = try await destinationAccount.addFolder(folder.name ?? "") - + for feed in folder.topLevelFeeds { if let existingFeed = destinationAccount.existingFeed(withURL: feed.url) { destinationAccount.addFeed(existingFeed, to: destinationFolder) { result in diff --git a/Mac/MainWindow/Sidebar/SidebarViewController+ContextualMenus.swift b/Mac/MainWindow/Sidebar/SidebarViewController+ContextualMenus.swift index a06728dc4..83637d2bb 100644 --- a/Mac/MainWindow/Sidebar/SidebarViewController+ContextualMenus.swift +++ b/Mac/MainWindow/Sidebar/SidebarViewController+ContextualMenus.swift @@ -119,7 +119,7 @@ extension SidebarViewController { NotificationCenter.default.post(Notification(name: .DidUpdateFeedPreferencesFromContextMenu)) } } else { - UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert]) { (granted, error) in + UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert]) { granted, _ in if granted { DispatchQueue.main.async { if feed.isNotifyAboutNewArticles == nil { feed.isNotifyAboutNewArticles = false } @@ -215,7 +215,7 @@ private extension SidebarViewController { menu.addItem(NSMenuItem.separator()) } - if let homePageURL = feed.homePageURL, let _ = URL(string: homePageURL) { + if let homePageURL = feed.homePageURL, URL(string: homePageURL) != nil { let item = menuItem(NSLocalizedString("Open Home Page", comment: "Command"), #selector(openHomePageFromContextualMenu(_:)), homePageURL, image: Assets.Images.openInBrowser) menu.addItem(item) menu.addItem(NSMenuItem.separator()) @@ -365,4 +365,3 @@ private extension SidebarViewController { return articles } } - diff --git a/Mac/MainWindow/Sidebar/SidebarViewController.swift b/Mac/MainWindow/Sidebar/SidebarViewController.swift index 1655e1d19..1d1ed36f4 100644 --- a/Mac/MainWindow/Sidebar/SidebarViewController.swift +++ b/Mac/MainWindow/Sidebar/SidebarViewController.swift @@ -136,7 +136,7 @@ extension Notification.Name { /// Restore state using legacy state restoration data. /// /// TODO: Delete for NetNewsWire 7. - func restoreLegacyState(from state: [AnyHashable : Any]) { + func restoreLegacyState(from state: [AnyHashable: Any]) { if let containerExpandedWindowState = state[UserInfoKey.containerExpandedWindowState] as? [[AnyHashable: AnyHashable]] { let containerIdentifiers = containerExpandedWindowState.compactMap( { ContainerIdentifier(userInfo: $0) }) @@ -339,7 +339,7 @@ extension Notification.Name { // MARK: - Navigation func canGoToNextUnread(wrappingToTop wrapping: Bool = false) -> Bool { - if let _ = nextSelectableRowWithUnreadArticle(wrappingToTop: wrapping) { + if nextSelectableRowWithUnreadArticle(wrappingToTop: wrapping) != nil { return true } return false @@ -461,7 +461,7 @@ extension Notification.Name { } } - //MARK: - Node Manipulation + // MARK: - Node Manipulation func deleteNodes(_ nodes: [Node]) { let nodesToDelete = treeController.normalizedSelectedNodes(nodes) @@ -504,7 +504,7 @@ extension Notification.Name { revealAndSelectRepresentedObject(sidebarItem as AnyObject) } - func deepLinkRevealAndSelect(for userInfo: [AnyHashable : Any]) { + func deepLinkRevealAndSelect(for userInfo: [AnyHashable: Any]) { guard let accountNode = findAccountNode(userInfo), let feedNode = findFeedNode(userInfo, beginningAt: accountNode), let sidebarItem = feedNode.representedObject as? SidebarItem else { @@ -537,7 +537,7 @@ extension SidebarViewController: NSUserInterfaceValidations { } } -//MARK: - Private +// MARK: - Private private extension SidebarViewController { @@ -758,7 +758,7 @@ private extension SidebarViewController { return nil } - func findAccountNode(_ userInfo: [AnyHashable : Any]?) -> Node? { + func findAccountNode(_ userInfo: [AnyHashable: Any]?) -> Node? { guard let accountID = userInfo?[ArticlePathKey.accountID] as? String else { return nil } @@ -778,7 +778,7 @@ private extension SidebarViewController { return nil } - func findFeedNode(_ userInfo: [AnyHashable : Any]?, beginningAt startingNode: Node) -> Node? { + func findFeedNode(_ userInfo: [AnyHashable: Any]?, beginningAt startingNode: Node) -> Node? { guard let feedID = userInfo?[ArticlePathKey.feedID] as? String else { return nil } @@ -857,7 +857,7 @@ private extension SidebarViewController { } func applyToAvailableCells(_ completion: (SidebarCell, Node) -> Void) { - outlineView.enumerateAvailableRowViews { (rowView: NSTableRowView, row: Int) -> Void in + outlineView.enumerateAvailableRowViews { (rowView: NSTableRowView, row: Int) in guard let cell = cellForRowView(rowView), let node = nodeForRow(row) else { return } diff --git a/Mac/MainWindow/Sidebar/UnreadCountView.swift b/Mac/MainWindow/Sidebar/UnreadCountView.swift index 54a9d2957..f1042982f 100644 --- a/Mac/MainWindow/Sidebar/UnreadCountView.swift +++ b/Mac/MainWindow/Sidebar/UnreadCountView.swift @@ -46,11 +46,11 @@ final class UnreadCountView: NSView { } private var intrinsicContentSizeIsValid = false - private var _intrinsicContentSize = NSZeroSize + private var _intrinsicContentSize = NSSize.zero override var intrinsicContentSize: NSSize { if !intrinsicContentSizeIsValid { - var size = NSZeroSize + var size = NSSize.zero if unreadCount > 0 { size = textSize() size.width += (Appearance.padding.left + Appearance.padding.right) @@ -74,7 +74,7 @@ final class UnreadCountView: NSView { private func textSize() -> NSSize { if unreadCount < 1 { - return NSZeroSize + return NSSize.zero } if let cachedSize = UnreadCountView.textSizeCache[unreadCount] { @@ -91,9 +91,9 @@ final class UnreadCountView: NSView { private func textRect() -> NSRect { let size = textSize() - var r = NSZeroRect + var r = NSRect.zero r.size = size - r.origin.x = (NSMaxX(bounds) - Appearance.padding.right) - r.size.width + r.origin.x = (bounds.maxX - Appearance.padding.right) - r.size.width r.origin.y = Appearance.padding.top return r } @@ -108,4 +108,3 @@ final class UnreadCountView: NSView { } } } - diff --git a/Mac/MainWindow/Timeline/ArticlePasteboardWriter.swift b/Mac/MainWindow/Timeline/ArticlePasteboardWriter.swift index 336ab74f6..a9e3ca095 100644 --- a/Mac/MainWindow/Timeline/ArticlePasteboardWriter.swift +++ b/Mac/MainWindow/Timeline/ArticlePasteboardWriter.swift @@ -38,7 +38,7 @@ extension Article: @retroactive PasteboardWriterOwner { func writableTypes(for pasteboard: NSPasteboard) -> [NSPasteboard.PasteboardType] { var types = [ArticlePasteboardWriter.articleUTIType] - if let _ = article.preferredURL { + if article.preferredURL != nil { types += [.URL] } types += [.string, .html, ArticlePasteboardWriter.articleUTIInternalType] @@ -78,11 +78,9 @@ private extension ArticlePasteboardWriter { } if let text = article.contentText { s += "\(text)\n\n" - } - else if let summary = article.summary { + } else if let summary = article.summary { s += "\(summary)\n\n" - } - else if let html = article.contentHTML { + } else if let html = article.contentHTML { let convertedHTML = html.convertingToPlainText() s += "\(convertedHTML)\n\n" } @@ -184,7 +182,6 @@ private extension ArticlePasteboardWriter { guard let authors = article.authors, !authors.isEmpty else { return nil } - return authors.map{ authorDictionary($0) } + return authors.map { authorDictionary($0) } } } - diff --git a/Mac/MainWindow/Timeline/Cell/TimelineCellData.swift b/Mac/MainWindow/Timeline/Cell/TimelineCellData.swift index 837f1bffe..3c5c70304 100644 --- a/Mac/MainWindow/Timeline/Cell/TimelineCellData.swift +++ b/Mac/MainWindow/Timeline/Cell/TimelineCellData.swift @@ -60,7 +60,7 @@ import Articles self.starred = article.status.starred } - init() { //Empty + init() { // Empty self.title = "" self.text = "" self.dateString = "" diff --git a/Mac/MainWindow/Timeline/Cell/TimelineCellLayout.swift b/Mac/MainWindow/Timeline/Cell/TimelineCellLayout.swift index e925eda03..8ce8e3ac9 100644 --- a/Mac/MainWindow/Timeline/Cell/TimelineCellLayout.swift +++ b/Mac/MainWindow/Timeline/Cell/TimelineCellLayout.swift @@ -42,8 +42,7 @@ import RSCore if height > 0.1 { self.height = height - } - else { + } else { self.height = [feedNameRect, dateRect, titleRect, summaryRect, textRect, unreadIndicatorRect, iconImageRect].maxY() + paddingBottom } } @@ -62,8 +61,7 @@ import RSCore var lastTextRect = titleRect if numberOfLinesForTitle == 0 { lastTextRect = textRect - } - else if numberOfLinesForTitle < appearance.titleNumberOfLines { + } else if numberOfLinesForTitle < appearance.titleNumberOfLines { if summaryRect.height > 0.1 { lastTextRect = summaryRect } @@ -124,13 +122,13 @@ import RSCore return (r, sizeInfo.numberOfLinesUsed) } - static func rectForSummary(_ textBoxRect: NSRect, _ titleRect: NSRect, _ titleNumberOfLines: Int, _ appearance: TimelineCellAppearance, _ cellData: TimelineCellData) -> NSRect { + static func rectForSummary(_ textBoxRect: NSRect, _ titleRect: NSRect, _ titleNumberOfLines: Int, _ appearance: TimelineCellAppearance, _ cellData: TimelineCellData) -> NSRect { if titleNumberOfLines >= appearance.titleNumberOfLines || cellData.text.isEmpty { return NSRect.zero } var r = textBoxRect - r.origin.y = NSMaxY(titleRect) + r.origin.y = titleRect.maxY let summaryNumberOfLines = appearance.titleNumberOfLines - titleNumberOfLines let sizeInfo = MultilineTextFieldSizer.size(for: cellData.text, font: appearance.textOnlyFont, numberOfLines: summaryNumberOfLines, width: Int(textBoxRect.width)) @@ -161,9 +159,9 @@ import RSCore static func rectForDate(_ textBoxRect: NSRect, _ rectAbove: NSRect, _ appearance: TimelineCellAppearance, _ cellData: TimelineCellData) -> NSRect { let textFieldSize = SingleLineTextFieldSizer.size(for: cellData.dateString, font: appearance.dateFont) - var r = NSZeroRect + var r = NSRect.zero r.size = textFieldSize - r.origin.y = NSMaxY(rectAbove) + appearance.titleBottomMargin + r.origin.y = rectAbove.maxY + appearance.titleBottomMargin r.size.width = textFieldSize.width r.origin.x = textBoxRect.maxX - textFieldSize.width @@ -173,11 +171,11 @@ import RSCore static func rectForFeedName(_ textBoxRect: NSRect, _ dateRect: NSRect, _ appearance: TimelineCellAppearance, _ cellData: TimelineCellData) -> NSRect { if cellData.showFeedName == .none { - return NSZeroRect + return NSRect.zero } let textFieldSize = SingleLineTextFieldSizer.size(for: cellData.feedName, font: appearance.feedNameFont) - var r = NSZeroRect + var r = NSRect.zero r.size = textFieldSize r.origin.y = dateRect.minY r.origin.x = textBoxRect.origin.x @@ -188,7 +186,7 @@ import RSCore static func rectForUnreadIndicator(_ appearance: TimelineCellAppearance, _ titleRect: NSRect) -> NSRect { - var r = NSZeroRect + var r = NSRect.zero r.size = NSSize(width: appearance.unreadCircleDimension, height: appearance.unreadCircleDimension) r.origin.x = appearance.cellPadding.left r.origin.y = titleRect.minY + 6 @@ -235,4 +233,3 @@ private extension Array where Element == NSRect { return y } } - diff --git a/Mac/MainWindow/Timeline/Cell/TimelineTableCellView.swift b/Mac/MainWindow/Timeline/Cell/TimelineTableCellView.swift index 24111455c..89c10788d 100644 --- a/Mac/MainWindow/Timeline/Cell/TimelineTableCellView.swift +++ b/Mac/MainWindow/Timeline/Cell/TimelineTableCellView.swift @@ -14,7 +14,7 @@ final class TimelineTableCellView: NSTableCellView { private let titleView = TimelineTableCellView.multiLineTextField() private let summaryView = TimelineTableCellView.multiLineTextField() private let textView = TimelineTableCellView.multiLineTextField() - private let unreadIndicatorView = UnreadIndicatorView(frame: NSZeroRect) + private let unreadIndicatorView = UnreadIndicatorView(frame: NSRect.zero) private let dateView = TimelineTableCellView.singleLineTextField() private let feedNameView = TimelineTableCellView.singleLineTextField() @@ -65,7 +65,7 @@ final class TimelineTableCellView: NSTableCellView { commonInit() } - required init?(coder: NSCoder) { + required init?(coder: NSCoder) { super.init(coder: coder) commonInit() } @@ -91,7 +91,7 @@ final class TimelineTableCellView: NSTableCellView { override func layout() { - resizeSubviews(withOldSize: NSZeroSize) + resizeSubviews(withOldSize: NSSize.zero) } override func resizeSubviews(withOldSize oldSize: NSSize) { @@ -149,8 +149,7 @@ private extension TimelineTableCellView { if Int(floor(rect.height)) == 0 || Int(floor(rect.width)) == 0 { hideView(textField) - } - else { + } else { showView(textField) textField.setFrame(ifNotEqualTo: rect) } @@ -300,7 +299,11 @@ private extension TimelineTableCellView { } func showOrHideView(_ view: NSView, _ shouldHide: Bool) { - shouldHide ? hideView(view) : showView(view) + if shouldHide { + hideView(view) + } else { + showView(view) + } } func updateSubviews() { diff --git a/Mac/MainWindow/Timeline/TimelineContainerView.swift b/Mac/MainWindow/Timeline/TimelineContainerView.swift index e75475405..5b79c1a8b 100644 --- a/Mac/MainWindow/Timeline/TimelineContainerView.swift +++ b/Mac/MainWindow/Timeline/TimelineContainerView.swift @@ -9,7 +9,6 @@ import AppKit final class TimelineContainerView: NSView { - private var contentViewConstraints: [NSLayoutConstraint]? var contentView: NSView? { @@ -34,4 +33,3 @@ final class TimelineContainerView: NSView { } } } - diff --git a/Mac/MainWindow/Timeline/TimelineContainerViewController.swift b/Mac/MainWindow/Timeline/TimelineContainerViewController.swift index 592189eb1..e581ea199 100644 --- a/Mac/MainWindow/Timeline/TimelineContainerViewController.swift +++ b/Mac/MainWindow/Timeline/TimelineContainerViewController.swift @@ -114,7 +114,7 @@ final class TimelineContainerViewController: NSViewController { return false } for object in representedObjects { - guard let _ = currentObjects.firstIndex(where: { $0 === object } ) else { + if currentObjects.firstIndex(where: { $0 === object }) == nil { return false } } @@ -183,8 +183,7 @@ private extension TimelineContainerViewController { func mode(for timelineViewController: TimelineViewController) -> TimelineSourceMode { if timelineViewController === regularTimelineViewController { return .regular - } - else if timelineViewController === searchTimelineViewController { + } else if timelineViewController === searchTimelineViewController { return .search } assertionFailure("Expected timelineViewController to match either regular or search timelineViewController, but it doesn’t.") diff --git a/Mac/MainWindow/Timeline/TimelineViewController+ContextualMenus.swift b/Mac/MainWindow/Timeline/TimelineViewController+ContextualMenus.swift index 9f9fb92de..c7db48812 100644 --- a/Mac/MainWindow/Timeline/TimelineViewController+ContextualMenus.swift +++ b/Mac/MainWindow/Timeline/TimelineViewController+ContextualMenus.swift @@ -248,11 +248,11 @@ private extension TimelineViewController { } func markAboveReadMenuItem(_ articles: [Article]) -> NSMenuItem { - return menuItem(NSLocalizedString("Mark Above as Read", comment: "Command"), #selector(markAboveArticlesReadFromContextualMenu(_:)), articles, image: Assets.Images.markAboveAsRead) + return menuItem(NSLocalizedString("Mark Above as Read", comment: "Command"), #selector(markAboveArticlesReadFromContextualMenu(_:)), articles, image: Assets.Images.markAboveAsRead) } func markBelowReadMenuItem(_ articles: [Article]) -> NSMenuItem { - return menuItem(NSLocalizedString("Mark Below as Read", comment: "Command"), #selector(markBelowArticlesReadFromContextualMenu(_:)), articles, image: Assets.Images.markBelowAsRead) + return menuItem(NSLocalizedString("Mark Below as Read", comment: "Command"), #selector(markBelowArticlesReadFromContextualMenu(_:)), articles, image: Assets.Images.markBelowAsRead) } func selectFeedInSidebarMenuItem(_ feed: Feed) -> NSMenuItem { diff --git a/Mac/MainWindow/Timeline/TimelineViewController.swift b/Mac/MainWindow/Timeline/TimelineViewController.swift index c6cd122f0..e03d09d69 100644 --- a/Mac/MainWindow/Timeline/TimelineViewController.swift +++ b/Mac/MainWindow/Timeline/TimelineViewController.swift @@ -12,7 +12,7 @@ import Articles import Account import os.log -@MainActor protocol TimelineDelegate: AnyObject { +@MainActor protocol TimelineDelegate: AnyObject { func timelineSelectionDidChange(_: TimelineViewController, selectedArticles: [Article]?) func timelineRequestedFeedSelection(_: TimelineViewController, feed: Feed) func timelineInvalidatedRestorationState(_: TimelineViewController) @@ -405,8 +405,7 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr if markAsRead { markSelectedArticlesAsRead(sender) - } - else { + } else { markSelectedArticlesAsUnread(sender) } } @@ -563,8 +562,7 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr for article in selectedArticles { if cutoffDate == nil { cutoffDate = article.logicalDatePublished - } - else if cutoffDate! > article.logicalDatePublished { + } else if cutoffDate! > article.logicalDatePublished { cutoffDate = article.logicalDatePublished } } @@ -605,7 +603,7 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr // MARK: - Navigation - func goToDeepLink(for userInfo: [AnyHashable : Any]) { + func goToDeepLink(for userInfo: [AnyHashable: Any]) { guard let articleID = userInfo[ArticlePathKey.articleID] as? String else { return } if isReadFiltered ?? false { @@ -633,10 +631,7 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr } func canGoToNextUnread(wrappingToTop wrapping: Bool = false) -> Bool { - guard let _ = indexOfNextUnreadArticle(wrappingToTop: wrapping) else { - return false - } - return true + return indexOfNextUnreadArticle(wrappingToTop: wrapping) != nil } func indexOfNextUnreadArticle(wrappingToTop wrapping: Bool = false) -> Int? { @@ -913,8 +908,7 @@ extension TimelineViewController: NSTableViewDelegate { cell.cellAppearance = showIcons ? cellAppearanceWithIcon : cellAppearance if let article = articles.articleAtRow(row) { configureTimelineCell(cell, article: article) - } - else { + } else { makeTimelineCellEmpty(cell) } } @@ -996,25 +990,25 @@ extension TimelineViewController: NSTableViewDelegate { } switch edge { - case .leading: - let action = NSTableViewRowAction(style: .regular, title: article.status.read ? "Unread" : "Read") { (action, row) in - self.toggleArticleRead(article); - tableView.rowActionsVisible = false - } - action.image = article.status.read ? Assets.Images.swipeMarkUnread : Assets.Images.swipeMarkRead - return [action] + case .leading: + let action = NSTableViewRowAction(style: .regular, title: article.status.read ? "Unread" : "Read") { (_, _) in + self.toggleArticleRead(article) + tableView.rowActionsVisible = false + } + action.image = article.status.read ? Assets.Images.swipeMarkUnread : Assets.Images.swipeMarkRead + return [action] - case .trailing: - let action = NSTableViewRowAction(style: .regular, title: article.status.starred ? "Unstar" : "Star") { (action, row) in - self.toggleArticleStarred(article); - tableView.rowActionsVisible = false - } + case .trailing: + let action = NSTableViewRowAction(style: .regular, title: article.status.starred ? "Unstar" : "Star") { (_, _) in + self.toggleArticleStarred(article) + tableView.rowActionsVisible = false + } action.backgroundColor = Assets.Colors.star - action.image = article.status.starred ? Assets.Images.swipeMarkUnstarred : Assets.Images.swipeMarkStarred - return [action] + action.image = article.status.starred ? Assets.Images.swipeMarkUnstarred : Assets.Images.swipeMarkStarred + return [action] - @unknown default: - Self.logger.error("TimelineViewController: unknown edge \(edge.rawValue, privacy: .public)") + @unknown default: + Self.logger.error("TimelineViewController: unknown edge \(edge.rawValue, privacy: .public)") } return [] @@ -1221,7 +1215,7 @@ private extension TimelineViewController { func fetchUnsortedArticlesSync(for representedObjects: [Any]) -> Set
{ cancelPendingAsyncFetches() - let fetchers = representedObjects.compactMap{ $0 as? ArticleFetcher } + let fetchers = representedObjects.compactMap { $0 as? ArticleFetcher } if fetchers.isEmpty { return Set
() } @@ -1316,8 +1310,7 @@ private extension TimelineViewController { return true } } - } - else if let folder = representedObject as? Folder { + } else if let folder = representedObject as? Folder { for oneFeed in feeds { if folder.hasFeed(with: oneFeed.feedID) || folder.hasFeed(withURL: oneFeed.url) { return true diff --git a/Mac/Preferences/Accounts/AccountsAddCloudKitWindowController.swift b/Mac/Preferences/Accounts/AccountsAddCloudKitWindowController.swift index d2bcb6b63..be9996ea5 100644 --- a/Mac/Preferences/Accounts/AccountsAddCloudKitWindowController.swift +++ b/Mac/Preferences/Accounts/AccountsAddCloudKitWindowController.swift @@ -52,7 +52,7 @@ final class AccountsAddCloudKitWindowController: NSWindowController { return } - let _ = AccountManager.shared.createAccount(type: .cloudKit) + _ = AccountManager.shared.createAccount(type: .cloudKit) hostWindow.endSheet(window, returnCode: NSApplication.ModalResponse.OK) } } diff --git a/Mac/Preferences/Accounts/AddAccountHelpView.swift b/Mac/Preferences/Accounts/AddAccountHelpView.swift index eee6f2224..efd039c43 100644 --- a/Mac/Preferences/Accounts/AddAccountHelpView.swift +++ b/Mac/Preferences/Accounts/AddAccountHelpView.swift @@ -25,8 +25,7 @@ struct AddAccountHelpView: View { ForEach(accountTypes, id: \.self) { accountType in if accountType == .cloudKit && hasiCloudAccount { EmptyView() - } - else if !(AppDefaults.shared.isDeveloperBuild && accountType.isDeveloperRestricted) { + } else if !(AppDefaults.shared.isDeveloperBuild && accountType.isDeveloperRestricted) { Button(action: { delegate?.presentSheetForAccount(accountType) }, label: { diff --git a/Mac/Preferences/Advanced/AdvancedPreferencesViewController.swift b/Mac/Preferences/Advanced/AdvancedPreferencesViewController.swift index 462a43d73..45e2b1a6a 100644 --- a/Mac/Preferences/Advanced/AdvancedPreferencesViewController.swift +++ b/Mac/Preferences/Advanced/AdvancedPreferencesViewController.swift @@ -57,8 +57,7 @@ private extension AdvancedPreferencesViewController { func updateUI() { if wantsTestBuilds { testBuildsButton.state = .on - } - else { + } else { releaseBuildsButton.state = .on } } diff --git a/Mac/Preferences/PreferencesControlsBackgroundView.swift b/Mac/Preferences/PreferencesControlsBackgroundView.swift index 5625f3d3d..f5b59ad0e 100644 --- a/Mac/Preferences/PreferencesControlsBackgroundView.swift +++ b/Mac/Preferences/PreferencesControlsBackgroundView.swift @@ -29,7 +29,7 @@ final class PreferencesControlsBackgroundView: NSView { let fillColor = self.effectiveAppearance.isDarkMode ? darkModeFillColor : lightModeFillColor fillColor.setFill() - let r = NSIntersectionRect(dirtyRect, bounds) + let r = dirtyRect.intersection(bounds) r.fill() let borderColor = self.effectiveAppearance.isDarkMode ? darkModeBorderColor : lightModeBorderColor diff --git a/Mac/Preferences/PreferencesTableViewBackgroundView.swift b/Mac/Preferences/PreferencesTableViewBackgroundView.swift index 21839a895..6450f242c 100644 --- a/Mac/Preferences/PreferencesTableViewBackgroundView.swift +++ b/Mac/Preferences/PreferencesTableViewBackgroundView.swift @@ -17,7 +17,7 @@ final class PreferencesTableViewBackgroundView: NSView { let color = self.effectiveAppearance.isDarkMode ? darkBorderColor : lightBorderColor color.setFill() - let r = NSIntersectionRect(dirtyRect, bounds) + let r = dirtyRect.intersection(bounds) r.fill() } } diff --git a/Mac/Preferences/PreferencesWindowController.swift b/Mac/Preferences/PreferencesWindowController.swift index 0d0e7d3ad..5dcb8f361 100644 --- a/Mac/Preferences/PreferencesWindowController.swift +++ b/Mac/Preferences/PreferencesWindowController.swift @@ -27,7 +27,7 @@ private struct ToolbarItemIdentifier { static let Advanced = "Advanced" } -final class PreferencesWindowController : NSWindowController, NSToolbarDelegate { +final class PreferencesWindowController: NSWindowController, NSToolbarDelegate { private let windowWidth = CGFloat(512.0) // Width is constant for all views; only the height changes private var viewControllers = [String: NSViewController]() @@ -140,8 +140,7 @@ private extension PreferencesWindowController { if let currentView = currentView { window!.contentView?.replaceSubview(currentView, with: newViewController.view) - } - else { + } else { window!.contentView?.addSubview(newViewController.view) } @@ -168,17 +167,17 @@ private extension PreferencesWindowController { let windowFrame = window!.frame let contentViewFrame = window!.contentView!.frame - let deltaHeight = NSHeight(contentViewFrame) - NSHeight(viewFrame) - let heightForWindow = NSHeight(windowFrame) - deltaHeight - let windowOriginY = NSMinY(windowFrame) + deltaHeight + let deltaHeight = contentViewFrame.height - viewFrame.height + let heightForWindow = windowFrame.height - deltaHeight + let windowOriginY = windowFrame.minY + deltaHeight var updatedWindowFrame = windowFrame updatedWindowFrame.size.height = heightForWindow updatedWindowFrame.origin.y = windowOriginY - updatedWindowFrame.size.width = windowWidth //NSWidth(viewFrame) + updatedWindowFrame.size.width = windowWidth // NSWidth(viewFrame) var updatedViewFrame = viewFrame - updatedViewFrame.origin = NSZeroPoint + updatedViewFrame.origin = NSPoint.zero updatedViewFrame.size.width = windowWidth if viewFrame != updatedViewFrame { view.frame = updatedViewFrame diff --git a/Mac/Resources/Credits.rtf b/Mac/Resources/Credits.rtf index 46022b180..c72062967 100644 --- a/Mac/Resources/Credits.rtf +++ b/Mac/Resources/Credits.rtf @@ -2,7 +2,7 @@ \cocoatextscaling0\cocoaplatform0{\fonttbl\f0\fnil\fcharset0 SFPro-Bold;\f1\fnil\fcharset0 SFPro-Regular;} {\colortbl;\red255\green255\blue255;\red0\green0\blue0;} {\*\expandedcolortbl;;\cssrgb\c0\c0\c0\cname textColor;} -\margl1440\margr1440\vieww14060\viewh15660\viewkind0 +\paperw12240\paperh15840\margl1440\margr1440\vieww14060\viewh15660\viewkind0 \deftab720 \pard\pardeftab720\sa60\partightenfactor0 @@ -14,16 +14,16 @@ \cf2 Contributing Developers \ \pard\pardeftab720\sl168\slmult1\sa60\partightenfactor0 {\field{\*\fldinst{HYPERLINK "https://stuartbreckenridge.net/"}}{\fldrslt \cf2 Stuart Breckenridge}}, {\field{\*\fldinst{HYPERLINK "https://github.com/vincode-io"}}{\fldrslt Maurice Parker}}\ -\pard\pardeftab720\sl168\slmult1\sa60\partightenfactor0 -\cf2 \ +\ App Icon\ -{\field{\*\fldinst{HYPERLINK "https://twitter.com/BradEllis"}}{\fldrslt Brad Ellis}}\ +\pard\pardeftab720\sl168\slmult1\sa60\partightenfactor0 +{\field{\*\fldinst{HYPERLINK "https://hachyderm.io/@bradellis"}}{\fldrslt \cf2 Brad Ellis}}\ \ Feedly Syncing\ {\field{\*\fldinst{HYPERLINK "https://twitter.com/kielgillard"}}{\fldrslt Kiel Gillard}}\ \ NewsBlur Syncing\ -{\field{\*\fldinst{HYPERLINK "https://twitter.com/quanganhdo"}}{\fldrslt Anh Do}}\ +{\field{\*\fldinst{HYPERLINK "https://mastodon.social/@anhdo"}}{\fldrslt Anh Do}}\ \ Under-the-Hood Magic and CSS Stylin's\ {\field{\*\fldinst{HYPERLINK "https://github.com/wevah"}}{\fldrslt Nate Weaver}}\ @@ -31,8 +31,14 @@ Under-the-Hood Magic and CSS Stylin's\ Newsfoot (JS footnote displayer)\ {\field{\*\fldinst{HYPERLINK "https://github.com/brehaut/"}}{\fldrslt Andrew Brehaut}}\ \ +\pard\pardeftab720\sl168\slmult1\sa60\partightenfactor0 +\cf2 Help Book\ +{\field{\*\fldinst{HYPERLINK "https://github.com/nostodnayr"}}{\fldrslt Ryan Dotson}}\ +\pard\pardeftab720\sl168\slmult1\sa60\partightenfactor0 +\cf2 \ And featuring contributions from\ -{\field{\*\fldinst{HYPERLINK "https://github.com/danielpunkass"}}{\fldrslt Daniel Jalkut}}, {\field{\*\fldinst{HYPERLINK "https://rhonabwy.com/"}}{\fldrslt Joe Heck}}, {\field{\*\fldinst{HYPERLINK "https://github.com/olofhellman"}}{\fldrslt Olof Hellman}}, {\field{\*\fldinst{HYPERLINK "https://blog.rizwan.dev/"}}{\fldrslt Rizwan Mohamed Ibrahim}}, {\field{\*\fldinst{HYPERLINK "https://twitter.com/philviso"}}{\fldrslt Phil Viso}}, and {\field{\*\fldinst{HYPERLINK "https://github.com/Ranchero-Software/NetNewsWire/graphs/contributors"}}{\fldrslt many more}}!\ +\pard\pardeftab720\sl168\slmult1\sa60\partightenfactor0 +{\field{\*\fldinst{HYPERLINK "https://github.com/danielpunkass"}}{\fldrslt \cf2 Daniel Jalkut}}, {\field{\*\fldinst{HYPERLINK "https://rhonabwy.com/"}}{\fldrslt Joe Heck}}, {\field{\*\fldinst{HYPERLINK "https://github.com/olofhellman"}}{\fldrslt Olof Hellman}}, {\field{\*\fldinst{HYPERLINK "https://blog.rizwan.dev/"}}{\fldrslt Rizwan Mohamed Ibrahim}}, {\field{\*\fldinst{HYPERLINK "https://github.com/philviso"}}{\fldrslt Phil Viso}}, and {\field{\*\fldinst{HYPERLINK "https://github.com/Ranchero-Software/NetNewsWire/graphs/contributors"}}{\fldrslt many more}}!\ \pard\pardeftab720\li360\sa60\partightenfactor0 \cf2 \ \pard\pardeftab720\sa60\partightenfactor0 diff --git a/Mac/SafariExtension/SafariExtensionHandler.swift b/Mac/SafariExtension/SafariExtensionHandler.swift index 88d8a92df..95d079e7f 100644 --- a/Mac/SafariExtension/SafariExtensionHandler.swift +++ b/Mac/SafariExtension/SafariExtensionHandler.swift @@ -29,7 +29,7 @@ final class SafariExtensionHandler: SFSafariExtensionHandler { } // Maps from UUID to a validation wrapper - nonisolated(unsafe) static var gPingPongMap = Dictionary() + nonisolated(unsafe) static var gPingPongMap = [String: ValidationWrapper]() static let validationQueue = DispatchQueue(label: "Toolbar Validation") // Bottleneck for calling through to a validation handler we have saved, and removing it from the list. @@ -40,8 +40,8 @@ final class SafariExtensionHandler: SFSafariExtensionHandler { } } - override func messageReceived(withName messageName: String, from page: SFSafariPage, userInfo: [String : Any]?) { - if (messageName == "subscribeToFeed") { + override func messageReceived(withName messageName: String, from page: SFSafariPage, userInfo: [String: Any]?) { + if messageName == "subscribeToFeed" { if var feedURLString = userInfo?["url"] as? String { var openInDefaultBrowser = false @@ -61,12 +61,11 @@ final class SafariExtensionHandler: SFSafariExtensionHandler { NSWorkspace.shared.open(feedURL) } } - } - else if (messageName == "pong") { + } else if messageName == "pong" { if let validationIDString = userInfo?["validationID"] as? String { // Should we validate the button? let shouldValidate = userInfo?["shouldValidate"] as? Bool ?? false - SafariExtensionHandler.callValidationHandler(forHandlerID: validationIDString, withShouldValidate:shouldValidate) + SafariExtensionHandler.callValidationHandler(forHandlerID: validationIDString, withShouldValidate: shouldValidate) } } } @@ -97,7 +96,7 @@ final class SafariExtensionHandler: SFSafariExtensionHandler { if thisValidationID != uniqueValidationID { // Default to valid ... we'll know soon enough whether the latest state // is actually still valid or not... - SafariExtensionHandler.callValidationHandler(forHandlerID: thisValidationID, withShouldValidate: true); + SafariExtensionHandler.callValidationHandler(forHandlerID: thisValidationID, withShouldValidate: true) } } @@ -108,17 +107,17 @@ final class SafariExtensionHandler: SFSafariExtensionHandler { // a timeout period has elapsed window.getActiveTab { (activeTab) in guard let activeTab = activeTab else { - SafariExtensionHandler.callValidationHandler(forHandlerID: uniqueValidationID, withShouldValidate:false); + SafariExtensionHandler.callValidationHandler(forHandlerID: uniqueValidationID, withShouldValidate: false) return } activeTab.getActivePage { (activePage) in guard let activePage = activePage else { - SafariExtensionHandler.callValidationHandler(forHandlerID: uniqueValidationID, withShouldValidate:false); - return + SafariExtensionHandler.callValidationHandler(forHandlerID: uniqueValidationID, withShouldValidate: false) + return } - activePage.getPropertiesWithCompletionHandler { (pageProperties) in + activePage.getPropertiesWithCompletionHandler { pageProperties in if let isActive = pageProperties?.isActive { if isActive { // Capture the uniqueValidationID to ensure it doesn't change out from under us on a future call @@ -127,7 +126,7 @@ final class SafariExtensionHandler: SFSafariExtensionHandler { let pongTimeoutInNanoseconds = Int(Double(NSEC_PER_SEC) * 0.5) let timeoutDeadline = DispatchTime.now() + DispatchTimeInterval.nanoseconds(pongTimeoutInNanoseconds) DispatchQueue.main.asyncAfter(deadline: timeoutDeadline, execute: { [timedOutValidationID = uniqueValidationID] in - SafariExtensionHandler.callValidationHandler(forHandlerID: timedOutValidationID, withShouldValidate:false) + SafariExtensionHandler.callValidationHandler(forHandlerID: timedOutValidationID, withShouldValidate: false) }) } } diff --git a/Mac/Scripting/Account+Scriptability.swift b/Mac/Scripting/Account+Scriptability.swift index 46c7c03e0..11116ad84 100644 --- a/Mac/Scripting/Account+Scriptability.swift +++ b/Mac/Scripting/Account+Scriptability.swift @@ -65,7 +65,7 @@ import RSCore self.classDescription as! NSScriptClassDescription } - func deleteElement(_ element:ScriptingObject) { + func deleteElement(_ element: ScriptingObject) { if let scriptableFolder = element as? ScriptableFolder { BatchUpdate.shared.perform { account.removeFolder(scriptableFolder.folder) { _ in @@ -93,8 +93,8 @@ import RSCore // MARK: --- Scriptable elements --- @objc(feeds) - var feeds: NSArray { - account.topLevelFeeds.map { ScriptableFeed($0, container:self) } as NSArray + var feeds: NSArray { + account.topLevelFeeds.map { ScriptableFeed($0, container: self) } as NSArray } @objc(countOfFeeds) @@ -116,23 +116,23 @@ import RSCore guard let feed = account.existingFeed(withFeedID: id) else { return nil } - return ScriptableFeed(feed, container:self) + return ScriptableFeed(feed, container: self) } @objc(valueInFeedsWithName:) func valueInFeeds(withName name: String) -> ScriptableFeed? { let feeds = Array(account.flattenedFeeds()) - guard let feed = feeds.first(where:{$0.name == name}) else { + guard let feed = feeds.first(where: { $0.name == name }) else { return nil } - return ScriptableFeed(feed, container:self) + return ScriptableFeed(feed, container: self) } @objc(folders) - var folders: NSArray { + var folders: NSArray { let foldersSet = account.folders ?? Set() let folders = Array(foldersSet) - return folders.map { ScriptableFolder($0, container:self) } as NSArray + return folders.map { ScriptableFolder($0, container: self) } as NSArray } @objc(countOfFolders) @@ -151,20 +151,20 @@ import RSCore } @objc(valueInFoldersWithUniqueID:) - func valueInFolders(withUniqueID id:NSNumber) -> ScriptableFolder? { + func valueInFolders(withUniqueID id: NSNumber) -> ScriptableFolder? { let folderId = id.intValue let foldersSet = account.folders ?? Set() let folders = Array(foldersSet) - guard let folder = folders.first(where:{$0.folderID == folderId}) else { + guard let folder = folders.first(where: { $0.folderID == folderId }) else { return nil } - return ScriptableFolder(folder, container:self) + return ScriptableFolder(folder, container: self) } // MARK: --- Scriptable properties --- @objc(allFeeds) - var allFeeds: NSArray { + var allFeeds: NSArray { let allFeeds = account.flattenedFeeds() let scriptableFeeds = allFeeds.map { feed in ScriptableFeed(feed, container: self) @@ -191,7 +191,7 @@ import RSCore guard let feed = account.existingFeed(withFeedID: id) else { return nil } - return ScriptableFeed(feed, container:self) + return ScriptableFeed(feed, container: self) } @objc(valueInAllFeedsWithName:) @@ -200,12 +200,12 @@ import RSCore guard let feed = feeds.first(where: {$0.name == name}) else { return nil } - return ScriptableFeed(feed, container:self) + return ScriptableFeed(feed, container: self) } @objc(opmlRepresentation) - var opmlRepresentation: String { - self.account.OPMLString(indentLevel:0) + var opmlRepresentation: String { + self.account.OPMLString(indentLevel: 0) } @objc(accountType) diff --git a/Mac/Scripting/AppDelegate+Scriptability.swift b/Mac/Scripting/AppDelegate+Scriptability.swift index 20710ad6f..d48d78c93 100644 --- a/Mac/Scripting/AppDelegate+Scriptability.swift +++ b/Mac/Scripting/AppDelegate+Scriptability.swift @@ -25,9 +25,9 @@ import Articles } @MainActor protocol ScriptingAppDelegate { - var scriptingCurrentArticle: Article? {get} - var scriptingSelectedArticles: [Article] {get} - var scriptingMainWindowController:ScriptingMainWindowController? {get} + var scriptingCurrentArticle: Article? {get} + var scriptingSelectedArticles: [Article] {get} + var scriptingMainWindowController: ScriptingMainWindowController? {get} } // Wrapper to safely transfer non-Sendable values across isolation boundaries @@ -60,7 +60,7 @@ extension AppDelegate: AppDelegateAppleEvents { if let themeURL = URL(string: themeURLString) { let request = URLRequest(url: themeURL) - let task = URLSession.shared.downloadTask(with: request) { location, response, error in + let task = URLSession.shared.downloadTask(with: request) { location, _, error in guard let location = location else { return } @@ -96,7 +96,7 @@ extension AppDelegate: AppDelegateAppleEvents { } } -final class NetNewsWireCreateElementCommand : NSCreateCommand { +final class NetNewsWireCreateElementCommand: NSCreateCommand { // AppleScript commands always execute on the main thread, so using assumeIsolated is safe // even though NSCreateCommand doesn't have concurrency annotations nonisolated override func performDefaultImplementation() -> Any? { @@ -105,10 +105,10 @@ final class NetNewsWireCreateElementCommand : NSCreateCommand { let instance = unsafeSelf.value let classDescription: NSScriptClassDescription = instance.createClassDescription let command: NSCreateCommand = instance - if (classDescription.className == "feed") { - return UnsafeSendable(value: ScriptableFeed.handleCreateElement(command:command)) - } else if (classDescription.className == "folder") { - return UnsafeSendable(value: ScriptableFolder.handleCreateElement(command:command)) + if classDescription.className == "feed" { + return UnsafeSendable(value: ScriptableFeed.handleCreateElement(command: command)) + } else if classDescription.className == "folder" { + return UnsafeSendable(value: ScriptableFolder.handleCreateElement(command: command)) } return UnsafeSendable(value: nil) } @@ -124,7 +124,7 @@ final class NetNewsWireCreateElementCommand : NSCreateCommand { is ambiguity about whether specifiers are lists or single objects, the code switches based on which it is. */ -final class NetNewsWireDeleteCommand : NSDeleteCommand { +final class NetNewsWireDeleteCommand: NSDeleteCommand { /* delete(objectToDelete:, from container:) @@ -132,10 +132,10 @@ final class NetNewsWireDeleteCommand : NSDeleteCommand { Here the code unravels the case of objectToDelete being a list or a single object, ultimately calling container.deleteElement(element) for each element to delete */ - @MainActor func delete(objectToDelete:Any, from container:ScriptingObjectContainer) { + @MainActor func delete(objectToDelete: Any, from container: ScriptingObjectContainer) { if let objectList = objectToDelete as? [Any] { for nthObject in objectList { - self.delete(objectToDelete:nthObject, from:container) + self.delete(objectToDelete: nthObject, from: container) } } else if let element = objectToDelete as? ScriptingObject { container.deleteElement(element) @@ -151,14 +151,14 @@ final class NetNewsWireDeleteCommand : NSDeleteCommand { After resolving, we call delete(objectToDelete:, from container:) with the container and the resolved objects */ - @MainActor func delete(specifier:NSScriptObjectSpecifier, from container:Any) { + @MainActor func delete(specifier: NSScriptObjectSpecifier, from container: Any) { if let containerList = container as? [Any] { for nthObject in containerList { - self.delete(specifier:specifier, from:nthObject) + self.delete(specifier: specifier, from: nthObject) } } else if let container = container as? ScriptingObjectContainer { - if let resolvedObjects = specifier.objectsByEvaluating(withContainers:container) { - self.delete(objectToDelete:resolvedObjects, from:container) + if let resolvedObjects = specifier.objectsByEvaluating(withContainers: container) { + self.delete(objectToDelete: resolvedObjects, from: container) } } } @@ -176,14 +176,14 @@ final class NetNewsWireDeleteCommand : NSDeleteCommand { MainActor.assumeIsolated { let instance = unsafeSelf.value if let receiverObjects = instance.receiversSpecifier?.objectsByEvaluatingSpecifier { - instance.delete(specifier:instance.keySpecifier, from:receiverObjects) + instance.delete(specifier: instance.keySpecifier, from: receiverObjects) } } return nil } } -final class NetNewsWireExistsCommand : NSExistsCommand { +final class NetNewsWireExistsCommand: NSExistsCommand { // cocoa default behavior doesn't work here, because of cases where we define an object's property // to be another object type. e.g., 'permalink of the current article' parses as @@ -195,9 +195,10 @@ final class NetNewsWireExistsCommand : NSExistsCommand { // The wrinkle is that it is possible that the direct object is a list, so we need to // handle that case as well - override func performDefaultImplementation() -> Any? { - guard let result = super.performDefaultImplementation() else { return NSNumber(booleanLiteral:false) } - return result - } + override func performDefaultImplementation() -> Any? { + guard let result = super.performDefaultImplementation() else { + return false as NSNumber + } + return result + } } - diff --git a/Mac/Scripting/Article+Scriptability.swift b/Mac/Scripting/Article+Scriptability.swift index 6f021331e..d47ca8a20 100644 --- a/Mac/Scripting/Article+Scriptability.swift +++ b/Mac/Scripting/Article+Scriptability.swift @@ -48,64 +48,64 @@ import Articles return self.classDescription as! NSScriptClassDescription } - func deleteElement(_ element:ScriptingObject) { - print ("delete event not handled") + func deleteElement(_ element: ScriptingObject) { + print("delete event not handled") } // MARK: - Scriptable properties @objc(url) - var url: String? { + var url: String? { article.preferredLink } @objc(permalink) - var permalink: String? { + var permalink: String? { article.link } @objc(externalUrl) - var externalUrl: String? { + var externalUrl: String? { article.externalLink } @objc(title) - var title: String { + var title: String { article.title ?? "" } @objc(contents) - var contents: String { + var contents: String { article.contentText ?? "" } @objc(html) - var html: String { + var html: String { article.contentHTML ?? "" } @objc(summary) - var summary: String { + var summary: String { article.summary ?? "" } @objc(datePublished) - var datePublished: Date? { + var datePublished: Date? { article.datePublished } @objc(dateModified) - var dateModified: Date? { + var dateModified: Date? { article.dateModified } @objc(dateArrived) - var dateArrived: Date { + var dateArrived: Date { article.status.dateArrived } @objc(read) - var read: Bool { + var read: Bool { get { article.status.boolStatus(forKey: .read) } @@ -115,9 +115,9 @@ import Articles } @objc(starred) - var starred: Bool { + var starred: Bool { get { - article.status.boolStatus(forKey:.starred) + article.status.boolStatus(forKey: .starred) } set { markArticles([self.article], statusKey: .starred, flag: newValue) @@ -125,19 +125,19 @@ import Articles } @objc(deleted) - var deleted: Bool { + var deleted: Bool { false } @objc(imageURL) - var imageURL: String { + var imageURL: String { article.imageLink ?? "" } @objc(authors) var authors: NSArray { let articleAuthors = article.authors ?? [] - return articleAuthors.map { ScriptableAuthor($0, container:self) } as NSArray + return articleAuthors.map { ScriptableAuthor($0, container: self) } as NSArray } @objc(feed) diff --git a/Mac/Scripting/Author+Scriptability.swift b/Mac/Scripting/Author+Scriptability.swift index 705a563b4..597dacdfb 100644 --- a/Mac/Scripting/Author+Scriptability.swift +++ b/Mac/Scripting/Author+Scriptability.swift @@ -15,7 +15,7 @@ import Articles let author: Author nonisolated(unsafe) let container: ScriptingObjectContainer - init (_ author: Author, container: ScriptingObjectContainer) { + init(_ author: Author, container: ScriptingObjectContainer) { self.author = author self.container = container } @@ -28,41 +28,41 @@ import Articles @objc(scriptingSpecifierDescriptor) func scriptingSpecifierDescriptor() -> NSScriptObjectSpecifier { - return (self.objectSpecifier ?? NSScriptObjectSpecifier() ) + objectSpecifier ?? NSScriptObjectSpecifier() } - // MARK: --- ScriptingObject protocol --- + // MARK: - ScriptingObject protocol nonisolated var scriptingKey: String { - return "authors" + "authors" } - // MARK: --- UniqueIdScriptingObject protocol --- + // MARK: - UniqueIdScriptingObject protocol @objc(uniqueId) - nonisolated var scriptingUniqueID:Any { - return author.authorID + nonisolated var scriptingUniqueID: Any { + author.authorID } - // MARK: --- Scriptable properties --- + // MARK: - Scriptable properties @objc(url) - var url:String { - return self.author.url ?? "" + var url: String { + author.url ?? "" } @objc(name) - var name:String { - return self.author.name ?? "" + var name: String { + author.name ?? "" } @objc(avatarURL) - var avatarURL:String { - return self.author.avatarURL ?? "" + var avatarURL: String { + author.avatarURL ?? "" } @objc(emailAddress) - var emailAddress:String { - return self.author.emailAddress ?? "" + var emailAddress: String { + author.emailAddress ?? "" } } diff --git a/Mac/Scripting/Folder+Scriptability.swift b/Mac/Scripting/Folder+Scriptability.swift index 6fc533108..7dcaf9896 100644 --- a/Mac/Scripting/Folder+Scriptability.swift +++ b/Mac/Scripting/Folder+Scriptability.swift @@ -16,7 +16,7 @@ import RSCore let folder: Folder nonisolated(unsafe) let container: ScriptingObjectContainer - init (_ folder:Folder, container: ScriptingObjectContainer) { + init (_ folder: Folder, container: ScriptingObjectContainer) { self.folder = folder self.container = container } @@ -39,7 +39,7 @@ import RSCore // but in either case it seems like the accountID would be used as the keydata, so I chose ID @objc(uniqueId) - nonisolated var scriptingUniqueID:Any { + nonisolated var scriptingUniqueID: Any { folder.folderID } @@ -64,7 +64,7 @@ import RSCore or tell account X to make new folder at end with properties {name:"new folder name"} */ - class func handleCreateElement(command: NSCreateCommand) -> Any? { + static func handleCreateElement(command: NSCreateCommand) -> Any? { guard command.isCreateCommand(forClass: "fold") else { return nil } @@ -74,7 +74,7 @@ import RSCore // identifies where the new folder should be created let (account, folder) = command.accountAndFolderForNewChild() guard folder == nil else { - print("support for folders within folders is NYI"); + print("support for folders within folders is NYI") return nil } @@ -94,10 +94,10 @@ import RSCore return nil } - // MARK: --- Scriptable elements --- + // MARK: - Scriptable elements @objc(feeds) - var feeds: NSArray { + var feeds: NSArray { let feeds = Array(folder.topLevelFeeds) return feeds.map { ScriptableFeed($0, container: self) } as NSArray } @@ -112,7 +112,7 @@ import RSCore let sortedArticles = allArticles.sorted(by: { $0.logicalDatePublished > $1.logicalDatePublished }) - return sortedArticles.map { ScriptableArticle($0, container:self) } as NSArray + return sortedArticles.map { ScriptableArticle($0, container: self) } as NSArray } @objc(countOfArticles) @@ -142,12 +142,12 @@ import RSCore // MARK: - Scriptable properties @objc(name) - var name:String { + var name: String { folder.name ?? "" } @objc(opmlRepresentation) - var opmlRepresentation:String { - folder.OPMLString(indentLevel:0) + var opmlRepresentation: String { + folder.OPMLString(indentLevel: 0) } } diff --git a/Mac/Scripting/NSApplication+Scriptability.swift b/Mac/Scripting/NSApplication+Scriptability.swift index 3d6600324..363ebdb54 100644 --- a/Mac/Scripting/NSApplication+Scriptability.swift +++ b/Mac/Scripting/NSApplication+Scriptability.swift @@ -10,15 +10,15 @@ import AppKit import Account import Articles -extension NSApplication : @preconcurrency ScriptingObjectContainer { +extension NSApplication: @preconcurrency ScriptingObjectContainer { // MARK: - ScriptingObjectContainer protocol - - nonisolated var scriptingClassDescription: NSScriptClassDescription { + + nonisolated var scriptingClassDescription: NSScriptClassDescription { return self.classDescription as! NSScriptClassDescription } - func deleteElement(_ element:ScriptingObject) { - print ("delete event not handled") + func deleteElement(_ element: ScriptingObject) { + print("delete event not handled") } nonisolated var scriptingKey: String { @@ -40,10 +40,10 @@ extension NSApplication : @preconcurrency ScriptingObjectContainer { @objc(selectedArticles) func selectedArticles() -> NSArray { let articles = appDelegate.scriptingSelectedArticles - let scriptableArticles:[ScriptableArticle] = articles.compactMap { article in + let scriptableArticles: [ScriptableArticle] = articles.compactMap { article in if let feed = article.feed, let scriptableFeed = ScriptableFeed.scriptableFeed(for: feed) { - return ScriptableArticle(article, container:scriptableFeed) + return ScriptableArticle(article, container: scriptableFeed) } else { return nil } @@ -91,9 +91,11 @@ extension NSApplication : @preconcurrency ScriptingObjectContainer { } @objc(valueInAccountsWithUniqueID:) - func valueInAccounts(withUniqueID id:String) -> ScriptableAccount? { + func valueInAccounts(withUniqueID id: String) -> ScriptableAccount? { let accounts = AccountManager.shared.accounts - guard let account = accounts.first(where:{$0.accountID == id}) else { return nil } + guard let account = accounts.first(where: { $0.accountID == id }) else { + return nil + } return ScriptableAccount(account) } @@ -105,7 +107,7 @@ extension NSApplication : @preconcurrency ScriptingObjectContainer { func allFeeds() -> [Feed] { let accounts = AccountManager.shared.activeAccounts - let emptyFeeds:[Feed] = [] + let emptyFeeds: [Feed] = [] return accounts.reduce(emptyFeeds) { (result, nthAccount) -> [Feed] in let accountFeeds = Array(nthAccount.topLevelFeeds) return result + accountFeeds @@ -114,7 +116,7 @@ extension NSApplication : @preconcurrency ScriptingObjectContainer { @objc(feeds) func feeds() -> NSArray { - allFeeds().map { ScriptableFeed($0, container:self) } as NSArray + allFeeds().map { ScriptableFeed($0, container: self) } as NSArray } @objc(countOfFeeds) @@ -125,14 +127,18 @@ extension NSApplication : @preconcurrency ScriptingObjectContainer { @objc(objectInFeedsAtIndex:) func objectInFeedsAtIndex(_ index: Int) -> ScriptableFeed? { let feeds = allFeeds() - guard index >= 0 && index < feeds.count else { return nil } + guard index >= 0 && index < feeds.count else { + return nil + } return ScriptableFeed(feeds[index], container: self) } @objc(valueInFeedsWithUniqueID:) - func valueInFeeds(withUniqueID id:String) -> ScriptableFeed? { + func valueInFeeds(withUniqueID id: String) -> ScriptableFeed? { let feeds = allFeeds() - guard let feed = feeds.first(where:{$0.feedID == id}) else { return nil } - return ScriptableFeed(feed, container:self) + guard let feed = feeds.first(where: { $0.feedID == id}) else { + return nil + } + return ScriptableFeed(feed, container: self) } } diff --git a/Mac/Scripting/NSScriptCommand+NetNewsWire.swift b/Mac/Scripting/NSScriptCommand+NetNewsWire.swift index 763e67d68..caa7f389a 100644 --- a/Mac/Scripting/NSScriptCommand+NetNewsWire.swift +++ b/Mac/Scripting/NSScriptCommand+NetNewsWire.swift @@ -10,43 +10,51 @@ import Foundation import Account @MainActor extension NSScriptCommand { - func property(forKey key:String) -> Any? { - if let evaluatedArguments = self.evaluatedArguments { + func property(forKey key: String) -> Any? { + if let evaluatedArguments = self.evaluatedArguments { if let props = evaluatedArguments["KeyDictionary"] as? [String: Any] { - return props[key] + return props[key] } } return nil } - func isCreateCommand(forClass whatClass:String) -> Bool { - guard let arguments = self.arguments else {return false} - guard let newObjectClass = arguments["ObjectClass"] as? Int else {return false} - guard (newObjectClass.fourCharCode == whatClass.fourCharCode) else {return false} + func isCreateCommand(forClass whatClass: String) -> Bool { + guard let arguments = self.arguments else { + return false + } + guard let newObjectClass = arguments["ObjectClass"] as? Int else { + return false + } + guard newObjectClass.fourCharCode == whatClass.fourCharCode else { + return false + } return true } func accountAndFolderForNewChild() -> (Account, Folder?) { let appleEvent = self.appleEvent var account = AccountManager.shared.defaultAccount - var folder:Folder? + var folder: Folder? if let appleEvent = appleEvent { - var descriptorToConsider:NSAppleEventDescriptor? - if let insertionLocationDescriptor = appleEvent.paramDescriptor(forKeyword:keyAEInsertHere) { + var descriptorToConsider: NSAppleEventDescriptor? + if let insertionLocationDescriptor = appleEvent.paramDescriptor(forKeyword: keyAEInsertHere) { print("insertionLocation : \(insertionLocationDescriptor)") // insertion location can be a typeObjectSpecifier, e.g. 'in account "Acct"' // or a typeInsertionLocation, e.g. 'at end of folder " - if (insertionLocationDescriptor.descriptorType == "insl".fourCharCode) { + if insertionLocationDescriptor.descriptorType == "insl".fourCharCode { descriptorToConsider = insertionLocationDescriptor.forKeyword("kobj".fourCharCode) - } else if ( insertionLocationDescriptor.descriptorType == "obj ".fourCharCode) { + } else if insertionLocationDescriptor.descriptorType == "obj ".fourCharCode { descriptorToConsider = insertionLocationDescriptor } - } else if let subjectDescriptor = appleEvent.attributeDescriptor(forKeyword:"subj".fourCharCode) { + } else if let subjectDescriptor = appleEvent.attributeDescriptor(forKeyword: "subj".fourCharCode) { descriptorToConsider = subjectDescriptor } - if let descriptorToConsider = descriptorToConsider { - guard let newContainerSpecifier = NSScriptObjectSpecifier(descriptor:descriptorToConsider) else {return (account, folder)} + if let descriptorToConsider { + guard let newContainerSpecifier = NSScriptObjectSpecifier(descriptor: descriptorToConsider) else { + return (account, folder) + } let newContainer = newContainerSpecifier.objectsByEvaluatingSpecifier if let scriptableAccount = newContainer as? ScriptableAccount { account = scriptableAccount.account diff --git a/Mac/Scripting/ScriptingObject.swift b/Mac/Scripting/ScriptingObject.swift index a03be12d0..f71fc36e6 100644 --- a/Mac/Scripting/ScriptingObject.swift +++ b/Mac/Scripting/ScriptingObject.swift @@ -9,12 +9,12 @@ import Foundation protocol ScriptingObject { - var objectSpecifier: NSScriptObjectSpecifier? { get } + var objectSpecifier: NSScriptObjectSpecifier? { get } var scriptingKey: String { get } } protocol NamedScriptingObject: ScriptingObject { - var name:String { get } + var name: String { get } } protocol UniqueIDScriptingObject: ScriptingObject { diff --git a/Mac/Scripting/ScriptingObjectContainer.swift b/Mac/Scripting/ScriptingObjectContainer.swift index df4505c38..2e37ca70b 100644 --- a/Mac/Scripting/ScriptingObjectContainer.swift +++ b/Mac/Scripting/ScriptingObjectContainer.swift @@ -10,30 +10,29 @@ import AppKit import Account protocol ScriptingObjectContainer: ScriptingObject { - var scriptingClassDescription:NSScriptClassDescription { get } - func deleteElement(_ element:ScriptingObject) + var scriptingClassDescription: NSScriptClassDescription { get } + func deleteElement(_ element: ScriptingObject) } extension ScriptingObjectContainer { - nonisolated func makeFormNameScriptObjectSpecifier(forObject object:NamedScriptingObject) -> NSScriptObjectSpecifier? { + nonisolated func makeFormNameScriptObjectSpecifier(forObject object: NamedScriptingObject) -> NSScriptObjectSpecifier? { let containerClassDescription = self.scriptingClassDescription let containerScriptObjectSpecifier = self.objectSpecifier let scriptingKey = object.scriptingKey let name = object.name - let specifier = NSNameSpecifier(containerClassDescription:containerClassDescription, - containerSpecifier:containerScriptObjectSpecifier, key:scriptingKey, name:name) + let specifier = NSNameSpecifier(containerClassDescription: containerClassDescription, + containerSpecifier: containerScriptObjectSpecifier, key: scriptingKey, name: name) return specifier } - nonisolated func makeFormUniqueIDScriptObjectSpecifier(forObject object:UniqueIDScriptingObject) -> NSScriptObjectSpecifier? { + nonisolated func makeFormUniqueIDScriptObjectSpecifier(forObject object: UniqueIDScriptingObject) -> NSScriptObjectSpecifier? { let containerClassDescription = self.scriptingClassDescription let containerScriptObjectSpecifier = self.objectSpecifier let scriptingKey = object.scriptingKey let uniqueId = object.scriptingUniqueID - let specifier = NSUniqueIDSpecifier(containerClassDescription:containerClassDescription, - containerSpecifier:containerScriptObjectSpecifier, key:scriptingKey, uniqueID: uniqueId) + let specifier = NSUniqueIDSpecifier(containerClassDescription: containerClassDescription, + containerSpecifier: containerScriptObjectSpecifier, key: scriptingKey, uniqueID: uniqueId) return specifier } } - diff --git a/Mac/ShareExtension/ShareViewController.swift b/Mac/ShareExtension/ShareViewController.swift index 14f7fa293..e2050f2a1 100644 --- a/Mac/ShareExtension/ShareViewController.swift +++ b/Mac/ShareExtension/ShareViewController.swift @@ -39,7 +39,7 @@ final class ShareViewController: NSViewController { extensionContainers = ExtensionContainersFile.read() buildFolderPopupMenu() - var provider: NSItemProvider? = nil + var provider: NSItemProvider? // Try to get any HTML that is maybe passed in for item in self.extensionContext!.inputItems as! [NSExtensionItem] { @@ -50,7 +50,7 @@ final class ShareViewController: NSViewController { } } - if provider != nil { + if provider != nil { provider!.loadItem(forTypeIdentifier: UTType.propertyList.identifier, options: nil, completionHandler: { [weak self] (pList, error) in if error != nil { return @@ -77,7 +77,7 @@ final class ShareViewController: NSViewController { } } - if provider != nil { + if provider != nil { provider!.loadItem(forTypeIdentifier: UTType.url.identifier, options: nil, completionHandler: { [weak self] (urlCoded, error) in if error != nil { return @@ -126,7 +126,7 @@ private extension ShareViewController { } let defaultContainer = ShareDefaultContainer.defaultContainer(containers: extensionContainers) - var defaultMenuItem: NSMenuItem? = nil + var defaultMenuItem: NSMenuItem? for account in extensionContainers.accounts { diff --git a/Modules/Account/Package.swift b/Modules/Account/Package.swift index 259e8bce2..21baad4a5 100644 --- a/Modules/Account/Package.swift +++ b/Modules/Account/Package.swift @@ -8,7 +8,7 @@ let package = Package( .library( name: "Account", type: .dynamic, - targets: ["Account"]), + targets: ["Account"]) ], dependencies: [ .package(path: "../Articles"), @@ -41,16 +41,16 @@ let package = Package( ], swiftSettings: [ .enableUpcomingFeature("NonisolatedNonsendingByDefault"), - .enableUpcomingFeature("InferIsolatedConformances"), + .enableUpcomingFeature("InferIsolatedConformances") ] ), .testTarget( name: "AccountTests", dependencies: ["Account"], resources: [ - .copy("JSON"), + .copy("JSON") ], swiftSettings: [.swiftLanguageMode(.v6)] - ), + ) ] ) diff --git a/Modules/Account/Sources/Account/Account.swift b/Modules/Account/Sources/Account/Account.swift index c810dd3e1..cd54e2652 100644 --- a/Modules/Account/Sources/Account/Account.swift +++ b/Modules/Account/Sources/Account/Account.swift @@ -378,10 +378,10 @@ public enum FetchType { } public static func requestOAuthAccessToken(with response: OAuthAuthorizationResponse, - client: OAuthAuthorizationClient, - accountType: AccountType, - transport: Transport = URLSession.webserviceTransport(), - completion: @escaping @MainActor (Result) -> Void) { + client: OAuthAuthorizationClient, + accountType: AccountType, + transport: Transport = URLSession.webserviceTransport(), + completion: @escaping @MainActor (Result) -> Void) { let grantingType: OAuthAuthorizationGranting.Type switch accountType { diff --git a/Modules/Account/Sources/Account/AccountDelegate.swift b/Modules/Account/Sources/Account/AccountDelegate.swift index e362d81c7..33e58b399 100644 --- a/Modules/Account/Sources/Account/AccountDelegate.swift +++ b/Modules/Account/Sources/Account/AccountDelegate.swift @@ -23,7 +23,7 @@ import Secrets var refreshProgress: DownloadProgress { get } - func receiveRemoteNotification(for account: Account, userInfo: [AnyHashable : Any]) async + func receiveRemoteNotification(for account: Account, userInfo: [AnyHashable: Any]) async func refreshAll(for account: Account) async throws func syncArticleStatus(for account: Account) async throws diff --git a/Modules/Account/Sources/Account/CloudKit/CloudKitArticlesZoneDelegate.swift b/Modules/Account/Sources/Account/CloudKit/CloudKitArticlesZoneDelegate.swift index 5ebb0c254..cf4337390 100644 --- a/Modules/Account/Sources/Account/CloudKit/CloudKitArticlesZoneDelegate.swift +++ b/Modules/Account/Sources/Account/CloudKit/CloudKitArticlesZoneDelegate.swift @@ -77,7 +77,7 @@ private extension CloudKitArticlesZoneDelegate { // Parse items on background thread let feedIDsAndItems = await Task.detached(priority: .userInitiated) { let parsedItems = records.compactMap { makeParsedItem($0) } - return Dictionary(grouping: parsedItems, by: { item in item.feedURL } ).mapValues { Set($0) } + return Dictionary(grouping: parsedItems, by: { item in item.feedURL }).mapValues { Set($0) } }.value nonisolated(unsafe) var updateError: Error? diff --git a/Modules/Account/Sources/Account/Feed.swift b/Modules/Account/Sources/Account/Feed.swift index 8321d3094..e0bb8e512 100644 --- a/Modules/Account/Sources/Account/Feed.swift +++ b/Modules/Account/Sources/Account/Feed.swift @@ -322,7 +322,7 @@ extension Feed: OPMLRepresentable { return Set(map { $0.feedID }) } - func sorted() -> Array { + func sorted() -> [Feed] { return sorted(by: { (feed1, feed2) -> Bool in if feed1.nameForDisplay.localizedStandardCompare(feed2.nameForDisplay) == .orderedSame { return feed1.url < feed2.url diff --git a/Modules/Account/Sources/Account/Feedbin/FeedbinAPICaller.swift b/Modules/Account/Sources/Account/Feedbin/FeedbinAPICaller.swift index fe2d157a6..e479f744f 100644 --- a/Modules/Account/Sources/Account/Feedbin/FeedbinAPICaller.swift +++ b/Modules/Account/Sources/Account/Feedbin/FeedbinAPICaller.swift @@ -254,7 +254,7 @@ enum CreateSubscriptionResult { let payload = try JSONEncoder().encode(FeedbinCreateTagging(feedID: feedID, name: name)) - let (response, _) = try await transport.send(request: request, method: HTTPMethod.post, payload:payload) + let (response, _) = try await transport.send(request: request, method: HTTPMethod.post, payload: payload) if let taggingLocation = response.valueForHTTPHeaderField(HTTPResponseHeader.location), let lowerBound = taggingLocation.range(of: "v2/taggings/")?.upperBound, @@ -463,7 +463,7 @@ enum CreateSubscriptionResult { extension FeedbinAPICaller { - func storeConditionalGet(key: String, headers: [AnyHashable : Any]) { + func storeConditionalGet(key: String, headers: [AnyHashable: Any]) { if var conditionalGet = accountMetadata?.conditionalGetInfo { conditionalGet[key] = HTTPConditionalGetInfo(headers: headers) accountMetadata?.conditionalGetInfo = conditionalGet diff --git a/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift b/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift index bcea1a1af..6376699f0 100644 --- a/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift +++ b/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift @@ -644,11 +644,11 @@ private extension FeedbinAccountDelegate { for articleIDGroup in articleIDGroups { do { try await apiCall(articleIDGroup) - try? await self.syncDatabase.deleteSelectedForProcessing(Set(articleIDGroup.map { String($0) } )) + try? await self.syncDatabase.deleteSelectedForProcessing(Set(articleIDGroup.map { String($0) })) } catch { savedError = error Self.logger.error("Feedbin: Article status sync call failed: \(error.localizedDescription)") - try? await self.syncDatabase.resetSelectedForProcessing(Set(articleIDGroup.map { String($0) } )) + try? await self.syncDatabase.resetSelectedForProcessing(Set(articleIDGroup.map { String($0) })) } } @@ -799,7 +799,7 @@ private extension FeedbinAccountDelegate { func processEntries(account: Account, entries: [FeedbinEntry]?) async throws { let parsedItems = mapEntriesToParsedItems(entries: entries) - let feedIDsAndItems = Dictionary(grouping: parsedItems, by: { item in item.feedURL } ).mapValues { Set($0) } + let feedIDsAndItems = Dictionary(grouping: parsedItems, by: { item in item.feedURL }).mapValues { Set($0) } try await account.updateAsync(feedIDsAndItems: feedIDsAndItems, defaultRead: true) } @@ -827,7 +827,7 @@ private extension FeedbinAccountDelegate { return } - let feedbinUnreadArticleIDs = Set(articleIDs.map { String($0) } ) + let feedbinUnreadArticleIDs = Set(articleIDs.map { String($0) }) let updatableFeedbinUnreadArticleIDs = feedbinUnreadArticleIDs.subtracting(pendingArticleIDs) let currentUnreadArticleIDs = try await account.fetchUnreadArticleIDsAsync() @@ -854,7 +854,7 @@ private extension FeedbinAccountDelegate { return } - let feedbinStarredArticleIDs = Set(articleIDs.map { String($0) } ) + let feedbinStarredArticleIDs = Set(articleIDs.map { String($0) }) let updatableFeedbinStarredArticleIDs = feedbinStarredArticleIDs.subtracting(pendingArticleIDs) let currentStarredArticleIDs = try await account.fetchStarredArticleIDsAsync() diff --git a/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegate.swift b/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegate.swift index 378f2de95..1fd6d7df3 100644 --- a/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegate.swift +++ b/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegate.swift @@ -104,7 +104,7 @@ import Secrets // MARK: Account API - func receiveRemoteNotification(for account: Account, userInfo: [AnyHashable : Any]) async { + func receiveRemoteNotification(for account: Account, userInfo: [AnyHashable: Any]) async { } func refreshAll(for account: Account) async throws { diff --git a/Modules/Account/Sources/Account/Folder.swift b/Modules/Account/Sources/Account/Folder.swift index d9c5a7d6a..1e12db214 100644 --- a/Modules/Account/Sources/Account/Folder.swift +++ b/Modules/Account/Sources/Account/Folder.swift @@ -213,7 +213,7 @@ extension Folder: OPMLRepresentable { @MainActor extension Set where Element == Folder { - func sorted() -> Array { + func sorted() -> [Folder] { return sorted(by: { (folder1, folder2) -> Bool in return folder1.nameForDisplay.localizedStandardCompare(folder2.nameForDisplay) == .orderedAscending }) diff --git a/Modules/Account/Sources/Account/LocalAccount/LocalAccountDelegate.swift b/Modules/Account/Sources/Account/LocalAccount/LocalAccountDelegate.swift index a34476309..d9f5741d6 100644 --- a/Modules/Account/Sources/Account/LocalAccount/LocalAccountDelegate.swift +++ b/Modules/Account/Sources/Account/LocalAccount/LocalAccountDelegate.swift @@ -36,7 +36,7 @@ import Secrets refresher.downloadProgress }() - func receiveRemoteNotification(for account: Account, userInfo: [AnyHashable : Any]) async { + func receiveRemoteNotification(for account: Account, userInfo: [AnyHashable: Any]) async { } @MainActor func refreshAll(for account: Account) async throws { diff --git a/Modules/Account/Sources/Account/LocalAccount/LocalAccountRefresher.swift b/Modules/Account/Sources/Account/LocalAccount/LocalAccountRefresher.swift index c75b526dd..06287c008 100644 --- a/Modules/Account/Sources/Account/LocalAccount/LocalAccountRefresher.swift +++ b/Modules/Account/Sources/Account/LocalAccount/LocalAccountRefresher.swift @@ -19,7 +19,6 @@ import os } @MainActor final class LocalAccountRefresher { - var delegate: LocalAccountRefresherDelegate? var downloadProgress: DownloadProgress { downloadSession.downloadProgress @@ -292,4 +291,3 @@ private extension Data { return self.isImage } } - diff --git a/Modules/Account/Sources/Account/NewsBlur/Internals/NewsBlurAccountDelegate+Internal.swift b/Modules/Account/Sources/Account/NewsBlur/Internals/NewsBlurAccountDelegate+Internal.swift index 0b09a2474..58c55b0dc 100644 --- a/Modules/Account/Sources/Account/NewsBlur/Internals/NewsBlurAccountDelegate+Internal.swift +++ b/Modules/Account/Sources/Account/NewsBlur/Internals/NewsBlurAccountDelegate+Internal.swift @@ -293,7 +293,7 @@ import os.log return } - let newsBlurUnreadStoryHashes = Set(hashes.map { $0.hash } ) + let newsBlurUnreadStoryHashes = Set(hashes.map { $0.hash }) let updatableNewsBlurUnreadStoryHashes = newsBlurUnreadStoryHashes.subtracting(pendingStoryHashes) let currentUnreadArticleIDs = try await account.fetchUnreadArticleIDsAsync() @@ -320,7 +320,7 @@ import os.log return } - let newsBlurStarredStoryHashes = Set(hashes.map { $0.hash } ) + let newsBlurStarredStoryHashes = Set(hashes.map { $0.hash }) let updatableNewsBlurUnreadStoryHashes = newsBlurStarredStoryHashes.subtracting(pendingStoryHashes) let currentStarredArticleIDs = try await account.fetchStarredArticleIDsAsync() diff --git a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIAccountDelegate.swift b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIAccountDelegate.swift index 3ece4589a..a4e1156c5 100644 --- a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIAccountDelegate.swift +++ b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIAccountDelegate.swift @@ -774,7 +774,7 @@ private extension ReaderAPIAccountDelegate { func processEntries(account: Account, entries: [ReaderAPIEntry]?) async { let parsedItems = mapEntriesToParsedItems(account: account, entries: entries) - let feedIDsAndItems = Dictionary(grouping: parsedItems, by: { item in item.feedURL } ).mapValues { Set($0) } + let feedIDsAndItems = Dictionary(grouping: parsedItems, by: { item in item.feedURL }).mapValues { Set($0) } try? await account.updateAsync(feedIDsAndItems: feedIDsAndItems, defaultRead: true) } diff --git a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPICaller.swift b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPICaller.swift index a5c6e1736..d1cde2bd5 100644 --- a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPICaller.swift +++ b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPICaller.swift @@ -201,9 +201,9 @@ enum CreateReaderAPISubscriptionResult { let oldTagName = "user/-/label/\(encodedOldName)" let newTagName = "user/-/label/\(encodedNewName)" - let postData = "T=\(token)&s=\(oldTagName)&dest=\(newTagName)".data(using: String.Encoding.utf8) + let postData = Data("T=\(token)&s=\(oldTagName)&dest=\(newTagName)".utf8) - _ = try await transport.send(request: request, method: HTTPMethod.post, payload: postData!) + _ = try await transport.send(request: request, method: HTTPMethod.post, payload: postData) } @MainActor public func deleteTag(folderExternalID: String) async throws { @@ -219,9 +219,9 @@ enum CreateReaderAPISubscriptionResult { request.setValue(MimeType.formURLEncoded, forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" - let postData = "T=\(token)&s=\(folderExternalID)".data(using: String.Encoding.utf8) + let postData = Data("T=\(token)&s=\(folderExternalID)".utf8) - _ = try await self.transport.send(request: request, method: HTTPMethod.post, payload: postData!) + _ = try await self.transport.send(request: request, method: HTTPMethod.post, payload: postData) } @MainActor public func retrieveSubscriptions() async throws -> [ReaderAPISubscription]? { @@ -265,9 +265,9 @@ enum CreateReaderAPISubscriptionResult { throw AccountError.invalidParameter } - let postData = "T=\(token)&quickadd=\(encodedFeedURL)".data(using: String.Encoding.utf8) + let postData = Data("T=\(token)&quickadd=\(encodedFeedURL)".utf8) - let (_, subResult) = try await self.transport.send(request: request, method: HTTPMethod.post, data: postData!, resultType: ReaderAPIQuickAddResult.self) + let (_, subResult) = try await self.transport.send(request: request, method: HTTPMethod.post, data: postData, resultType: ReaderAPIQuickAddResult.self) guard let subResult else { return .notFound @@ -306,9 +306,9 @@ enum CreateReaderAPISubscriptionResult { request.setValue(MimeType.formURLEncoded, forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" - let postData = "T=\(token)&s=\(subscriptionID)&ac=unsubscribe".data(using: String.Encoding.utf8) + let postData = Data("T=\(token)&s=\(subscriptionID)&ac=unsubscribe".utf8) - _ = try await self.transport.send(request: request, method: HTTPMethod.post, payload: postData!) + _ = try await self.transport.send(request: request, method: HTTPMethod.post, payload: postData) } public func createTagging(subscriptionID: String, tagName: String) async throws { @@ -354,7 +354,7 @@ enum CreateReaderAPISubscriptionResult { } let postData = postString.data(using: String.Encoding.utf8) - _ = try await transport.send(request: request, method: HTTPMethod.post, payload: postData!) + _ = try await transport.send(request: request, method: HTTPMethod.post, payload: postData) } @MainActor public func retrieveEntries(articleIDs: [String]) async throws -> [ReaderAPIEntry]? { @@ -384,9 +384,9 @@ enum CreateReaderAPISubscriptionResult { } }).joined(separator: "&") - let postData = "T=\(token)&output=json&\(idsToFetch)".data(using: String.Encoding.utf8) + let postData = Data("T=\(token)&output=json&\(idsToFetch)".utf8) - let (_, entryWrapper) = try await transport.send(request: request, method: HTTPMethod.post, data: postData!, resultType: ReaderAPIEntryWrapper.self) + let (_, entryWrapper) = try await transport.send(request: request, method: HTTPMethod.post, data: postData, resultType: ReaderAPIEntryWrapper.self) guard let entryWrapper else { throw AccountError.invalidResponse @@ -557,8 +557,8 @@ private extension ReaderAPICaller { let actionIndicator = add ? "a" : "r" - let postData = "T=\(token)&\(idsToFetch)&\(actionIndicator)=\(state.rawValue)".data(using: String.Encoding.utf8) + let postData = Data("T=\(token)&\(idsToFetch)&\(actionIndicator)=\(state.rawValue)".utf8) - _ = try await transport.send(request: request, method: HTTPMethod.post, payload: postData!) + _ = try await transport.send(request: request, method: HTTPMethod.post, payload: postData) } } diff --git a/Modules/Account/Sources/Account/URLRequest+Account.swift b/Modules/Account/Sources/Account/URLRequest+Account.swift index 9e5ea78de..f222c0e46 100755 --- a/Modules/Account/Sources/Account/URLRequest+Account.swift +++ b/Modules/Account/Sources/Account/URLRequest+Account.swift @@ -14,18 +14,17 @@ import Secrets public extension URLRequest { init(url: URL, credentials: Credentials?, conditionalGet: HTTPConditionalGetInfo? = nil) { - self.init(url: url) - guard let credentials = credentials else { + guard let credentials else { return } switch credentials.type { case .basic: - let data = "\(credentials.username):\(credentials.secret)".data(using: .utf8) - let base64 = data?.base64EncodedString() - let auth = "Basic \(base64 ?? "")" + let data = Data("\(credentials.username):\(credentials.secret)".utf8) + let base64 = data.base64EncodedString() + let auth = "Basic \(base64)" setValue(auth, forHTTPHeaderField: HTTPRequestHeader.authorization) case .newsBlurBasic: setValue("application/x-www-form-urlencoded", forHTTPHeaderField: HTTPRequestHeader.contentType) @@ -33,15 +32,15 @@ public extension URLRequest { var postData = URLComponents() postData.queryItems = [ URLQueryItem(name: "username", value: credentials.username), - URLQueryItem(name: "password", value: credentials.secret), + URLQueryItem(name: "password", value: credentials.secret) ] httpBody = postData.enhancedPercentEncodedQuery?.data(using: .utf8) case .newsBlurSessionID: setValue("\(NewsBlurAPICaller.sessionIDCookieKey)=\(credentials.secret)", forHTTPHeaderField: "Cookie") httpShouldHandleCookies = true case .readerBasic: - setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") - httpMethod = "POST" + setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") + httpMethod = "POST" var postData = URLComponents() postData.queryItems = [ URLQueryItem(name: "Email", value: credentials.username), @@ -49,22 +48,20 @@ public extension URLRequest { ] httpBody = postData.enhancedPercentEncodedQuery?.data(using: .utf8) case .readerAPIKey: - let auth = "GoogleLogin auth=\(credentials.secret)" - setValue(auth, forHTTPHeaderField: HTTPRequestHeader.authorization) + let auth = "GoogleLogin auth=\(credentials.secret)" + setValue(auth, forHTTPHeaderField: HTTPRequestHeader.authorization) case .oauthAccessToken: - let auth = "OAuth \(credentials.secret)" - setValue(auth, forHTTPHeaderField: "Authorization") + let auth = "OAuth \(credentials.secret)" + setValue(auth, forHTTPHeaderField: "Authorization") case .oauthAccessTokenSecret: - assertionFailure("Token secrets are used by OAuth1. Did you mean to use `OAuthSwift` instead of a URLRequest?") - break - case .oauthRefreshToken: - // While both access and refresh tokens are credentials, it seems the `Credentials` cases - // enumerates how the identity of the user can be proved rather than - // credentials-in-general, such as in this refresh token case, - // the authority to prove an identity. - assertionFailure("Refresh tokens are used to replace expired access tokens. Did you mean to use `accessToken` instead?") - break - } + assertionFailure("Token secrets are used by OAuth1. Did you mean to use `OAuthSwift` instead of a URLRequest?") + case .oauthRefreshToken: + // While both access and refresh tokens are credentials, it seems the `Credentials` cases + // enumerates how the identity of the user can be proved rather than + // credentials-in-general, such as in this refresh token case, + // the authority to prove an identity. + assertionFailure("Refresh tokens are used to replace expired access tokens. Did you mean to use `accessToken` instead?") + } guard let conditionalGet = conditionalGet else { return @@ -78,7 +75,5 @@ public extension URLRequest { if let etag = conditionalGet.etag { setValue(etag, forHTTPHeaderField: HTTPRequestHeader.ifNoneMatch) } - } - } diff --git a/Modules/Articles/Package.swift b/Modules/Articles/Package.swift index 1f271b649..e05bf078b 100644 --- a/Modules/Articles/Package.swift +++ b/Modules/Articles/Package.swift @@ -8,10 +8,10 @@ let package = Package( .library( name: "Articles", type: .dynamic, - targets: ["Articles"]), + targets: ["Articles"]) ], dependencies: [ - .package(path: "../RSCore"), + .package(path: "../RSCore") ], targets: [ .target( @@ -21,7 +21,7 @@ let package = Package( ], swiftSettings: [ .enableUpcomingFeature("NonisolatedNonsendingByDefault"), - .enableUpcomingFeature("InferIsolatedConformances"), - ]), + .enableUpcomingFeature("InferIsolatedConformances") + ]) ] ) diff --git a/Modules/Articles/Sources/Articles/Article.swift b/Modules/Articles/Sources/Articles/Article.swift index 7dd9ae3ae..44c417579 100644 --- a/Modules/Articles/Sources/Articles/Article.swift +++ b/Modules/Articles/Sources/Articles/Article.swift @@ -47,8 +47,7 @@ public final class Article: Hashable, Sendable { if let articleID = articleID { self.articleID = articleID - } - else { + } else { self.articleID = Article.calculatedArticleID(feedID: feedID, uniqueID: uniqueID) } } @@ -111,16 +110,24 @@ public extension Article { result.append(text) } - if let _ = scanner.scanString("<") { + if scanner.scanString("<") != nil { // All the allowed tags currently don't allow attributes if let tag = scanner.scanUpToString(">") { if Self.allowedTags.contains(tag.replacingOccurrences(of: "/", with: "")) { - forHTML ? result.append("<\(tag)>") : result.append("") + if forHTML { + result.append("<\(tag)>") + } else { + result.append("") + } } else { - forHTML ? result.append("<\(tag)>") : result.append("<\(tag)>") + if forHTML { + result.append("<\(tag)>") + } else { + result.append("<\(tag)>") + } } - let _ = scanner.scanString(">") + _ = scanner.scanString(">") } } } diff --git a/Modules/Articles/Sources/Articles/ArticleStatus.swift b/Modules/Articles/Sources/Articles/ArticleStatus.swift index 2b420c417..e3f6ae1c8 100644 --- a/Modules/Articles/Sources/Articles/ArticleStatus.swift +++ b/Modules/Articles/Sources/Articles/ArticleStatus.swift @@ -93,7 +93,7 @@ public extension Set where Element == ArticleStatus { public extension Array where Element == ArticleStatus { - func articleIDs() -> [String] { + func articleIDs() -> [String] { return map { $0.articleID } } } diff --git a/Modules/Articles/Sources/Articles/Author.swift b/Modules/Articles/Sources/Articles/Author.swift index 7736f3f56..630ffda63 100644 --- a/Modules/Articles/Sources/Articles/Author.swift +++ b/Modules/Articles/Sources/Articles/Author.swift @@ -26,8 +26,7 @@ public struct Author: Codable, Hashable, Sendable { if let authorID = authorID { self.authorID = authorID - } - else { + } else { var s = name ?? "" s += url ?? "" s += avatarURL ?? "" @@ -46,8 +45,7 @@ public struct Author: Codable, Hashable, Sendable { do { let authors = try decoder.decode([Author].self, from: data) return Set(authors) - } - catch { + } catch { assertionFailure("JSON representation of Author array could not be decoded: \(jsonString) error: \(error)") } return nil @@ -75,8 +73,7 @@ extension Set where Element == Author { do { let jsonData = try encoder.encode(Array(self)) return String(data: jsonData, encoding: .utf8) - } - catch { + } catch { assertionFailure("JSON representation of Author array could not be encoded: \(self) error: \(error)") } return nil diff --git a/Modules/ArticlesDatabase/Package.swift b/Modules/ArticlesDatabase/Package.swift index c7f451c39..56837b4b3 100644 --- a/Modules/ArticlesDatabase/Package.swift +++ b/Modules/ArticlesDatabase/Package.swift @@ -8,13 +8,13 @@ let package = Package( .library( name: "ArticlesDatabase", type: .dynamic, - targets: ["ArticlesDatabase"]), + targets: ["ArticlesDatabase"]) ], dependencies: [ .package(path: "../Articles"), .package(path: "../RSCore"), .package(path: "../RSParser"), - .package(path: "../RSDatabase"), + .package(path: "../RSDatabase") ], targets: [ .target( @@ -23,12 +23,12 @@ let package = Package( "RSCore", "RSDatabase", "RSParser", - "Articles", + "Articles" ], swiftSettings: [ .enableUpcomingFeature("NonisolatedNonsendingByDefault"), - .enableUpcomingFeature("InferIsolatedConformances"), + .enableUpcomingFeature("InferIsolatedConformances") ] - ), + ) ] ) diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesDatabase.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesDatabase.swift index 388058ca4..5f3bcc493 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesDatabase.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesDatabase.swift @@ -36,7 +36,7 @@ public struct ArticleChanges: Sendable { } } -@MainActor public final class ArticlesDatabase: Sendable { +@MainActor public final class ArticlesDatabase { public enum RetentionStyle: Sendable { case feedBased // Local and iCloud: article retention is defined by contents of feed case syncSystem // Feedbin, Feedly, etc.: article retention is defined by external system diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesTable.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesTable.swift index aebfcca89..0e4fe4f98 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesTable.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesTable.swift @@ -48,7 +48,7 @@ final class ArticlesTable: DatabaseTable, Sendable { // MARK: - Fetching Articles for Feed func fetchArticles(_ feedID: String) throws -> Set
{ - return try fetchArticles{ self.fetchArticlesForFeedID(feedID, $0) } + return try fetchArticles { self.fetchArticlesForFeedID(feedID, $0) } } func fetchArticlesAsync(_ feedID: String, _ completion: @escaping ArticleSetResultBlock) { @@ -56,7 +56,7 @@ final class ArticlesTable: DatabaseTable, Sendable { } func fetchArticles(_ feedIDs: Set) throws -> Set
{ - return try fetchArticles{ self.fetchArticles(feedIDs, $0) } + return try fetchArticles { self.fetchArticles(feedIDs, $0) } } func fetchArticlesAsync(_ feedIDs: Set, _ completion: @escaping ArticleSetResultBlock) { @@ -66,7 +66,7 @@ final class ArticlesTable: DatabaseTable, Sendable { // MARK: - Fetching Articles by articleID func fetchArticles(articleIDs: Set) throws -> Set
{ - return try fetchArticles{ self.fetchArticles(articleIDs: articleIDs, $0) } + return try fetchArticles { self.fetchArticles(articleIDs: articleIDs, $0) } } func fetchArticlesAsync(articleIDs: Set, _ completion: @escaping ArticleSetResultBlock) { @@ -76,7 +76,7 @@ final class ArticlesTable: DatabaseTable, Sendable { // MARK: - Fetching Unread Articles func fetchUnreadArticles(_ feedIDs: Set, _ limit: Int?) throws -> Set
{ - return try fetchArticles{ self.fetchUnreadArticles(feedIDs, limit, $0) } + return try fetchArticles { self.fetchUnreadArticles(feedIDs, limit, $0) } } func fetchUnreadArticlesAsync(_ feedIDs: Set, _ limit: Int?, _ completion: @escaping ArticleSetResultBlock) { @@ -86,7 +86,7 @@ final class ArticlesTable: DatabaseTable, Sendable { // MARK: - Fetching Today Articles func fetchArticlesSince(_ feedIDs: Set, _ cutoffDate: Date, _ limit: Int?) throws -> Set
{ - return try fetchArticles{ self.fetchArticlesSince(feedIDs, cutoffDate, limit, $0) } + return try fetchArticles { self.fetchArticlesSince(feedIDs, cutoffDate, limit, $0) } } func fetchArticlesSinceAsync(_ feedIDs: Set, _ cutoffDate: Date, _ limit: Int?, _ completion: @escaping ArticleSetResultBlock) { @@ -96,7 +96,7 @@ final class ArticlesTable: DatabaseTable, Sendable { // MARK: - Fetching Starred Articles func fetchStarredArticles(_ feedIDs: Set, _ limit: Int?) throws -> Set
{ - return try fetchArticles{ self.fetchStarredArticles(feedIDs, limit, $0) } + return try fetchArticles { self.fetchStarredArticles(feedIDs, limit, $0) } } func fetchStarredArticlesAsync(_ feedIDs: Set, _ limit: Int?, _ completion: @escaping ArticleSetResultBlock) { @@ -104,7 +104,7 @@ final class ArticlesTable: DatabaseTable, Sendable { } func fetchStarredArticlesCount(_ feedIDs: Set) throws -> Int { - return try fetchArticlesCount{ self.fetchStarredArticlesCount(feedIDs, $0) } + return try fetchArticlesCount { self.fetchStarredArticlesCount(feedIDs, $0) } } // MARK: - Fetching Search Articles @@ -130,13 +130,13 @@ final class ArticlesTable: DatabaseTable, Sendable { func fetchArticlesMatching(_ searchString: String, _ feedIDs: Set) throws -> Set
{ var articles = try fetchArticlesMatching(searchString) - articles = articles.filter{ feedIDs.contains($0.feedID) } + articles = articles.filter { feedIDs.contains($0.feedID) } return articles } func fetchArticlesMatchingWithArticleIDs(_ searchString: String, _ articleIDs: Set) throws -> Set
{ var articles = try fetchArticlesMatching(searchString) - articles = articles.filter{ articleIDs.contains($0.articleID) } + articles = articles.filter { articleIDs.contains($0.articleID) } return articles } @@ -216,20 +216,20 @@ final class ArticlesTable: DatabaseTable, Sendable { func makeDatabaseCalls(_ database: FMDatabase) { let articleIDs = parsedItems.articleIDs() - let (statusesDictionary, _) = self.statusesTable.ensureStatusesForArticleIDs(articleIDs, false, database) //1 + let (statusesDictionary, _) = self.statusesTable.ensureStatusesForArticleIDs(articleIDs, false, database) // 1 assert(statusesDictionary.count == articleIDs.count) - let incomingArticles = Article.articlesWithParsedItems(parsedItems, feedID, self.accountID, statusesDictionary) //2 + let incomingArticles = Article.articlesWithParsedItems(parsedItems, feedID, self.accountID, statusesDictionary) // 2 if incomingArticles.isEmpty { self.callUpdateArticlesCompletionBlock(nil, nil, nil, completion) return } - let fetchedArticles = self.fetchArticlesForFeedID(feedID, database) //4 + let fetchedArticles = self.fetchArticlesForFeedID(feedID, database) // 4 let fetchedArticlesDictionary = fetchedArticles.dictionary() - let newArticles = self.findAndSaveNewArticles(incomingArticles, fetchedArticlesDictionary, database) //5 - let updatedArticles = self.findAndSaveUpdatedArticles(incomingArticles, fetchedArticlesDictionary, database) //6 + let newArticles = self.findAndSaveNewArticles(incomingArticles, fetchedArticlesDictionary, database) // 5 + let updatedArticles = self.findAndSaveUpdatedArticles(incomingArticles, fetchedArticlesDictionary, database) // 6 // Articles to delete are 1) not starred and 2) older than 30 days and 3) no longer in feed. let articlesToDelete: Set
@@ -242,7 +242,7 @@ final class ArticlesTable: DatabaseTable, Sendable { articlesToDelete = Set
() } - self.callUpdateArticlesCompletionBlock(newArticles, updatedArticles, articlesToDelete, completion) //7 + self.callUpdateArticlesCompletionBlock(newArticles, updatedArticles, articlesToDelete, completion) // 7 self.addArticlesToCache(newArticles) self.addArticlesToCache(updatedArticles) @@ -298,29 +298,29 @@ final class ArticlesTable: DatabaseTable, Sendable { articleIDs.formUnion(parsedItems.articleIDs()) } - let (statusesDictionary, _) = self.statusesTable.ensureStatusesForArticleIDs(articleIDs, read, database) //1 + let (statusesDictionary, _) = self.statusesTable.ensureStatusesForArticleIDs(articleIDs, read, database) // 1 assert(statusesDictionary.count == articleIDs.count) - let allIncomingArticles = Article.articlesWithFeedIDsAndItems(feedIDsAndItems, self.accountID, statusesDictionary) //2 + let allIncomingArticles = Article.articlesWithFeedIDsAndItems(feedIDsAndItems, self.accountID, statusesDictionary) // 2 if allIncomingArticles.isEmpty { self.callUpdateArticlesCompletionBlock(nil, nil, nil, completion) return } - let incomingArticles = self.filterIncomingArticles(allIncomingArticles) //3 + let incomingArticles = self.filterIncomingArticles(allIncomingArticles) // 3 if incomingArticles.isEmpty { self.callUpdateArticlesCompletionBlock(nil, nil, nil, completion) return } let incomingArticleIDs = incomingArticles.articleIDs() - let fetchedArticles = self.fetchArticles(articleIDs: incomingArticleIDs, database) //4 + let fetchedArticles = self.fetchArticles(articleIDs: incomingArticleIDs, database) // 4 let fetchedArticlesDictionary = fetchedArticles.dictionary() - let newArticles = self.findAndSaveNewArticles(incomingArticles, fetchedArticlesDictionary, database) //5 - let updatedArticles = self.findAndSaveUpdatedArticles(incomingArticles, fetchedArticlesDictionary, database) //6 + let newArticles = self.findAndSaveNewArticles(incomingArticles, fetchedArticlesDictionary, database) // + let updatedArticles = self.findAndSaveUpdatedArticles(incomingArticles, fetchedArticlesDictionary, database) // 6 - self.callUpdateArticlesCompletionBlock(newArticles, updatedArticles, nil, completion) //7 + self.callUpdateArticlesCompletionBlock(newArticles, updatedArticles, nil, completion) // 7 self.addArticlesToCache(newArticles) self.addArticlesToCache(updatedArticles) @@ -543,7 +543,7 @@ final class ArticlesTable: DatabaseTable, Sendable { completion(nil) return } - + queue.runInTransaction { databaseResult in switch databaseResult { case .success(let database): @@ -569,7 +569,7 @@ final class ArticlesTable: DatabaseTable, Sendable { guard let resultSet = database.executeQuery(sql, withArgumentsIn: nil) else { return } - let articleIDs = resultSet.mapToSet{ $0.string(forColumn: DatabaseKey.articleID) } + let articleIDs = resultSet.mapToSet { $0.string(forColumn: DatabaseKey.articleID) } if articleIDs.isEmpty { return } @@ -677,7 +677,7 @@ final class ArticlesTable: DatabaseTable, Sendable { guard let resultSet = database.executeQuery(sql, withArgumentsIn: parameters) else { return } - let articleIDs = resultSet.mapToSet{ $0.string(forColumn: DatabaseKey.articleID) } + let articleIDs = resultSet.mapToSet { $0.string(forColumn: DatabaseKey.articleID) } if articleIDs.isEmpty { return } @@ -734,8 +734,8 @@ nonisolated private extension ArticlesTable { private func fetchArticlesCount(_ fetchMethod: @escaping ArticlesCountFetchMethod) throws -> Int { nonisolated(unsafe) var articlesCount = 0 - nonisolated(unsafe) var error: DatabaseError? = nil - + nonisolated(unsafe) var error: DatabaseError? + queue.runInDatabaseSync { databaseResult in switch databaseResult { case .success(let database): @@ -859,8 +859,8 @@ nonisolated private extension ArticlesTable { func sqliteSearchString(with searchString: String) -> String { var s = "" - searchString.enumerateSubstrings(in: searchString.startIndex.., _ database: FMDatabase) -> Set
{ let articles = fetchArticlesMatching(searchString, database) // TODO: include the feedIDs in the SQL rather than filtering here. - return articles.filter{ feedIDs.contains($0.feedID) } + return articles.filter { feedIDs.contains($0.feedID) } } func fetchArticlesMatchingWithArticleIDs(_ searchString: String, _ articleIDs: Set, _ database: FMDatabase) -> Set
{ let articles = fetchArticlesMatching(searchString, database) // TODO: include the articleIDs in the SQL rather than filtering here. - return articles.filter{ articleIDs.contains($0.articleID) } + return articles.filter { articleIDs.contains($0.articleID) } } // MARK: - Saving Parsed Items @@ -987,7 +987,7 @@ nonisolated private extension ArticlesTable { return newArticles.isEmpty ? nil : newArticles } - func findAndSaveNewArticles(_ incomingArticles: Set
, _ fetchedArticlesDictionary: [String: Article], _ database: FMDatabase) -> Set
? { //5 + func findAndSaveNewArticles(_ incomingArticles: Set
, _ fetchedArticlesDictionary: [String: Article], _ database: FMDatabase) -> Set
? { // 5 guard let newArticles = findNewArticles(incomingArticles, fetchedArticlesDictionary) else { return nil } @@ -1011,11 +1011,11 @@ nonisolated private extension ArticlesTable { // MARK: - Updating Existing Articles func articlesWithRelatedObjectChanges(_ comparisonKeyPath: KeyPath?>, _ updatedArticles: Set
, _ fetchedArticles: [String: Article]) -> Set
{ - return updatedArticles.filter{ (updatedArticle) -> Bool in + return updatedArticles.filter { (updatedArticle) -> Bool in if let fetchedArticle = fetchedArticles[updatedArticle.articleID] { return updatedArticle[keyPath: comparisonKeyPath] != fetchedArticle[keyPath: comparisonKeyPath] } - assertionFailure("Expected to find matching fetched article."); + assertionFailure("Expected to find matching fetched article.") return true } } @@ -1032,7 +1032,7 @@ nonisolated private extension ArticlesTable { } func findUpdatedArticles(_ incomingArticles: Set
, _ fetchedArticlesDictionary: [String: Article]) -> Set
? { - let updatedArticles = incomingArticles.filter{ (incomingArticle) -> Bool in //6 + let updatedArticles = incomingArticles.filter { (incomingArticle) -> Bool in // 6 if let existingArticle = fetchedArticlesDictionary[incomingArticle.articleID] { if existingArticle != incomingArticle { return true @@ -1044,7 +1044,7 @@ nonisolated private extension ArticlesTable { return updatedArticles.isEmpty ? nil : updatedArticles } - func findAndSaveUpdatedArticles(_ incomingArticles: Set
, _ fetchedArticlesDictionary: [String: Article], _ database: FMDatabase) -> Set
? { //6 + func findAndSaveUpdatedArticles(_ incomingArticles: Set
, _ fetchedArticlesDictionary: [String: Article], _ database: FMDatabase) -> Set
? { // 6 guard let updatedArticles = findUpdatedArticles(incomingArticles, fetchedArticlesDictionary) else { return nil } @@ -1065,7 +1065,7 @@ nonisolated private extension ArticlesTable { // Untested theory: this gets us better performance and less database fragmentation. guard let fetchedArticle = fetchedArticles[updatedArticle.articleID] else { - assertionFailure("Expected to find matching fetched article."); + assertionFailure("Expected to find matching fetched article.") saveNewArticles(Set([updatedArticle]), database) return } @@ -1106,7 +1106,7 @@ nonisolated private extension ArticlesTable { func filterIncomingArticles(_ articles: Set
) -> Set
{ // Drop Articles that we can ignore. precondition(retentionStyle == .syncSystem) - return Set(articles.filter{ !articleIsIgnorable($0) }) + return Set(articles.filter { !articleIsIgnorable($0) }) } func removeArticles(_ articleIDs: Set, _ database: FMDatabase) { diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Extensions/Article+Database.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Extensions/Article+Database.swift index ff045c7a6..2e21df005 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Extensions/Article+Database.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Extensions/Article+Database.swift @@ -62,7 +62,7 @@ extension Article { self.init(accountID: accountID, articleID: parsedItem.syncServiceID, feedID: feedID, uniqueID: parsedItem.uniqueID, title: parsedItem.title, contentHTML: parsedItem.contentHTML, contentText: parsedItem.contentText, markdown: parsedItem.markdown, url: parsedItem.url, externalURL: parsedItem.externalURL, summary: parsedItem.summary, imageURL: parsedItem.imageURL, datePublished: datePublished, dateModified: dateModified, authors: authors, status: status) } - private func addPossibleStringChangeWithKeyPath(_ comparisonKeyPath: KeyPath, _ otherArticle: Article, _ key: String, _ dictionary: inout DatabaseDictionary) { + private func addPossibleStringChangeWithKeyPath(_ comparisonKeyPath: KeyPath, _ otherArticle: Article, _ key: String, _ dictionary: inout DatabaseDictionary) { if self[keyPath: comparisonKeyPath] != otherArticle[keyPath: comparisonKeyPath] { dictionary[key] = self[keyPath: comparisonKeyPath] ?? "" } @@ -133,7 +133,7 @@ extension Article { static func articlesWithParsedItems(_ parsedItems: Set, _ feedID: String, _ accountID: String, _ statusesDictionary: [String: ArticleStatus]) -> Set
{ let maximumDateAllowed = _maximumDateAllowed() - return Set(parsedItems.map{ Article(parsedItem: $0, maximumDateAllowed: maximumDateAllowed, accountID: accountID, feedID: feedID, status: statusesDictionary[$0.articleID]!) }) + return Set(parsedItems.map { Article(parsedItem: $0, maximumDateAllowed: maximumDateAllowed, accountID: accountID, feedID: feedID, status: statusesDictionary[$0.articleID]!) }) } } @@ -215,7 +215,7 @@ extension Set where Element == Article { } func databaseObjects() -> [DatabaseObject] { - return self.map{ $0 as DatabaseObject } + return self.map { $0 as DatabaseObject } } func databaseDictionaries() -> [DatabaseDictionary]? { diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Extensions/ArticleStatus+Database.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Extensions/ArticleStatus+Database.swift index 60a500c73..84d3476de 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Extensions/ArticleStatus+Database.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Extensions/ArticleStatus+Database.swift @@ -19,11 +19,9 @@ extension ArticleStatus { self.init(articleID: articleID, read: read, starred: starred, dateArrived: dateArrived) } - } extension ArticleStatus: @retroactive DatabaseObject { - public var databaseID: String { return articleID } @@ -32,4 +30,3 @@ extension ArticleStatus: @retroactive DatabaseObject { return [DatabaseKey.articleID: articleID, DatabaseKey.read: read, DatabaseKey.starred: starred, DatabaseKey.dateArrived: dateArrived] } } - diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/SearchTable.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/SearchTable.swift index 0a3b8d4c5..931cddbdd 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/SearchTable.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/SearchTable.swift @@ -116,7 +116,7 @@ final class SearchTable: DatabaseTable, @unchecked Sendable { /// Index new articles. func indexNewArticles(_ articles: Set
, _ database: FMDatabase) { - let articleSearchInfos = Set(articles.map{ ArticleSearchInfo(article: $0) }) + let articleSearchInfos = Set(articles.map { ArticleSearchInfo(article: $0) }) performInitialIndexForArticles(articleSearchInfos, database) } diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/StatusesTable.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/StatusesTable.swift index 3d156a08a..bc15d5c6b 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/StatusesTable.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/StatusesTable.swift @@ -190,7 +190,7 @@ final class StatusesTable: DatabaseTable, Sendable { return statusWithRow(row, articleID: articleID) } - func statusWithRow(_ row: FMResultSet, articleID: String) ->ArticleStatus? { + func statusWithRow(_ row: FMResultSet, articleID: String) -> ArticleStatus? { if let cachedStatus = cache[articleID] { return cachedStatus } diff --git a/Modules/CloudKitSync/Package.swift b/Modules/CloudKitSync/Package.swift index d05f882c8..09281319a 100644 --- a/Modules/CloudKitSync/Package.swift +++ b/Modules/CloudKitSync/Package.swift @@ -8,7 +8,7 @@ let package = Package( .library( name: "CloudKitSync", targets: ["CloudKitSync"] - ), + ) ], dependencies: [ .package(path: "../RSCore") @@ -21,12 +21,12 @@ let package = Package( ], swiftSettings: [ .enableUpcomingFeature("NonisolatedNonsendingByDefault"), - .enableUpcomingFeature("InferIsolatedConformances"), + .enableUpcomingFeature("InferIsolatedConformances") ] ), .testTarget( name: "CloudKitSyncTests", dependencies: ["CloudKitSync"] - ), + ) ] ) diff --git a/Modules/CloudKitSync/Sources/CloudKitSync/CloudKitZone.swift b/Modules/CloudKitSync/Sources/CloudKitSync/CloudKitZone.swift index ddd570625..8e097b258 100644 --- a/Modules/CloudKitSync/Sources/CloudKitSync/CloudKitZone.swift +++ b/Modules/CloudKitSync/Sources/CloudKitSync/CloudKitZone.swift @@ -29,7 +29,7 @@ public enum CloudKitZoneError: LocalizedError, Sendable { // Wrapper to safely transfer non-Sendable values in @Sendable closures // Generic over the Success type of the Result -fileprivate struct CloudKitZoneCaptures: @unchecked Sendable { +private struct CloudKitZoneCaptures: @unchecked Sendable { weak var zone: (any CloudKitZone)? let completion: (Result) -> Void } @@ -59,7 +59,7 @@ public typealias CloudKitRecordKey = (recordType: CKRecord.RecordType, recordID: func subscribeToZoneChanges() /// Process a remove notification - func receiveRemoteNotification(userInfo: [AnyHashable : Any]) async + func receiveRemoteNotification(userInfo: [AnyHashable: Any]) async } @@ -119,14 +119,14 @@ public extension CloudKitZone { return CKRecord.ID(recordName: UUID().uuidString, zoneID: zoneID) } - func retryIfPossible(after: Double, block: @escaping @MainActor () -> ()) { + func retryIfPossible(after: Double, block: @escaping @MainActor () -> Void) { let delayTime = DispatchTime.now() + after DispatchQueue.main.asyncAfter(deadline: delayTime, execute: { block() }) } - func receiveRemoteNotification(userInfo: [AnyHashable : Any]) async { + func receiveRemoteNotification(userInfo: [AnyHashable: Any]) async { let note = CKRecordZoneNotification(fromRemoteNotificationDictionary: userInfo) guard note?.recordZoneID?.zoneName == zoneID.zoneName else { return @@ -148,7 +148,7 @@ public extension CloudKitZone { return } - database.save(CKRecordZone(zoneID: zoneID)) { (recordZone, error) in + database.save(CKRecordZone(zoneID: zoneID)) { (_, error) in Task { @MainActor in if let error { completion(.failure(CloudKitError(error))) @@ -185,7 +185,7 @@ public extension CloudKitZone { op.desiredKeys = desiredKeys } - op.recordMatchedBlock = { recordID, result in + op.recordMatchedBlock = { _, result in if let record = try? result.get() { records.append(record) } @@ -213,7 +213,7 @@ public extension CloudKitZone { completion(.success(records)) } case .zoneNotFound: - self.createZoneRecord() { result in + self.createZoneRecord { result in switch result { case .success: self.query(ckQuery, desiredKeys: desiredKeys, completion: completion) @@ -254,7 +254,7 @@ public extension CloudKitZone { op.desiredKeys = desiredKeys } - op.recordMatchedBlock = { recordID, result in + op.recordMatchedBlock = { _, result in if let record = try? result.get() { records.append(record) } @@ -282,7 +282,7 @@ public extension CloudKitZone { completion(.success(records)) } case .zoneNotFound: - self.createZoneRecord() { result in + self.createZoneRecord { result in switch result { case .success: self.query(cursor: cursor, desiredKeys: desiredKeys, carriedRecords: records, completion: completion) @@ -341,7 +341,7 @@ public extension CloudKitZone { } } case .zoneNotFound: - self.createZoneRecord() { result in + self.createZoneRecord { result in switch result { case .success: self.fetch(externalID: externalID, completion: captures.completion) @@ -403,7 +403,7 @@ public extension CloudKitZone { } case .zoneNotFound: - self.createZoneRecord() { result in + self.createZoneRecord { result in switch result { case .success: self.saveIfNew(records, completion: completion) @@ -475,7 +475,7 @@ public extension CloudKitZone { captures.completion(.success((savedSubscription!))) } case .zoneNotFound: - self.createZoneRecord() { result in + self.createZoneRecord { result in switch result { case .success: self.save(subscription, completion: captures.completion) @@ -506,7 +506,7 @@ public extension CloudKitZone { let op = CKQueryOperation(query: ckQuery) op.qualityOfService = Self.qualityOfService - op.recordMatchedBlock = { recordID, result in + op.recordMatchedBlock = { _, result in if let record = try? result.get() { records.append(record) } @@ -550,7 +550,7 @@ public extension CloudKitZone { let op = CKQueryOperation(cursor: cursor) op.qualityOfService = Self.qualityOfService - op.recordMatchedBlock = { recordID, result in + op.recordMatchedBlock = { _, result in if let record = try? result.get() { records.append(record) } @@ -667,7 +667,7 @@ public extension CloudKitZone { completion(.success(())) } case .zoneNotFound: - self.createZoneRecord() { result in + self.createZoneRecord { result in switch result { case .success: self.modify(recordsToSave: recordsToSave, recordIDsToDelete: recordIDsToDelete, completion: completion) @@ -728,7 +728,7 @@ public extension CloudKitZone { } } - saveChunks() { result in + saveChunks { result in switch result { case .success: deleteChunks() @@ -764,11 +764,11 @@ public extension CloudKitZone { op.fetchAllChanges = true op.qualityOfService = Self.qualityOfService - op.recordZoneChangeTokensUpdatedBlock = { zoneID, token, _ in + op.recordZoneChangeTokensUpdatedBlock = { _, token, _ in savedChangeToken = token } - op.recordWasChangedBlock = { recordID, result in + op.recordWasChangedBlock = { _, result in if let record = try? result.get() { changedRecords.append(record) } @@ -779,7 +779,7 @@ public extension CloudKitZone { deletedRecordKeys.append(recordKey) } - op.recordZoneFetchResultBlock = { zoneID, result in + op.recordZoneFetchResultBlock = { _, result in if case .success(let (serverChangeToken, _, _)) = result { savedChangeToken = serverChangeToken } @@ -815,7 +815,7 @@ public extension CloudKitZone { } } case .zoneNotFound: - self.createZoneRecord() { result in + self.createZoneRecord { result in switch result { case .success: self.fetchChangesInZone(completion: completion) diff --git a/Modules/CloudKitSync/Sources/CloudKitSync/CloudKitZoneResult.swift b/Modules/CloudKitSync/Sources/CloudKitSync/CloudKitZoneResult.swift index 9f9354a55..c763b1c70 100644 --- a/Modules/CloudKitSync/Sources/CloudKitSync/CloudKitZoneResult.swift +++ b/Modules/CloudKitSync/Sources/CloudKitSync/CloudKitZoneResult.swift @@ -63,13 +63,13 @@ public enum CloudKitZoneResult { private extension CloudKitZoneResult { static func anyRequestErrors(_ errors: [AnyHashable: CKError]) -> CloudKitZoneResult? { - if errors.values.contains(where: { $0.code == .changeTokenExpired } ) { + if errors.values.contains(where: { $0.code == .changeTokenExpired }) { return .changeTokenExpired } - if errors.values.contains(where: { $0.code == .zoneNotFound } ) { + if errors.values.contains(where: { $0.code == .zoneNotFound }) { return .zoneNotFound } - if errors.values.contains(where: { $0.code == .userDeletedZone } ) { + if errors.values.contains(where: { $0.code == .userDeletedZone }) { return .userDeletedZone } return nil diff --git a/Modules/FeedFinder/Sources/FeedFinder/FeedSpecifier.swift b/Modules/FeedFinder/Sources/FeedFinder/FeedSpecifier.swift index e6b0c6bc8..af8b20be0 100644 --- a/Modules/FeedFinder/Sources/FeedFinder/FeedSpecifier.swift +++ b/Modules/FeedFinder/Sources/FeedFinder/FeedSpecifier.swift @@ -32,7 +32,7 @@ public struct FeedSpecifier: Hashable, Sendable { self.source = source self.orderFound = orderFound } - + /// Some feed URLs are known in advance. Save time/bandwidth by special-casing those. static func knownFeedSpecifier(url: URL) -> FeedSpecifier? { if url.isRachelByTheBayURL { @@ -87,7 +87,7 @@ private extension FeedSpecifier { score += 50 } - score = score - ((orderFound - 1) * 5) + score -= (orderFound - 1) * 5 if urlString.caseInsensitiveContains("comments") { score -= 10 diff --git a/Modules/FeedFinder/Sources/FeedFinder/HTMLFeedFinder.swift b/Modules/FeedFinder/Sources/FeedFinder/HTMLFeedFinder.swift index 815d53f9f..980a23d7b 100644 --- a/Modules/FeedFinder/Sources/FeedFinder/HTMLFeedFinder.swift +++ b/Modules/FeedFinder/Sources/FeedFinder/HTMLFeedFinder.swift @@ -25,7 +25,7 @@ final class HTMLFeedFinder { for oneFeedLink in metadata.feedLinks { if let oneURLString = oneFeedLink.urlString?.normalizedURL { - orderFound = orderFound + 1 + orderFound += 1 let oneFeedSpecifier = FeedSpecifier(title: oneFeedLink.title, urlString: oneURLString, source: .HTMLHead, orderFound: orderFound) addFeedSpecifier(oneFeedSpecifier) } @@ -34,7 +34,7 @@ final class HTMLFeedFinder { let bodyLinks = RSHTMLLinkParser.htmlLinks(with: parserData) for oneBodyLink in bodyLinks { if linkMightBeFeed(oneBodyLink), let normalizedURL = oneBodyLink.urlString?.normalizedURL { - orderFound = orderFound + 1 + orderFound += 1 let oneFeedSpecifier = FeedSpecifier(title: oneBodyLink.text, urlString: normalizedURL, source: .HTMLLink, orderFound: orderFound) addFeedSpecifier(oneFeedSpecifier) } @@ -50,8 +50,7 @@ private extension HTMLFeedFinder { if let existingFeedSpecifier = feedSpecifiersDictionary[feedSpecifier.urlString] { let mergedFeedSpecifier = existingFeedSpecifier.feedSpecifierByMerging(feedSpecifier) feedSpecifiersDictionary[feedSpecifier.urlString] = mergedFeedSpecifier - } - else { + } else { feedSpecifiersDictionary[feedSpecifier.urlString] = feedSpecifier } } diff --git a/Modules/RSCore/Package.swift b/Modules/RSCore/Package.swift index 9a2d3927f..613504059 100644 --- a/Modules/RSCore/Package.swift +++ b/Modules/RSCore/Package.swift @@ -15,7 +15,7 @@ let package = Package( dependencies: ["RSCoreObjC"], swiftSettings: [ .enableUpcomingFeature("NonisolatedNonsendingByDefault"), - .enableUpcomingFeature("InferIsolatedConformances"), + .enableUpcomingFeature("InferIsolatedConformances") ] ), .target( @@ -33,7 +33,7 @@ let package = Package( ], swiftSettings: [ .enableUpcomingFeature("NonisolatedNonsendingByDefault"), - .enableUpcomingFeature("InferIsolatedConformances"), + .enableUpcomingFeature("InferIsolatedConformances") ] ), .testTarget( @@ -41,6 +41,6 @@ let package = Package( dependencies: ["RSCore"], resources: [.copy("Resources")], swiftSettings: [.swiftLanguageMode(.v5)] - ), + ) ] ) diff --git a/Modules/RSCore/Sources/RSCore/AppKit/Keyboard.swift b/Modules/RSCore/Sources/RSCore/AppKit/Keyboard.swift index 6cdb03b18..d6721aa75 100644 --- a/Modules/RSCore/Sources/RSCore/AppKit/Keyboard.swift +++ b/Modules/RSCore/Sources/RSCore/AppKit/Keyboard.swift @@ -102,7 +102,7 @@ public struct KeyboardKey: Hashable, Sendable { var integerValue = 0 - switch(s) { + switch s { case "[space]": integerValue = " ".keyboardIntegerValue! case "[uparrow]": @@ -121,8 +121,8 @@ public struct KeyboardKey: Hashable, Sendable { integerValue = KeyboardKey.deleteKeyCode case "[deletefunction]": integerValue = NSDeleteFunctionKey - case "[tab]": - integerValue = NSTabCharacter + case "[tab]": + integerValue = NSTabCharacter default: guard let unwrappedIntegerValue = s.keyboardIntegerValue else { return nil diff --git a/Modules/RSCore/Sources/RSCore/AppKit/MultilineTextFieldSizer.swift b/Modules/RSCore/Sources/RSCore/AppKit/MultilineTextFieldSizer.swift index 4f13c5668..518120887 100644 --- a/Modules/RSCore/Sources/RSCore/AppKit/MultilineTextFieldSizer.swift +++ b/Modules/RSCore/Sources/RSCore/AppKit/MultilineTextFieldSizer.swift @@ -30,7 +30,7 @@ public struct TextFieldSizeInfo: Sendable { private let numberOfLines: Int private let font: NSFont - private let textField:NSTextField + private let textField: NSTextField private let singleLineHeightEstimate: Int private let doubleLineHeightEstimate: Int private var cache = [String: WidthHeightCache]() // Each string has a cache. @@ -227,8 +227,7 @@ private extension MultilineTextFieldSizer { if oneWidth < width && (oneWidth > smallNeighbor.width || smallNeighbor.width == 0) { smallNeighbor = (oneWidth, oneHeight) - } - else if oneWidth > width && (oneWidth < largeNeighbor.width || largeNeighbor.width == 0) { + } else if oneWidth > width && (oneWidth < largeNeighbor.width || largeNeighbor.width == 0) { largeNeighbor = (oneWidth, oneHeight) } @@ -242,4 +241,3 @@ private extension MultilineTextFieldSizer { } #endif - diff --git a/Modules/RSCore/Sources/RSCore/AppKit/NSOutlineView+RSCore.swift b/Modules/RSCore/Sources/RSCore/AppKit/NSOutlineView+RSCore.swift index 067427f6e..c41f09349 100644 --- a/Modules/RSCore/Sources/RSCore/AppKit/NSOutlineView+RSCore.swift +++ b/Modules/RSCore/Sources/RSCore/AppKit/NSOutlineView+RSCore.swift @@ -64,13 +64,12 @@ public extension NSOutlineView { while true { row += 1 - if let _ = item(atRow: row) { + if item(atRow: row) != nil { if canSelect(row) { selectRowAndScrollToVisible(row) return } - } - else { + } else { return // if there are no more items, we’re out of rows } } @@ -180,4 +179,3 @@ public extension NSOutlineView { } } #endif - diff --git a/Modules/RSCore/Sources/RSCore/AppKit/NSResponder+RSCore.swift b/Modules/RSCore/Sources/RSCore/AppKit/NSResponder+RSCore.swift index dbf7f4f84..fa1ce7913 100644 --- a/Modules/RSCore/Sources/RSCore/AppKit/NSResponder+RSCore.swift +++ b/Modules/RSCore/Sources/RSCore/AppKit/NSResponder+RSCore.swift @@ -13,14 +13,13 @@ public extension NSResponder { func hasAncestor(_ ancestor: NSResponder) -> Bool { var nomad: NSResponder = self - while(true) { + while true { if nomad === ancestor { return true } - if let _ = nomad.nextResponder { - nomad = nomad.nextResponder! - } - else { + if let next = nomad.nextResponder { + nomad = next + } else { break } } diff --git a/Modules/RSCore/Sources/RSCore/AppKit/NSTableView+RSCore.swift b/Modules/RSCore/Sources/RSCore/AppKit/NSTableView+RSCore.swift index 704ce3919..0fb4e7ac4 100644 --- a/Modules/RSCore/Sources/RSCore/AppKit/NSTableView+RSCore.swift +++ b/Modules/RSCore/Sources/RSCore/AppKit/NSTableView+RSCore.swift @@ -40,12 +40,12 @@ public extension NSTableView { let documentVisibleRect = scrollView.documentVisibleRect let r = rect(ofRow: row) - if NSContainsRect(documentVisibleRect, r) { + if documentVisibleRect.contains(r) { return } - let rMidY = NSMidY(r) - var scrollPoint = NSZeroPoint; + let rMidY = r.midY + var scrollPoint = NSPoint.zero scrollPoint.y = floor(rMidY - (documentVisibleRect.size.height / 2.0)) + CGFloat(extraHeight) scrollPoint.y = max(scrollPoint.y, 0) @@ -54,7 +54,7 @@ public extension NSTableView { let clipView = scrollView.contentView - let rClipView = NSMakeRect(scrollPoint.x, scrollPoint.y, NSWidth(clipView.bounds), NSHeight(clipView.bounds)) + let rClipView = NSRect(x: scrollPoint.x, y: scrollPoint.y, width: clipView.bounds.width, height: clipView.bounds.height) clipView.animator().bounds = rClipView } diff --git a/Modules/RSCore/Sources/RSCore/AppKit/RSAppMovementMonitor.swift b/Modules/RSCore/Sources/RSCore/AppKit/RSAppMovementMonitor.swift index ddeb22f11..a9b4a5cf0 100644 --- a/Modules/RSCore/Sources/RSCore/AppKit/RSAppMovementMonitor.swift +++ b/Modules/RSCore/Sources/RSCore/AppKit/RSAppMovementMonitor.swift @@ -78,7 +78,7 @@ import Cocoa // every time the app becomes active. This catches a good number of edge-case // changes to the app bundle's path, such as when a containing folder or the // volume name changes. - NotificationCenter.default.addObserver(forName: NSApplication.didBecomeActiveNotification, object: nil, queue: nil) { notification in + NotificationCenter.default.addObserver(forName: NSApplication.didBecomeActiveNotification, object: nil, queue: nil) { _ in Task { @MainActor in // Removing observer in invalidate doesn't seem to prevent this getting called? Maybe // because it's on the same invocation of the runloop? diff --git a/Modules/RSCore/Sources/RSCore/AppKit/RSToolbarItem.swift b/Modules/RSCore/Sources/RSCore/AppKit/RSToolbarItem.swift index 1da6e5253..556d76845 100644 --- a/Modules/RSCore/Sources/RSCore/AppKit/RSToolbarItem.swift +++ b/Modules/RSCore/Sources/RSCore/AppKit/RSToolbarItem.swift @@ -12,7 +12,7 @@ import AppKit public class RSToolbarItem: NSToolbarItem { override public func validate() { - guard let view = view, let _ = view.window else { + guard let view = view, view.window != nil else { isEnabled = false return } @@ -34,7 +34,7 @@ private extension RSToolbarItem { return false } - while(true) { + while true { if let validated = validateWithResponder(responder!) { return validated } diff --git a/Modules/RSCore/Sources/RSCore/AppKit/URLPasteboardWriter.swift b/Modules/RSCore/Sources/RSCore/AppKit/URLPasteboardWriter.swift index 150100ab5..dbb4de1e7 100644 --- a/Modules/RSCore/Sources/RSCore/AppKit/URLPasteboardWriter.swift +++ b/Modules/RSCore/Sources/RSCore/AppKit/URLPasteboardWriter.swift @@ -18,11 +18,11 @@ import AppKit self.urlString = urlString } - public class func write(urlString: String, to pasteboard: NSPasteboard) { + public static func write(urlString: String, to pasteboard: NSPasteboard) { write(urlStrings: [urlString], to: pasteboard) } - public class func write(urlStrings: [String], to pasteboard: NSPasteboard) { + public static func write(urlStrings: [String], to pasteboard: NSPasteboard) { assert(!urlStrings.isEmpty) guard !urlStrings.isEmpty else { return @@ -36,7 +36,7 @@ import AppKit // MARK: - NSPasteboardWriting public func writableTypes(for pasteboard: NSPasteboard) -> [NSPasteboard.PasteboardType] { - if let _ = URL(string: urlString) { + if URL(string: urlString) != nil { return [.URL, .string] } return [.string] diff --git a/Modules/RSCore/Sources/RSCore/AppKit/UserApp.swift b/Modules/RSCore/Sources/RSCore/AppKit/UserApp.swift index 7246a42d1..26ee81101 100644 --- a/Modules/RSCore/Sources/RSCore/AppKit/UserApp.swift +++ b/Modules/RSCore/Sources/RSCore/AppKit/UserApp.swift @@ -44,8 +44,7 @@ public final class UserApp { if app == runningApplication { break } - } - else { + } else { if !app.isTerminated { runningApplication = app break @@ -58,8 +57,7 @@ public final class UserApp { icon = runningApplication.icon if let bundleURL = runningApplication.bundleURL { path = bundleURL.path - } - else { + } else { path = NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleID)?.path } if icon == nil, let path = path { @@ -74,8 +72,7 @@ public final class UserApp { icon = NSWorkspace.shared.icon(forFile: path) } existsOnDisk = true - } - else { + } else { existsOnDisk = false icon = nil } @@ -140,4 +137,3 @@ public final class UserApp { } } #endif - diff --git a/Modules/RSCore/Sources/RSCore/BatchUpdate.swift b/Modules/RSCore/Sources/RSCore/BatchUpdate.swift index ebb631786..2e576adf4 100644 --- a/Modules/RSCore/Sources/RSCore/BatchUpdate.swift +++ b/Modules/RSCore/Sources/RSCore/BatchUpdate.swift @@ -49,17 +49,17 @@ public extension Notification.Name { public func end() { precondition(Thread.isMainThread) decrementCount() - } + } } private extension BatchUpdate { func incrementCount() { - count = count + 1 + count += 1 } func decrementCount() { - count = count - 1 + count -= 1 if count < 1 { assert(count > -1, "Expected batch updates count to be 0 or greater.") count = 0 diff --git a/Modules/RSCore/Sources/RSCore/BinaryDiskCache.swift b/Modules/RSCore/Sources/RSCore/BinaryDiskCache.swift index 654d80f6c..723622ac8 100644 --- a/Modules/RSCore/Sources/RSCore/BinaryDiskCache.swift +++ b/Modules/RSCore/Sources/RSCore/BinaryDiskCache.swift @@ -53,8 +53,7 @@ nonisolated public final class BinaryDiskCache: Sendable { do { try _setData(data, forKey: key) } catch {} - } - else { + } else { do { try _deleteData(forKey: key) } catch {} diff --git a/Modules/RSCore/Sources/RSCore/CoalescingQueue.swift b/Modules/RSCore/Sources/RSCore/CoalescingQueue.swift index 1945efd0f..e7840f27c 100644 --- a/Modules/RSCore/Sources/RSCore/CoalescingQueue.swift +++ b/Modules/RSCore/Sources/RSCore/CoalescingQueue.swift @@ -71,7 +71,7 @@ private extension CoalescingQueue { func add(_ call: QueueCall) { restartTimer() - + if !calls.contains(call) { calls.append(call) } diff --git a/Modules/RSCore/Sources/RSCore/Data+RSCore.swift b/Modules/RSCore/Sources/RSCore/Data+RSCore.swift index dea25d07f..bbe3277b8 100644 --- a/Modules/RSCore/Sources/RSCore/Data+RSCore.swift +++ b/Modules/RSCore/Sources/RSCore/Data+RSCore.swift @@ -89,20 +89,20 @@ public extension Data { /// Tags in UTF-8/ASCII format. enum UTF8 { - static let lowercaseHTML = "html".data(using: .utf8)! - static let lowercaseBody = "body".data(using: .utf8)! - static let uppercaseHTML = "HTML".data(using: .utf8)! - static let uppercaseBody = "BODY".data(using: .utf8)! - static let lowercaseHead = "head".data(using: .utf8)! - static let uppercaseHead = "HEAD".data(using: .utf8)! - static let lowercaseDoctype = ".allocate(capacity: outputCapacity) defer { outputBuffer.deallocate() } - let _ = stripHTML( + _ = stripHTML( cString, inputLength, outputBuffer, @@ -217,7 +215,7 @@ public extension String { /// Replaces `p`, `blockquote`, `div`, `br`, and `li` tags with varying quantities /// of newlines, strips all other tags, and guarantees no more than two consecutive newlines. /// - /// - Returns: A copy of self, with HTML tags removed.. + /// - Returns: A copy of self, with HTML tags removed. func convertingToPlainText() -> String { if !self.contains("<") { return self @@ -253,7 +251,7 @@ public extension String { /// /// - Returns: `true` if the string contains `string`; `false` otherwise. func caseInsensitiveContains(_ string: String) -> Bool { - return self.range(of: string, options: .caseInsensitive) != nil + self.range(of: string, options: .caseInsensitive) != nil } /// Returns the string with the special XML characters (other than single-quote) ampersand-escaped. @@ -264,16 +262,16 @@ public extension String { for char in self { switch char { - case "&": - escaped.append("&") - case "<": - escaped.append("<") - case ">": - escaped.append(">") - case "\"": - escaped.append(""") - default: - escaped.append(char) + case "&": + escaped.append("&") + case "<": + escaped.append("<") + case ">": + escaped.append(">") + case "\"": + escaped.append(""") + default: + escaped.append(char) } } @@ -295,4 +293,3 @@ public extension String { self.stripping(prefix: "http://").stripping(prefix: "https://") } } - diff --git a/Modules/RSCore/Sources/RSCore/UIKit/InteractiveLabel.swift b/Modules/RSCore/Sources/RSCore/UIKit/InteractiveLabel.swift index 0be7db9fe..4e06f7b19 100644 --- a/Modules/RSCore/Sources/RSCore/UIKit/InteractiveLabel.swift +++ b/Modules/RSCore/Sources/RSCore/UIKit/InteractiveLabel.swift @@ -61,7 +61,7 @@ public final class InteractiveLabel: UILabel, @preconcurrency UIEditMenuInteract public func editMenuInteraction(_ interaction: UIEditMenuInteraction, menuFor configuration: UIEditMenuConfiguration, suggestedActions: [UIMenuElement]) -> UIMenu? { - let copyAction = UIAction(title: "Copy", image: nil) { [weak self] action in + let copyAction = UIAction(title: "Copy", image: nil) { [weak self] _ in self?.copy(nil) } return UIMenu(title: "", children: [copyAction]) diff --git a/Modules/RSCore/Sources/RSCore/UIKit/UICollectionView+RSCore.swift b/Modules/RSCore/Sources/RSCore/UIKit/UICollectionView+RSCore.swift index d406c5972..e3ab8d830 100644 --- a/Modules/RSCore/Sources/RSCore/UIKit/UICollectionView+RSCore.swift +++ b/Modules/RSCore/Sources/RSCore/UIKit/UICollectionView+RSCore.swift @@ -12,7 +12,7 @@ import Foundation import UIKit extension UICollectionView { - + /// Selects an item and scrolls it to the middle if it is not visible public func selectItemAndScrollIfNotVisible(at indexPath: IndexPath, animations: Animations) { guard let dataSource = dataSource, diff --git a/Modules/RSCore/Sources/RSCore/UIKit/UIFont+RSCore.swift b/Modules/RSCore/Sources/RSCore/UIKit/UIFont+RSCore.swift index 42b566032..910907d48 100644 --- a/Modules/RSCore/Sources/RSCore/UIKit/UIFont+RSCore.swift +++ b/Modules/RSCore/Sources/RSCore/UIKit/UIFont+RSCore.swift @@ -12,9 +12,9 @@ import UIKit extension UIFont { - func withTraits(traits:UIFontDescriptor.SymbolicTraits) -> UIFont { + func withTraits(traits: UIFontDescriptor.SymbolicTraits) -> UIFont { if let descriptor = fontDescriptor.withSymbolicTraits(traits) { - return UIFont(descriptor: descriptor, size: 0) //size 0 means keep the size as it is + return UIFont(descriptor: descriptor, size: 0) // size 0 means keep the size as it is } else { return self } diff --git a/Modules/RSCore/Sources/RSCoreResources/AppKit/WebViewWindowController.swift b/Modules/RSCore/Sources/RSCoreResources/AppKit/WebViewWindowController.swift index 576ce7d18..b743944d4 100644 --- a/Modules/RSCore/Sources/RSCoreResources/AppKit/WebViewWindowController.swift +++ b/Modules/RSCore/Sources/RSCoreResources/AppKit/WebViewWindowController.swift @@ -27,7 +27,7 @@ public final class WebViewWindowController: NSWindowController { public func displayContents(of path: String) { // We assume there might be images, style sheets, etc. contained by the folder that the file appears in, so we get read access to the parent folder. - let _ = self.window + _ = self.window let fileURL = URL(fileURLWithPath: path) let folderURL = fileURL.deletingLastPathComponent() diff --git a/Modules/RSCore/Tests/RSCoreTests/Data+RSCoreTests.swift b/Modules/RSCore/Tests/RSCoreTests/Data+RSCoreTests.swift index fa061a732..92f352705 100644 --- a/Modules/RSCore/Tests/RSCoreTests/Data+RSCoreTests.swift +++ b/Modules/RSCore/Tests/RSCoreTests/Data+RSCoreTests.swift @@ -10,7 +10,7 @@ import XCTest import Foundation @testable import RSCore -//final class Data_RSCoreTests: XCTestCase { +// final class Data_RSCoreTests: XCTestCase { // var bigHTML: String! // // var pngData: Data! @@ -125,10 +125,10 @@ import Foundation // // } // -//} +// } // Tests to compare the result of Data+RSCore with the old Objective-C versions. -//extension Data_RSCoreTests { +// extension Data_RSCoreTests { // // func testCompare_isProbablyHTML() { // let noLT = "html body".data(using: .utf8)! @@ -186,4 +186,4 @@ import Foundation // // } // -//} +// } diff --git a/Modules/RSCore/Tests/RSCoreTests/MacroProcessorTests.swift b/Modules/RSCore/Tests/RSCoreTests/MacroProcessorTests.swift index e6a33e647..34512bada 100644 --- a/Modules/RSCore/Tests/RSCoreTests/MacroProcessorTests.swift +++ b/Modules/RSCore/Tests/RSCoreTests/MacroProcessorTests.swift @@ -44,7 +44,7 @@ final class MacroProcessorTests: XCTestCase { func testEmptyDelimiters() { do { let template = "foo bar" - let _ = try MacroProcessor.renderedText(withTemplate: template, substitutions: substitutions, macroStart: "") + _ = try MacroProcessor.renderedText(withTemplate: template, substitutions: substitutions, macroStart: "") XCTFail("Error should be thrown") } catch { // Success @@ -52,7 +52,7 @@ final class MacroProcessorTests: XCTestCase { do { let template = "foo bar" - let _ = try MacroProcessor.renderedText(withTemplate: template, substitutions: substitutions, macroEnd: "") + _ = try MacroProcessor.renderedText(withTemplate: template, substitutions: substitutions, macroEnd: "") XCTFail("Error should be thrown") } catch { // Success diff --git a/Modules/RSCore/Tests/RSCoreTests/String+RSCoreTests.swift b/Modules/RSCore/Tests/RSCoreTests/String+RSCoreTests.swift index 10b0e283f..12c15fbf3 100644 --- a/Modules/RSCore/Tests/RSCoreTests/String+RSCoreTests.swift +++ b/Modules/RSCore/Tests/RSCoreTests/String+RSCoreTests.swift @@ -8,7 +8,7 @@ import XCTest -final class String_RSCore: XCTestCase { +final class StringRSCoreTests: XCTestCase { func testCollapsingWhitespace() { diff --git a/Modules/RSCore/Tests/RSCoreTests/StripHTMLTests.swift b/Modules/RSCore/Tests/RSCoreTests/StripHTMLTests.swift index 717c15578..8c349b413 100644 --- a/Modules/RSCore/Tests/RSCoreTests/StripHTMLTests.swift +++ b/Modules/RSCore/Tests/RSCoreTests/StripHTMLTests.swift @@ -148,7 +148,7 @@ final class StripHTMLTests: XCTestCase { self.measure { for _ in 0..<1000 { - let _ = html.strippingHTML(maxCharacters: 300) + _ = html.strippingHTML(maxCharacters: 300) } } } @@ -214,7 +214,7 @@ final class StripHTMLTests: XCTestCase { self.measure { for _ in 0..<100 { for html in htmlFiles { - let _ = html.strippingHTML(maxCharacters: 300) + _ = html.strippingHTML(maxCharacters: 300) } } } diff --git a/Modules/RSCore/Tests/RSCoreTests/XCTestManifests.swift b/Modules/RSCore/Tests/RSCoreTests/XCTestManifests.swift index 4f81fdd24..d0653dea8 100644 --- a/Modules/RSCore/Tests/RSCoreTests/XCTestManifests.swift +++ b/Modules/RSCore/Tests/RSCoreTests/XCTestManifests.swift @@ -3,7 +3,7 @@ import XCTest #if !canImport(ObjectiveC) public func allTests() -> [XCTestCaseEntry] { return [ - testCase(RSCoreTests.allTests), + testCase(RSCoreTests.allTests) ] } #endif diff --git a/Modules/RSDatabase/Package.swift b/Modules/RSDatabase/Package.swift index ceb5b9fc8..d4204ddda 100644 --- a/Modules/RSDatabase/Package.swift +++ b/Modules/RSDatabase/Package.swift @@ -12,7 +12,7 @@ let package = Package( .library( name: "RSDatabaseObjC", type: .dynamic, - targets: ["RSDatabaseObjC"]), + targets: ["RSDatabaseObjC"]) ], dependencies: [ ], @@ -22,7 +22,7 @@ let package = Package( dependencies: ["RSDatabaseObjC"], swiftSettings: [ .enableUpcomingFeature("NonisolatedNonsendingByDefault"), - .enableUpcomingFeature("InferIsolatedConformances"), + .enableUpcomingFeature("InferIsolatedConformances") ] ), .target( @@ -31,6 +31,6 @@ let package = Package( ), .testTarget( name: "RSDatabaseTests", - dependencies: ["RSDatabase"]), + dependencies: ["RSDatabase"]) ] ) diff --git a/Modules/RSDatabase/Sources/RSDatabase/DatabaseObject.swift b/Modules/RSDatabase/Sources/RSDatabase/DatabaseObject.swift index aa5f166db..fcf63f452 100644 --- a/Modules/RSDatabase/Sources/RSDatabase/DatabaseObject.swift +++ b/Modules/RSDatabase/Sources/RSDatabase/DatabaseObject.swift @@ -55,7 +55,7 @@ extension Array where Element == DatabaseObject { func databaseDictionaries() -> [DatabaseDictionary]? { - let dictionaries = self.compactMap{ $0.databaseDictionary() } + let dictionaries = self.compactMap { $0.databaseDictionary() } return dictionaries.isEmpty ? nil : dictionaries } } diff --git a/Modules/RSDatabase/Sources/RSDatabase/DatabaseTable.swift b/Modules/RSDatabase/Sources/RSDatabase/DatabaseTable.swift index b4e634580..0bb191d2c 100644 --- a/Modules/RSDatabase/Sources/RSDatabase/DatabaseTable.swift +++ b/Modules/RSDatabase/Sources/RSDatabase/DatabaseTable.swift @@ -29,7 +29,6 @@ public extension DatabaseTable { } func selectRowsWhere(key: String, inValues values: [Any], in database: FMDatabase) -> FMResultSet? { - if values.isEmpty { return nil } @@ -39,7 +38,6 @@ public extension DatabaseTable { // MARK: Deleting func deleteRowsWhere(key: String, equalsAnyValue values: [Any], in database: FMDatabase) { - if values.isEmpty { return } @@ -49,33 +47,28 @@ public extension DatabaseTable { // MARK: Updating func updateRowsWithValue(_ value: Any, valueKey: String, whereKey: String, matches: [Any], database: FMDatabase) { - - let _ = database.rs_updateRows(withValue: value, valueKey: valueKey, whereKey: whereKey, inValues: matches, tableName: self.name) + _ = database.rs_updateRows(withValue: value, valueKey: valueKey, whereKey: whereKey, inValues: matches, tableName: self.name) } func updateRowsWithDictionary(_ dictionary: DatabaseDictionary, whereKey: String, matches: Any, database: FMDatabase) { - - let _ = database.rs_updateRows(with: dictionary, whereKey: whereKey, equalsValue: matches, tableName: self.name) + _ = database.rs_updateRows(with: dictionary, whereKey: whereKey, equalsValue: matches, tableName: self.name) } // MARK: Saving func insertRows(_ dictionaries: [DatabaseDictionary], insertType: RSDatabaseInsertType, in database: FMDatabase) { - dictionaries.forEach { (oneDictionary) in - let _ = database.rs_insertRow(with: oneDictionary, insertType: insertType, tableName: self.name) + _ = database.rs_insertRow(with: oneDictionary, insertType: insertType, tableName: self.name) } } func insertRow(_ rowDictionary: DatabaseDictionary, insertType: RSDatabaseInsertType, in database: FMDatabase) { - insertRows([rowDictionary], insertType: insertType, in: database) } // MARK: Counting func numberWithCountResultSet(_ resultSet: FMResultSet) -> Int { - guard resultSet.next() else { return 0 } @@ -108,7 +101,7 @@ public extension DatabaseTable { func containsColumn(_ columnName: String, in database: FMDatabase) -> Bool { if let resultSet = database.executeQuery("select * from \(name) limit 1;", withArgumentsIn: nil) { if let columnMap = resultSet.columnNameToIndexMap { - if let _ = columnMap[columnName.lowercased()] { + if columnMap[columnName.lowercased()] != nil { return true } } diff --git a/Modules/RSDatabase/Sources/RSDatabase/FMDatabase+Extras.swift b/Modules/RSDatabase/Sources/RSDatabase/FMDatabase+Extras.swift index ea523ff63..37b07f688 100644 --- a/Modules/RSDatabase/Sources/RSDatabase/FMDatabase+Extras.swift +++ b/Modules/RSDatabase/Sources/RSDatabase/FMDatabase+Extras.swift @@ -20,7 +20,7 @@ public extension FMDatabase { return database } - func executeUpdateInTransaction(_ sql : String, withArgumentsIn parameters: [Any]? = nil) { + func executeUpdateInTransaction(_ sql: String, withArgumentsIn parameters: [Any]? = nil) { beginTransaction() guard executeUpdate(sql, withArgumentsIn: parameters) else { rollback() @@ -97,7 +97,7 @@ public extension FMDatabase { guard let resultSet = executeQuery(sql, withArgumentsIn: parameters) else { return nil } - + let count = resultSet.intWithCountResult() return count } diff --git a/Modules/RSDatabase/Sources/RSDatabase/FMResultSet+Extras.swift b/Modules/RSDatabase/Sources/RSDatabase/FMResultSet+Extras.swift index 1dfb24d19..9d53ff5d7 100644 --- a/Modules/RSDatabase/Sources/RSDatabase/FMResultSet+Extras.swift +++ b/Modules/RSDatabase/Sources/RSDatabase/FMResultSet+Extras.swift @@ -17,7 +17,7 @@ public extension FMResultSet { let count = Int(long(forColumnIndex: 0)) close() - + return count } @@ -36,4 +36,3 @@ public extension FMResultSet { return Set(compactMap(completion)) } } - diff --git a/Modules/RSDatabase/Sources/RSDatabase/Related Objects/DatabaseLookupTable.swift b/Modules/RSDatabase/Sources/RSDatabase/Related Objects/DatabaseLookupTable.swift index ea4918ffb..0eed88910 100644 --- a/Modules/RSDatabase/Sources/RSDatabase/Related Objects/DatabaseLookupTable.swift +++ b/Modules/RSDatabase/Sources/RSDatabase/Related Objects/DatabaseLookupTable.swift @@ -70,8 +70,7 @@ public final class DatabaseLookupTable: Sendable { for object in objects { if let relatedObjects = object.relatedObjectsWithName(relationshipName), !relatedObjects.isEmpty { objectsWithRelationships += [object] - } - else { + } else { objectsWithNoRelationships += [object] } } @@ -112,7 +111,7 @@ private extension DatabaseLookupTable { let sql = "delete from \(name) where \(objectIDKey)=? and \(relatedObjectIDKey) in \(placeholders)" let parameters: [Any] = [objectID] + Array(relatedObjectIDs) - let _ = database.executeUpdate(sql, withArgumentsIn: parameters) + _ = database.executeUpdate(sql, withArgumentsIn: parameters) } // MARK: Saving/Updating @@ -185,7 +184,7 @@ private extension DatabaseLookupTable { for relatedObjectID in relatedObjectIDs { let d: [NSObject: Any] = [(objectIDKey as NSString): objectID, (relatedObjectIDKey as NSString): relatedObjectID] - let _ = database.rs_insertRow(with: d, insertType: .orIgnore, tableName: name) + _ = database.rs_insertRow(with: d, insertType: .orIgnore, tableName: name) } } @@ -245,4 +244,3 @@ private extension DatabaseLookupTable { objectIDsWithNoRelatedObjects.withLock { $0.subtract(objectIDs) } } } - diff --git a/Modules/RSDatabase/Sources/RSDatabase/Related Objects/DatabaseRelatedObjectsTable.swift b/Modules/RSDatabase/Sources/RSDatabase/Related Objects/DatabaseRelatedObjectsTable.swift index dfcd40daf..e239588db 100644 --- a/Modules/RSDatabase/Sources/RSDatabase/Related Objects/DatabaseRelatedObjectsTable.swift +++ b/Modules/RSDatabase/Sources/RSDatabase/Related Objects/DatabaseRelatedObjectsTable.swift @@ -39,8 +39,7 @@ public extension DatabaseRelatedObjectsTable { for databaseID in databaseIDs { if let cachedObject = cache[databaseID] { cachedObjects += [cachedObject] - } - else { + } else { databaseIDsToFetch.insert(databaseID) } } @@ -68,7 +67,7 @@ public extension DatabaseRelatedObjectsTable { // Objects in cache must already exist in database. Filter them out. let objectsToSave = objects.filter { (object) -> Bool in - if let _ = cache[object.databaseID] { + if cache[object.databaseID] != nil { return false } return true diff --git a/Modules/RSDatabase/Sources/RSDatabase/Related Objects/RelatedObjectIDsMap.swift b/Modules/RSDatabase/Sources/RSDatabase/Related Objects/RelatedObjectIDsMap.swift index 318f8f339..43e1a64f6 100644 --- a/Modules/RSDatabase/Sources/RSDatabase/Related Objects/RelatedObjectIDsMap.swift +++ b/Modules/RSDatabase/Sources/RSDatabase/Related Objects/RelatedObjectIDsMap.swift @@ -27,8 +27,7 @@ struct RelatedObjectIDsMap: Sendable { let relatedObjectID: String = lookupValue.relatedObjectID if d[objectID] == nil { d[objectID] = Set([relatedObjectID]) - } - else { + } else { d[objectID]!.insert(relatedObjectID) } } diff --git a/Modules/RSDatabase/Sources/RSDatabase/Related Objects/RelatedObjectsMap.swift b/Modules/RSDatabase/Sources/RSDatabase/Related Objects/RelatedObjectsMap.swift index 1c7abbb8c..5add6539e 100644 --- a/Modules/RSDatabase/Sources/RSDatabase/Related Objects/RelatedObjectsMap.swift +++ b/Modules/RSDatabase/Sources/RSDatabase/Related Objects/RelatedObjectsMap.swift @@ -22,7 +22,7 @@ public struct RelatedObjectsMap: Sendable { for objectID in relatedObjectIDsMap.objectIDs() { if let relatedObjectIDs = relatedObjectIDsMap[objectID] { - let relatedObjects = relatedObjectIDs.compactMap{ relatedObjectsDictionary[$0] } + let relatedObjects = relatedObjectIDs.compactMap { relatedObjectsDictionary[$0] } if !relatedObjects.isEmpty { d[objectID] = relatedObjects } diff --git a/Modules/RSParser/Package.swift b/Modules/RSParser/Package.swift index d3c384d0c..57b81f16e 100644 --- a/Modules/RSParser/Package.swift +++ b/Modules/RSParser/Package.swift @@ -12,7 +12,7 @@ let package = Package( .library( name: "RSParserObjC", type: .dynamic, - targets: ["RSParserObjC"]), + targets: ["RSParserObjC"]) ], dependencies: [ .package(path: "../RSMarkdown") @@ -24,7 +24,7 @@ let package = Package( path: "Sources/Swift", swiftSettings: [ .enableUpcomingFeature("NonisolatedNonsendingByDefault"), - .enableUpcomingFeature("InferIsolatedConformances"), + .enableUpcomingFeature("InferIsolatedConformances") ]), .target( name: "RSParserObjC", @@ -41,8 +41,8 @@ let package = Package( resources: [.copy("Resources")], swiftSettings: [ .enableUpcomingFeature("NonisolatedNonsendingByDefault"), - .enableUpcomingFeature("InferIsolatedConformances"), + .enableUpcomingFeature("InferIsolatedConformances") ] - ), + ) ] ) diff --git a/Modules/RSParser/Sources/Swift/Feeds/FeedParser.swift b/Modules/RSParser/Sources/Swift/Feeds/FeedParser.swift index 61fb60821..102b91f73 100644 --- a/Modules/RSParser/Sources/Swift/Feeds/FeedParser.swift +++ b/Modules/RSParser/Sources/Swift/Feeds/FeedParser.swift @@ -68,8 +68,7 @@ public struct FeedParser { case .unknown, .notAFeed: return nil } - } - catch { throw error } + } catch { throw error } } public static func parse(_ parserData: ParserData) async throws -> ParsedFeed? { @@ -77,8 +76,7 @@ public struct FeedParser { parse(parserData) { parsedFeed, error in if let error { continuation.resume(throwing: error) - } - else { + } else { continuation.resume(returning: parsedFeed) } } diff --git a/Modules/RSParser/Sources/Swift/Feeds/JSON/JSONFeedParser.swift b/Modules/RSParser/Sources/Swift/Feeds/JSON/JSONFeedParser.swift index d5007e054..2b9800859 100644 --- a/Modules/RSParser/Sources/Swift/Feeds/JSON/JSONFeedParser.swift +++ b/Modules/RSParser/Sources/Swift/Feeds/JSON/JSONFeedParser.swift @@ -58,7 +58,7 @@ public struct JSONFeedParser { throw FeedParserError.invalidJSON } - guard let version = d[Key.version] as? String, let _ = version.range(of: JSONFeedParser.jsonFeedVersionMarker) else { + guard let version = d[Key.version] as? String, version.range(of: JSONFeedParser.jsonFeedVersionMarker) != nil else { throw FeedParserError.jsonFeedVersionNotFound } guard let itemsArray = d[Key.items] as? JSONArray else { diff --git a/Modules/RSParser/Sources/Swift/Feeds/JSON/RSSInJSONParser.swift b/Modules/RSParser/Sources/Swift/Feeds/JSON/RSSInJSONParser.swift index 1ddc9519a..7865c27b4 100644 --- a/Modules/RSParser/Sources/Swift/Feeds/JSON/RSSInJSONParser.swift +++ b/Modules/RSParser/Sources/Swift/Feeds/JSON/RSSInJSONParser.swift @@ -54,8 +54,7 @@ public struct RSSInJSONParser { return ParsedFeed(type: .rssInJSON, title: title, homePageURL: homePageURL, feedURL: feedURL, language: feedLanguage, feedDescription: feedDescription, nextURL: nil, iconURL: nil, faviconURL: nil, authors: nil, expired: false, hubs: nil, items: items) - } - catch { throw error } + } catch { throw error } } } @@ -117,11 +116,11 @@ private extension RSSInJSONParser { } if s.isEmpty { // Sheesh. Tough case. - if let _ = contentHTML { - s = contentHTML! + if let html = contentHTML { + s = html } - if let _ = contentText { - s = contentText! + if let text = contentText { + s = text } } uniqueID = (s as NSString).rsparser_md5Hash() @@ -149,9 +148,8 @@ private extension RSSInJSONParser { return Set([oneTag]) } return nil - } - else if let categoryArray = itemDictionary["category"] as? JSONArray { - return Set(categoryArray.compactMap{ $0["#value"] as? String }) + } else if let categoryArray = itemDictionary["category"] as? JSONArray { + return Set(categoryArray.compactMap { $0["#value"] as? String }) } return nil } diff --git a/Modules/RSParser/Sources/Swift/Feeds/ParsedItem.swift b/Modules/RSParser/Sources/Swift/Feeds/ParsedItem.swift index 035d3e17d..c88cabb7c 100644 --- a/Modules/RSParser/Sources/Swift/Feeds/ParsedItem.swift +++ b/Modules/RSParser/Sources/Swift/Feeds/ParsedItem.swift @@ -10,8 +10,8 @@ import Foundation import RSMarkdown public struct ParsedItem: Hashable, Sendable { - public let syncServiceID: String? //Nil when not syncing - public let uniqueID: String //RSS guid, for instance; may be calculated + public let syncServiceID: String? // Nil when not syncing + public let uniqueID: String // RSS guid, for instance; may be calculated public let feedURL: String public let url: String? public let externalURL: String? @@ -29,11 +29,24 @@ public struct ParsedItem: Hashable, Sendable { public let tags: Set? public let attachments: Set? - public init(syncServiceID: String?, uniqueID: String, feedURL: String, url: String?, externalURL: String?, title: String?, - language: String?, contentHTML: String?, contentText: String?, markdown: String?, summary: String?, imageURL: String?, - bannerImageURL: String?,datePublished: Date?, dateModified: Date?, authors: Set?, - tags: Set?, attachments: Set?) { - + public init(syncServiceID: String?, + uniqueID: String, + feedURL: String, + url: String?, + externalURL: String?, + title: String?, + language: String?, + contentHTML: String?, + contentText: String?, + markdown: String?, + summary: String?, + imageURL: String?, + bannerImageURL: String?, + datePublished: Date?, + dateModified: Date?, + authors: Set?, + tags: Set?, + attachments: Set?) { self.syncServiceID = syncServiceID self.uniqueID = uniqueID self.feedURL = feedURL @@ -65,8 +78,7 @@ public struct ParsedItem: Hashable, Sendable { public func hash(into hasher: inout Hasher) { if let syncServiceID = syncServiceID { hasher.combine(syncServiceID) - } - else { + } else { hasher.combine(uniqueID) hasher.combine(feedURL) } diff --git a/Modules/RSParser/Tests/RSParserTests/AtomParserTests.swift b/Modules/RSParser/Tests/RSParserTests/AtomParserTests.swift index 12dde3803..b98a7ae05 100644 --- a/Modules/RSParser/Tests/RSParserTests/AtomParserTests.swift +++ b/Modules/RSParser/Tests/RSParserTests/AtomParserTests.swift @@ -16,7 +16,7 @@ final class AtomParserTests: XCTestCase { // 0.009 sec on my 2012 iMac. let d = parserData("DaringFireball", "atom", "https://daringfireball.net/feeds/main") self.measure { - let _ = try! FeedParser.parse(d) + _ = try! FeedParser.parse(d) } } @@ -25,7 +25,7 @@ final class AtomParserTests: XCTestCase { // 0.003 sec on my 2012 iMac. let d = parserData("allthis", "atom", "http://leancrew.com/all-this") self.measure { - let _ = try! FeedParser.parse(d) + _ = try! FeedParser.parse(d) } } @@ -134,8 +134,7 @@ final class AtomParserTests: XCTestCase { let author = article.authors!.first! if author.name == "Daring Fireball Department of Commerce" { XCTAssertNil(author.url) - } - else { + } else { XCTAssertEqual(author.name, "John Gruber") XCTAssertEqual(author.url, "http://daringfireball.net/") } diff --git a/Modules/RSParser/Tests/RSParserTests/FeedParserTypeTests.swift b/Modules/RSParser/Tests/RSParserTests/FeedParserTypeTests.swift index 627ba8f74..0e3b3931e 100644 --- a/Modules/RSParser/Tests/RSParserTests/FeedParserTypeTests.swift +++ b/Modules/RSParser/Tests/RSParserTests/FeedParserTypeTests.swift @@ -201,7 +201,7 @@ final class FeedParserTypeTests: XCTestCase { let d = parserData("EMarley", "rss", "https://medium.com/@emarley") self.measure { - let _ = feedType(d) + _ = feedType(d) } } @@ -211,7 +211,7 @@ final class FeedParserTypeTests: XCTestCase { let d = parserData("inessential", "json", "http://inessential.com/") self.measure { - let _ = feedType(d) + _ = feedType(d) } } @@ -221,7 +221,7 @@ final class FeedParserTypeTests: XCTestCase { let d = parserData("DaringFireball", "html", "http://daringfireball.net/") self.measure { - let _ = feedType(d) + _ = feedType(d) } } @@ -231,7 +231,7 @@ final class FeedParserTypeTests: XCTestCase { let d = parserData("DaringFireball", "rss", "http://daringfireball.net/") self.measure { - let _ = feedType(d) + _ = feedType(d) } } diff --git a/Modules/RSParser/Tests/RSParserTests/HTMLLinkTests.swift b/Modules/RSParser/Tests/RSParserTests/HTMLLinkTests.swift index fb77aea3f..bc3a95371 100644 --- a/Modules/RSParser/Tests/RSParserTests/HTMLLinkTests.swift +++ b/Modules/RSParser/Tests/RSParserTests/HTMLLinkTests.swift @@ -17,7 +17,7 @@ final class HTMLLinkTests: XCTestCase { // 0.003 sec on my 2012 iMac let d = parserData("sixcolors", "html", "http://sixcolors.com/") self.measure { - let _ = RSHTMLLinkParser.htmlLinks(with: d) + _ = RSHTMLLinkParser.htmlLinks(with: d) } } diff --git a/Modules/RSParser/Tests/RSParserTests/HTMLMetadataTests.swift b/Modules/RSParser/Tests/RSParserTests/HTMLMetadataTests.swift index 441b748ad..3245e7706 100644 --- a/Modules/RSParser/Tests/RSParserTests/HTMLMetadataTests.swift +++ b/Modules/RSParser/Tests/RSParserTests/HTMLMetadataTests.swift @@ -32,7 +32,7 @@ final class HTMLMetadataTests: XCTestCase { // 0.002 sec on my 2012 iMac let d = parserData("DaringFireball", "html", "http://daringfireball.net/") self.measure { - let _ = RSHTMLMetadataParser.htmlMetadata(with: d) + _ = RSHTMLMetadataParser.htmlMetadata(with: d) } } @@ -55,7 +55,7 @@ final class HTMLMetadataTests: XCTestCase { // 0.001 sec on my 2012 iMac let d = parserData("furbo", "html", "http://furbo.org/") self.measure { - let _ = RSHTMLMetadataParser.htmlMetadata(with: d) + _ = RSHTMLMetadataParser.htmlMetadata(with: d) } } @@ -72,7 +72,7 @@ final class HTMLMetadataTests: XCTestCase { XCTAssertEqual(feedLink.type, "application/rss+xml") XCTAssertEqual(feedLink.urlString, "http://inessential.com/xml/rss.xml") - XCTAssertEqual(metadata.appleTouchIcons.count, 0); + XCTAssertEqual(metadata.appleTouchIcons.count, 0) } func testInessentialPerformance() { @@ -80,7 +80,7 @@ final class HTMLMetadataTests: XCTestCase { // 0.001 sec on my 2012 iMac let d = parserData("inessential", "html", "http://inessential.com/") self.measure { - let _ = RSHTMLMetadataParser.htmlMetadata(with: d) + _ = RSHTMLMetadataParser.htmlMetadata(with: d) } } @@ -89,7 +89,7 @@ final class HTMLMetadataTests: XCTestCase { // 0.004 sec on my 2012 iMac let d = parserData("coco", "html", "https://www.theatlantic.com/entertainment/archive/2017/11/coco-is-among-pixars-best-movies-in-years/546695/") self.measure { - let _ = RSHTMLMetadataParser.htmlMetadata(with: d) + _ = RSHTMLMetadataParser.htmlMetadata(with: d) } } @@ -100,17 +100,17 @@ final class HTMLMetadataTests: XCTestCase { XCTAssertEqual(metadata.favicons.first?.urlString, "https://sixcolors.com/images/favicon.ico") - XCTAssertEqual(metadata.feedLinks.count, 1); + XCTAssertEqual(metadata.feedLinks.count, 1) let feedLink = metadata.feedLinks.first! - XCTAssertEqual(feedLink.title, "RSS"); - XCTAssertEqual(feedLink.type, "application/rss+xml"); - XCTAssertEqual(feedLink.urlString, "http://feedpress.me/sixcolors"); + XCTAssertEqual(feedLink.title, "RSS") + XCTAssertEqual(feedLink.type, "application/rss+xml") + XCTAssertEqual(feedLink.urlString, "http://feedpress.me/sixcolors") - XCTAssertEqual(metadata.appleTouchIcons.count, 6); - let icon = metadata.appleTouchIcons[3]; - XCTAssertEqual(icon.rel, "apple-touch-icon"); - XCTAssertEqual(icon.sizes, "120x120"); - XCTAssertEqual(icon.urlString, "https://sixcolors.com/apple-touch-icon-120.png"); + XCTAssertEqual(metadata.appleTouchIcons.count, 6) + let icon = metadata.appleTouchIcons[3] + XCTAssertEqual(icon.rel, "apple-touch-icon") + XCTAssertEqual(icon.sizes, "120x120") + XCTAssertEqual(icon.urlString, "https://sixcolors.com/apple-touch-icon-120.png") } func testSixColorsPerformance() { @@ -118,7 +118,7 @@ final class HTMLMetadataTests: XCTestCase { // 0.002 sec on my 2012 iMac let d = parserData("sixcolors", "html", "http://sixcolors.com/") self.measure { - let _ = RSHTMLMetadataParser.htmlMetadata(with: d) + _ = RSHTMLMetadataParser.htmlMetadata(with: d) } } @@ -145,10 +145,10 @@ final class HTMLMetadataTests: XCTestCase { let d = parserData("YouTubeTheVolvoRocks", "html", "https://www.youtube.com/user/TheVolvorocks") let metadata = RSHTMLMetadataParser.htmlMetadata(with: d) - XCTAssertEqual(metadata.feedLinks.count, 1); + XCTAssertEqual(metadata.feedLinks.count, 1) let feedLink = metadata.feedLinks.first! - XCTAssertEqual(feedLink.title, "RSS"); - XCTAssertEqual(feedLink.type, "application/rss+xml"); - XCTAssertEqual(feedLink.urlString, "https://www.youtube.com/feeds/videos.xml?channel_id=UCct7QF2jcWRY6dhXWMSq9LQ"); + XCTAssertEqual(feedLink.title, "RSS") + XCTAssertEqual(feedLink.type, "application/rss+xml") + XCTAssertEqual(feedLink.urlString, "https://www.youtube.com/feeds/videos.xml?channel_id=UCct7QF2jcWRY6dhXWMSq9LQ") } } diff --git a/Modules/RSParser/Tests/RSParserTests/JSONFeedParserTests.swift b/Modules/RSParser/Tests/RSParserTests/JSONFeedParserTests.swift index 7de63ffed..4d25ddd11 100644 --- a/Modules/RSParser/Tests/RSParserTests/JSONFeedParserTests.swift +++ b/Modules/RSParser/Tests/RSParserTests/JSONFeedParserTests.swift @@ -16,7 +16,7 @@ final class JSONFeedParserTests: XCTestCase { // 0.001 sec on my 2012 iMac. let d = parserData("inessential", "json", "http://inessential.com/") self.measure { - let _ = try! FeedParser.parse(d) + _ = try! FeedParser.parse(d) } } @@ -25,7 +25,7 @@ final class JSONFeedParserTests: XCTestCase { // 0.009 sec on my 2012 iMac. let d = parserData("DaringFireball", "json", "http://daringfireball.net/") self.measure { - let _ = try! FeedParser.parse(d) + _ = try! FeedParser.parse(d) } } diff --git a/Modules/RSParser/Tests/RSParserTests/RSSInJSONParserTests.swift b/Modules/RSParser/Tests/RSParserTests/RSSInJSONParserTests.swift index b09530a6e..b8317fb72 100644 --- a/Modules/RSParser/Tests/RSParserTests/RSSInJSONParserTests.swift +++ b/Modules/RSParser/Tests/RSParserTests/RSSInJSONParserTests.swift @@ -16,7 +16,7 @@ final class RSSInJSONParserTests: XCTestCase { // 0.003 sec on my 2012 iMac. let d = parserData("ScriptingNews", "json", "http://scripting.com/") self.measure { - let _ = try! FeedParser.parse(d) + _ = try! FeedParser.parse(d) } } diff --git a/Modules/RSParser/Tests/RSParserTests/RSSParserTests.swift b/Modules/RSParser/Tests/RSParserTests/RSSParserTests.swift index ef71c5b1b..247070c24 100644 --- a/Modules/RSParser/Tests/RSParserTests/RSSParserTests.swift +++ b/Modules/RSParser/Tests/RSParserTests/RSSParserTests.swift @@ -16,7 +16,7 @@ final class RSSParserTests: XCTestCase { // 0.004 sec on my 2012 iMac. let d = parserData("scriptingNews", "rss", "http://scripting.com/") self.measure { - let _ = try! FeedParser.parse(d) + _ = try! FeedParser.parse(d) } } @@ -25,7 +25,7 @@ final class RSSParserTests: XCTestCase { // 0.004 sec on my 2012 iMac. let d = parserData("KatieFloyd", "rss", "http://katiefloyd.com/") self.measure { - let _ = try! FeedParser.parse(d) + _ = try! FeedParser.parse(d) } } @@ -34,7 +34,7 @@ final class RSSParserTests: XCTestCase { // 0.001 sec on my 2012 iMac. let d = parserData("EMarley", "rss", "https://medium.com/@emarley") self.measure { - let _ = try! FeedParser.parse(d) + _ = try! FeedParser.parse(d) } } @@ -43,7 +43,7 @@ final class RSSParserTests: XCTestCase { // 0.002 sec on my 2012 iMac. let d = parserData("manton", "rss", "http://manton.org/") self.measure { - let _ = try! FeedParser.parse(d) + _ = try! FeedParser.parse(d) } } diff --git a/Modules/RSTree/Package.swift b/Modules/RSTree/Package.swift index b570f1cec..ddee8ba52 100644 --- a/Modules/RSTree/Package.swift +++ b/Modules/RSTree/Package.swift @@ -8,7 +8,7 @@ let package = Package( .library( name: "RSTree", type: .dynamic, - targets: ["RSTree"]), + targets: ["RSTree"]) ], targets: [ .target( @@ -16,7 +16,7 @@ let package = Package( dependencies: [], swiftSettings: [ .enableUpcomingFeature("NonisolatedNonsendingByDefault"), - .enableUpcomingFeature("InferIsolatedConformances"), - ]), + .enableUpcomingFeature("InferIsolatedConformances") + ]) ] ) diff --git a/Modules/RSTree/Sources/RSTree/Node.swift b/Modules/RSTree/Sources/RSTree/Node.swift index 5a15e7e5a..fc1ee9ae6 100644 --- a/Modules/RSTree/Sources/RSTree/Node.swift +++ b/Modules/RSTree/Sources/RSTree/Node.swift @@ -159,7 +159,7 @@ import Foundation // MARK: - Equatable - nonisolated public class func ==(lhs: Node, rhs: Node) -> Bool { + nonisolated public static func ==(lhs: Node, rhs: Node) -> Bool { lhs === rhs } } diff --git a/Modules/RSTree/Sources/RSTree/TreeController.swift b/Modules/RSTree/Sources/RSTree/TreeController.swift index e47e071c4..ac967b8aa 100644 --- a/Modules/RSTree/Sources/RSTree/TreeController.swift +++ b/Modules/RSTree/Sources/RSTree/TreeController.swift @@ -12,7 +12,7 @@ import Foundation func treeController(treeController: TreeController, childNodesFor: Node) -> [Node]? } -public typealias NodeVisitBlock = (_ : Node) -> Void +public typealias NodeVisitBlock = (_: Node) -> Void @MainActor public final class TreeController { @@ -80,7 +80,7 @@ private extension TreeController { func visitNode(_ node: Node, _ visitBlock: NodeVisitBlock) { visitBlock(node) - node.childNodes.forEach{ (oneChildNode) in + node.childNodes.forEach { (oneChildNode) in visitNode(oneChildNode, visitBlock) } } @@ -109,12 +109,12 @@ private extension TreeController { let childNodes = delegate?.treeController(treeController: self, childNodesFor: node) ?? [Node]() childNodesDidChange = !nodeArraysAreEqual(childNodes, node.childNodes) - if (childNodesDidChange) { + if childNodesDidChange { node.childNodes = childNodes } - childNodes.forEach{ (oneChildNode) in - if rebuildChildNodes(node: oneChildNode) { + for childNode in childNodes { + if rebuildChildNodes(node: childNode) { childNodesDidChange = true } } diff --git a/Modules/RSWeb/Package.swift b/Modules/RSWeb/Package.swift index db1db76db..fe04b4be1 100644 --- a/Modules/RSWeb/Package.swift +++ b/Modules/RSWeb/Package.swift @@ -24,7 +24,7 @@ let package = Package( swiftSettings: [ .unsafeFlags(["-warnings-as-errors"]), .enableUpcomingFeature("NonisolatedNonsendingByDefault"), - .enableUpcomingFeature("InferIsolatedConformances"), + .enableUpcomingFeature("InferIsolatedConformances") ] ), .testTarget( diff --git a/Modules/RSWeb/Sources/RSWeb/Dictionary+RSWeb.swift b/Modules/RSWeb/Sources/RSWeb/Dictionary+RSWeb.swift index c244174a6..33722c902 100644 --- a/Modules/RSWeb/Sources/RSWeb/Dictionary+RSWeb.swift +++ b/Modules/RSWeb/Sources/RSWeb/Dictionary+RSWeb.swift @@ -8,7 +8,7 @@ import Foundation -nonisolated public extension Dictionary where Key == String, Value == String { +nonisolated public extension Dictionary where Key == String, Value == String { /// Translates a dictionary into a string like `foo=bar¶m2=some%20thing`. var urlQueryString: String? { diff --git a/Modules/RSWeb/Sources/RSWeb/DownloadProgress.swift b/Modules/RSWeb/Sources/RSWeb/DownloadProgress.swift index 077fa9d05..2eae82b1b 100755 --- a/Modules/RSWeb/Sources/RSWeb/DownloadProgress.swift +++ b/Modules/RSWeb/Sources/RSWeb/DownloadProgress.swift @@ -150,7 +150,7 @@ nonisolated public final class DownloadProgress: Hashable, Sendable { hasher.combine(id) } - // MARK - Equatable + // MARK: - Equatable public static func ==(lhs: DownloadProgress, rhs: DownloadProgress) -> Bool { lhs.id == rhs.id diff --git a/Modules/RSWeb/Sources/RSWeb/DownloadSession.swift b/Modules/RSWeb/Sources/RSWeb/DownloadSession.swift index 4937f71a0..b669117c9 100755 --- a/Modules/RSWeb/Sources/RSWeb/DownloadSession.swift +++ b/Modules/RSWeb/Sources/RSWeb/DownloadSession.swift @@ -199,7 +199,7 @@ extension DownloadSession: @preconcurrency URLSessionDataDelegate { return } info.addData(data) - + if !delegate.downloadSession(self, shouldContinueAfterReceivingData: info.data as Data, url: info.url) { dataTask.cancel() removeTask(dataTask) @@ -276,7 +276,7 @@ private extension DownloadSession { updateDownloadProgress() } - func urlStringIsBlackListedRedirect(_ urlString: String) -> Bool { + func urlStringIsDisallowedRedirect(_ urlString: String) -> Bool { // Hotels and similar often do permanent redirects. We can catch some of those. @@ -293,7 +293,7 @@ private extension DownloadSession { } func cacheRedirect(_ oldURL: URL, _ newURL: URL) { - if urlStringIsBlackListedRedirect(newURL.absoluteString) { + if urlStringIsDisallowedRedirect(newURL.absoluteString) { return } redirectCache[oldURL] = newURL @@ -308,7 +308,7 @@ private extension DownloadSession { var currentURL = url - while(true) { + while true { if let oneRedirectURL = redirectCache[currentURL] { diff --git a/Modules/RSWeb/Sources/RSWeb/HTTPConditionalGetInfo.swift b/Modules/RSWeb/Sources/RSWeb/HTTPConditionalGetInfo.swift index 8753f2690..66e535ea3 100755 --- a/Modules/RSWeb/Sources/RSWeb/HTTPConditionalGetInfo.swift +++ b/Modules/RSWeb/Sources/RSWeb/HTTPConditionalGetInfo.swift @@ -27,7 +27,7 @@ nonisolated public struct HTTPConditionalGetInfo: Codable, Equatable { self.init(lastModified: lastModified, etag: etag) } - public init?(headers: [AnyHashable : Any]) { + public init?(headers: [AnyHashable: Any]) { let lastModified = headers[HTTPResponseHeader.lastModified] as? String let etag = headers[HTTPResponseHeader.etag] as? String self.init(lastModified: lastModified, etag: etag) diff --git a/Modules/RSWeb/Sources/RSWeb/HTTPLinkPagingInfo.swift b/Modules/RSWeb/Sources/RSWeb/HTTPLinkPagingInfo.swift index c3cbe1b24..cd2d05f07 100644 --- a/Modules/RSWeb/Sources/RSWeb/HTTPLinkPagingInfo.swift +++ b/Modules/RSWeb/Sources/RSWeb/HTTPLinkPagingInfo.swift @@ -29,7 +29,7 @@ public struct HTTPLinkPagingInfo { var dict: [String: String] = [:] links.forEach({ - let components = $0.components(separatedBy:"; ") + let components = $0.components(separatedBy: "; ") let page = components[0].trimmingCharacters(in: CharacterSet(charactersIn: " <>")) dict[components[1]] = page }) diff --git a/Modules/RSWeb/Sources/RSWeb/HTTPRequestHeader.swift b/Modules/RSWeb/Sources/RSWeb/HTTPRequestHeader.swift index 8da0be40c..765c3aaba 100755 --- a/Modules/RSWeb/Sources/RSWeb/HTTPRequestHeader.swift +++ b/Modules/RSWeb/Sources/RSWeb/HTTPRequestHeader.swift @@ -17,5 +17,5 @@ nonisolated public struct HTTPRequestHeader { // Conditional GET public static let ifModifiedSince = "If-Modified-Since" - public static let ifNoneMatch = "If-None-Match" //Etag + public static let ifNoneMatch = "If-None-Match" // Etag } diff --git a/Modules/RSWeb/Sources/RSWeb/HTTPResponseCode.swift b/Modules/RSWeb/Sources/RSWeb/HTTPResponseCode.swift index 6e9bf46e7..4847bd0a7 100755 --- a/Modules/RSWeb/Sources/RSWeb/HTTPResponseCode.swift +++ b/Modules/RSWeb/Sources/RSWeb/HTTPResponseCode.swift @@ -13,7 +13,7 @@ public struct HTTPResponseCode { // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html // Not an enum because the main interest is the actual values. - public static let responseContinue = 100 //"continue" is a language keyword, hence the weird name + public static let responseContinue = 100 // "continue" is a language keyword, hence the weird name public static let switchingProtocols = 101 public static let OK = 200 diff --git a/Modules/RSWeb/Sources/RSWeb/MacWebBrowser.swift b/Modules/RSWeb/Sources/RSWeb/MacWebBrowser.swift index c187f842f..0db15ed6a 100755 --- a/Modules/RSWeb/Sources/RSWeb/MacWebBrowser.swift +++ b/Modules/RSWeb/Sources/RSWeb/MacWebBrowser.swift @@ -146,7 +146,7 @@ import UniformTypeIdentifiers extension MacWebBrowser: CustomDebugStringConvertible { public var debugDescription: String { - if let name = name, let bundleIdentifier = bundleIdentifier{ + if let name, let bundleIdentifier { return "MacWebBrowser: \(name) (\(bundleIdentifier))" } else { return "MacWebBrowser" diff --git a/Modules/RSWeb/Sources/RSWeb/String+RSWeb.swift b/Modules/RSWeb/Sources/RSWeb/String+RSWeb.swift index 4819b27e6..d2fbc0ed9 100644 --- a/Modules/RSWeb/Sources/RSWeb/String+RSWeb.swift +++ b/Modules/RSWeb/Sources/RSWeb/String+RSWeb.swift @@ -18,22 +18,21 @@ nonisolated public extension String { for char in self { switch char { - case "&": - escaped.append("&") - case "<": - escaped.append("<") - case ">": - escaped.append(">") - case "\"": - escaped.append(""") - case "'": - escaped.append("'") - default: - escaped.append(char) + case "&": + escaped.append("&") + case "<": + escaped.append("<") + case ">": + escaped.append(">") + case "\"": + escaped.append(""") + case "'": + escaped.append("'") + default: + escaped.append(char) } } return escaped } - } diff --git a/Modules/RSWeb/Sources/RSWeb/URL+RSWeb.swift b/Modules/RSWeb/Sources/RSWeb/URL+RSWeb.swift index 1668ea3b4..867f128ef 100755 --- a/Modules/RSWeb/Sources/RSWeb/URL+RSWeb.swift +++ b/Modules/RSWeb/Sources/RSWeb/URL+RSWeb.swift @@ -34,8 +34,7 @@ public extension URL { if isHTTPSURL() { return absoluteString.stringByRemovingCaseInsensitivePrefix(URLConstants.prefixHTTPS) - } - else if isHTTPURL() { + } else if isHTTPURL() { return absoluteString.stringByRemovingCaseInsensitivePrefix(URLConstants.prefixHTTP) } @@ -76,7 +75,7 @@ private extension String { let lowerPrefix = prefix.lowercased() let lowerSelf = self.lowercased() - if (lowerSelf == lowerPrefix) { + if lowerSelf == lowerPrefix { return "" } if !lowerSelf.hasPrefix(lowerPrefix) { diff --git a/Modules/RSWeb/Sources/RSWeb/WebServices/Transport.swift b/Modules/RSWeb/Sources/RSWeb/WebServices/Transport.swift index a338245e1..06299efd6 100644 --- a/Modules/RSWeb/Sources/RSWeb/WebServices/Transport.swift +++ b/Modules/RSWeb/Sources/RSWeb/WebServices/Transport.swift @@ -193,7 +193,7 @@ nonisolated extension URLSession: Transport { var sendRequest = request sendRequest.httpMethod = method - let task = self.dataTask(with: sendRequest) { (data, response, error) in + let task = self.dataTask(with: sendRequest) { (_, response, error) in DispatchQueue.main.async { if let error = error { return completion(.failure(error)) diff --git a/Modules/RSWeb/Sources/RSWeb/WebServices/TransportJSON.swift b/Modules/RSWeb/Sources/RSWeb/WebServices/TransportJSON.swift index 043867417..3ba49e2a6 100644 --- a/Modules/RSWeb/Sources/RSWeb/WebServices/TransportJSON.swift +++ b/Modules/RSWeb/Sources/RSWeb/WebServices/TransportJSON.swift @@ -42,15 +42,13 @@ nonisolated extension Transport { DispatchQueue.main.async { completion(.success((response, decoded))) } - } - catch { + } catch { DispatchQueue.main.async { completion(.failure(error)) } } } - } - else { + } else { completion(.success((response, nil))) } diff --git a/Modules/Secrets/Sources/Secrets/CredentialsManager.swift b/Modules/Secrets/Sources/Secrets/CredentialsManager.swift index caa13f0d8..45b5ec65e 100644 --- a/Modules/Secrets/Sources/Secrets/CredentialsManager.swift +++ b/Modules/Secrets/Sources/Secrets/CredentialsManager.swift @@ -84,7 +84,7 @@ public struct CredentialsManager { throw CredentialsError.unhandledError(status: status) } - guard let existingItem = item as? [String : Any], + guard let existingItem = item as? [String: Any], let secretData = existingItem[kSecValueData as String] as? Data, let secret = String(data: secretData, encoding: String.Encoding.utf8) else { return nil diff --git a/Shared/Commands/DeleteCommand.swift b/Shared/Commands/DeleteCommand.swift index 1e4833164..c1b81771b 100644 --- a/Shared/Commands/DeleteCommand.swift +++ b/Shared/Commands/DeleteCommand.swift @@ -19,11 +19,11 @@ final class DeleteCommand: UndoableCommand { var redoActionName: String { undoActionName } - let errorHandler: (Error) -> () + let errorHandler: (Error) -> Void private let itemSpecifiers: [SidebarItemSpecifier] - @MainActor init?(nodesToDelete: [Node], treeController: TreeController? = nil, undoManager: UndoManager, errorHandler: @escaping (Error) -> ()) { + @MainActor init?(nodesToDelete: [Node], treeController: TreeController? = nil, undoManager: UndoManager, errorHandler: @escaping (Error) -> Void) { guard DeleteCommand.canDelete(nodesToDelete) else { return nil @@ -77,10 +77,7 @@ final class DeleteCommand: UndoableCommand { } for node in nodes { - if let _ = node.representedObject as? Feed { - continue - } - if let _ = node.representedObject as? Folder { + if node.representedObject is Feed || node.representedObject is Folder { continue } return false @@ -100,7 +97,7 @@ final class DeleteCommand: UndoableCommand { private let folder: Folder? private let feed: Feed? private let path: ContainerPath - private let errorHandler: (Error) -> () + private let errorHandler: (Error) -> Void private var container: Container? { if let parentFolder = parentFolder { @@ -165,10 +162,9 @@ final class DeleteCommand: UndoableCommand { } func restore() { - if let _ = feed { + if feed != nil { restoreFeed() - } - else if let _ = folder { + } else if folder != nil { restoreFolder() } } @@ -234,8 +230,7 @@ final class DeleteCommand: UndoableCommand { while nomad != nil { if let folder = nomad!.representedObject as? Folder { folders += [folder] - } - else { + } else { break } nomad = nomad!.parent @@ -259,13 +254,11 @@ private struct DeleteActionName { var numberOfFolders = 0 for node in nodes { - if let _ = node.representedObject as? Feed { + if node.representedObject is Feed { numberOfFeeds += 1 - } - else if let _ = node.representedObject as? Folder { + } else if node.representedObject is Folder { numberOfFolders += 1 - } - else { + } else { return nil // Delete only Feeds and Folders. } } diff --git a/Shared/Extensions/NSAttributedString+Extensions.swift b/Shared/Extensions/NSAttributedString+Extensions.swift index 38f532e98..0371ff9c7 100644 --- a/Shared/Extensions/NSAttributedString+Extensions.swift +++ b/Shared/Extensions/NSAttributedString+Extensions.swift @@ -40,8 +40,10 @@ extension NSAttributedString { let baseDescriptor = baseFont.fontDescriptor let baseSymbolicTraits = baseDescriptor.symbolicTraits - mutable.enumerateAttribute(.font, in: fullRange, options: []) { (font: Any?, range: NSRange, stop: UnsafeMutablePointer) in - guard let font = font as? Font else { return } + mutable.enumerateAttribute(.font, in: fullRange, options: []) { (font, range, _) in + guard let font = font as? Font else { + return + } let currentDescriptor = font.fontDescriptor let symbolicTraits = baseSymbolicTraits.union(currentDescriptor.symbolicTraits) @@ -79,22 +81,22 @@ extension NSAttributedString { init?(forTag: String) { switch forTag { - case "b", "strong": - self = .bold - case "i", "em", "cite", "var", "dfn": - self = .italic - case "sup": - self = .superscript - case "sub": - self = .subscript - case "u", "ins": - self = .underline - case "s", "del": - self = .strikethrough - case "code", "samp", "tt", "kbd": - self = .monospace - default: - return nil + case "b", "strong": + self = .bold + case "i", "em", "cite", "var", "dfn": + self = .italic + case "sup": + self = .superscript + case "sub": + self = .subscript + case "u", "ins": + self = .underline + case "s", "del": + self = .strikethrough + case "code", "samp", "tt", "kbd": + self = .monospace + default: + return nil } } } @@ -170,7 +172,7 @@ extension NSAttributedString { while let entitychar = iterator.next() { if entitychar.isWhitespace { lastchar = entitychar - break; + break } entity.append(entitychar) @@ -276,13 +278,11 @@ private struct CountedSet where Element: Hashable { } func contains(_ element: Element) -> Bool { - return _storage[element] != nil + _storage[element] != nil } subscript(key: Element) -> Int { - get { - return _storage[key, default: 0] - } + _storage[key, default: 0] } } diff --git a/Shared/Timeline/ArticleArray.swift b/Shared/Timeline/ArticleArray.swift index 0f5552a4d..071d1fae5 100644 --- a/Shared/Timeline/ArticleArray.swift +++ b/Shared/Timeline/ArticleArray.swift @@ -27,10 +27,10 @@ typealias ArticleArray = [Article] func orderedRowIndexes(fromIndex startIndex: Int, wrappingToTop wrapping: Bool) -> [Int] { if startIndex >= self.count { // Wrap around to the top if specified - return wrapping ? Array(0..(startIndex..(0.. Int? { @@ -132,6 +132,4 @@ typealias ArticleArray = [Article] articlesBelow.removeFirst() return articlesBelow } - } - diff --git a/Shared/Timeline/ArticleSorter.swift b/Shared/Timeline/ArticleSorter.swift index 9eefd698d..fb536b3a9 100644 --- a/Shared/Timeline/ArticleSorter.swift +++ b/Shared/Timeline/ArticleSorter.swift @@ -18,20 +18,20 @@ import Foundation @MainActor struct ArticleSorter { - static func sortedByDate(articles: [T], - sortDirection: ComparisonResult, - groupByFeed: Bool) -> [T] { + static func sortedByDate(articles: [T], sortDirection: ComparisonResult, groupByFeed: Bool) -> [T] { if groupByFeed { return sortedByFeedName(articles: articles, sortByDateDirection: sortDirection) } else { return sortedByDate(articles: articles, sortDirection: sortDirection) } } +} - // MARK: - +// MARK: - Private - private static func sortedByFeedName(articles: [T], - sortByDateDirection: ComparisonResult) -> [T] { +private extension ArticleSorter { + + static func sortedByFeedName(articles: [T], sortByDateDirection: ComparisonResult) -> [T] { // Group articles by "feed-feedID" - feed ID is used to differentiate between // two feeds that have the same name let groupedArticles = Dictionary(grouping: articles) { "\($0.sortableName.lowercased())-\($0.sortableFeedID)" } @@ -44,9 +44,8 @@ import Foundation } } - private static func sortedByDate(articles: [T], - sortDirection: ComparisonResult) -> [T] { - return articles.sorted { (article1, article2) -> Bool in + static func sortedByDate(articles: [T], sortDirection: ComparisonResult) -> [T] { + articles.sorted { (article1, article2) -> Bool in if article1.sortableDate == article2.sortableDate { return article1.sortableArticleID < article2.sortableArticleID } @@ -57,5 +56,4 @@ import Foundation return article1.sortableDate < article2.sortableDate } } - } diff --git a/iOS/Account/CloudKitAccountViewController.swift b/iOS/Account/CloudKitAccountViewController.swift index 0006aa461..82d0d388d 100644 --- a/iOS/Account/CloudKitAccountViewController.swift +++ b/iOS/Account/CloudKitAccountViewController.swift @@ -38,7 +38,7 @@ final class CloudKitAccountViewController: UITableViewController { return } - let _ = AccountManager.shared.createAccount(type: .cloudKit) + _ = AccountManager.shared.createAccount(type: .cloudKit) dismiss(animated: true, completion: nil) delegate?.dismiss() } diff --git a/iOS/Account/FeedbinAccountViewController.swift b/iOS/Account/FeedbinAccountViewController.swift index cecbdc553..687bf8bf5 100644 --- a/iOS/Account/FeedbinAccountViewController.swift +++ b/iOS/Account/FeedbinAccountViewController.swift @@ -149,7 +149,7 @@ final class FeedbinAccountViewController: UITableViewController { } @objc func textDidChange(_ note: Notification) { - actionButton.isEnabled = !(emailTextField.text?.isEmpty ?? false) && !(passwordTextField.text?.isEmpty ?? false) + actionButton.isEnabled = !(emailTextField.text?.isEmpty ?? false) && !(passwordTextField.text?.isEmpty ?? false) } private func showError(_ message: String) { @@ -161,7 +161,7 @@ final class FeedbinAccountViewController: UITableViewController { actionButton.isEnabled = value } - private func toggleActivityIndicatorAnimation(visible value: Bool){ + private func toggleActivityIndicatorAnimation(visible value: Bool) { activityIndicator.isHidden = !value if value { activityIndicator.startAnimating() diff --git a/iOS/Account/ReaderAPIAccountViewController.swift b/iOS/Account/ReaderAPIAccountViewController.swift index 61a15c151..8a3589f94 100644 --- a/iOS/Account/ReaderAPIAccountViewController.swift +++ b/iOS/Account/ReaderAPIAccountViewController.swift @@ -71,20 +71,20 @@ final class ReaderAPIAccountViewController: UITableViewController { private func setupFooter() { switch accountType { - case .bazQux: - footerLabel.text = NSLocalizedString("Sign in to your BazQux account and sync your feeds across your devices. Your username and password will be encrypted and stored in Keychain.\n\nDon’t have a BazQux account?", comment: "BazQux") - signUpButton.setTitle(NSLocalizedString("Sign Up Here", comment: "BazQux SignUp"), for: .normal) - case .inoreader: - footerLabel.text = NSLocalizedString("Sign in to your Inoreader account and sync your feeds across your devices. Your username and password will be encrypted and stored in Keychain.\n\nDon’t have an Inoreader account?", comment: "Inoreader") - signUpButton.setTitle(NSLocalizedString("Sign Up Here", comment: "Inoreader SignUp"), for: .normal) - case .theOldReader: - footerLabel.text = NSLocalizedString("Sign in to your The Old Reader account and sync your feeds across your devices. Your username and password will be encrypted and stored in Keychain.\n\nDon’t have a The Old Reader account?", comment: "TOR") - signUpButton.setTitle(NSLocalizedString("Sign Up Here", comment: "TOR SignUp"), for: .normal) - case .freshRSS: - footerLabel.text = NSLocalizedString("Sign in to your FreshRSS instance and sync your feeds across your devices. Your username and password will be encrypted and stored in Keychain.\n\nDon’t have an FreshRSS instance?", comment: "FreshRSS") - signUpButton.setTitle(NSLocalizedString("Find Out More", comment: "FreshRSS SignUp"), for: .normal) - default: - return + case .bazQux: + footerLabel.text = NSLocalizedString("Sign in to your BazQux account and sync your feeds across your devices. Your username and password will be encrypted and stored in Keychain.\n\nDon’t have a BazQux account?", comment: "BazQux") + signUpButton.setTitle(NSLocalizedString("Sign Up Here", comment: "BazQux SignUp"), for: .normal) + case .inoreader: + footerLabel.text = NSLocalizedString("Sign in to your Inoreader account and sync your feeds across your devices. Your username and password will be encrypted and stored in Keychain.\n\nDon’t have an Inoreader account?", comment: "Inoreader") + signUpButton.setTitle(NSLocalizedString("Sign Up Here", comment: "Inoreader SignUp"), for: .normal) + case .theOldReader: + footerLabel.text = NSLocalizedString("Sign in to your The Old Reader account and sync your feeds across your devices. Your username and password will be encrypted and stored in Keychain.\n\nDon’t have a The Old Reader account?", comment: "TOR") + signUpButton.setTitle(NSLocalizedString("Sign Up Here", comment: "TOR SignUp"), for: .normal) + case .freshRSS: + footerLabel.text = NSLocalizedString("Sign in to your FreshRSS instance and sync your feeds across your devices. Your username and password will be encrypted and stored in Keychain.\n\nDon’t have an FreshRSS instance?", comment: "FreshRSS") + signUpButton.setTitle(NSLocalizedString("Find Out More", comment: "FreshRSS SignUp"), for: .normal) + default: + return } } @@ -230,7 +230,7 @@ final class ReaderAPIAccountViewController: UITableViewController { showError(NSLocalizedString("Username, password, and API URL are required.", comment: "Credentials Error")) return false } - guard let _ = URL(string: apiURLTextField.text!) else { + guard URL(string: apiURLTextField.text!) != nil else { showError(NSLocalizedString("Invalid API URL.", comment: "Invalid API URL")) return false } @@ -246,16 +246,16 @@ final class ReaderAPIAccountViewController: UITableViewController { @IBAction func signUpWithProvider(_ sender: Any) { var url: URL! switch accountType { - case .bazQux: - url = URL(string: "https://bazqux.com")! - case .inoreader: - url = URL(string: "https://www.inoreader.com")! - case .theOldReader: - url = URL(string: "https://theoldreader.com")! - case .freshRSS: - url = URL(string: "https://freshrss.org")! - default: - return + case .bazQux: + url = URL(string: "https://bazqux.com")! + case .inoreader: + url = URL(string: "https://www.inoreader.com")! + case .theOldReader: + url = URL(string: "https://theoldreader.com")! + case .freshRSS: + url = URL(string: "https://freshrss.org")! + default: + return } let safari = SFSafariViewController(url: url) safari.modalPresentationStyle = .currentContext diff --git a/iOS/Add/AddFolderViewController.swift b/iOS/Add/AddFolderViewController.swift index daec8ef3d..bd7438d7a 100644 --- a/iOS/Add/AddFolderViewController.swift +++ b/iOS/Add/AddFolderViewController.swift @@ -102,13 +102,13 @@ final class AddFolderViewController: UITableViewController { return defaultNumberOfRows - 1 } - return defaultNumberOfRows + return defaultNumberOfRows } } extension AddFolderViewController: UIPickerViewDataSource, UIPickerViewDelegate { - func numberOfComponents(in pickerView: UIPickerView) ->Int { + func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } @@ -123,7 +123,6 @@ extension AddFolderViewController: UIPickerViewDataSource, UIPickerViewDelegate func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { didSelect(accounts[row]) } - } extension AddFolderViewController: UITextFieldDelegate { @@ -132,5 +131,4 @@ extension AddFolderViewController: UITextFieldDelegate { textField.resignFirstResponder() return true } - } diff --git a/iOS/AppDefaults.swift b/iOS/AppDefaults.swift index ab85440af..aa66773e7 100644 --- a/iOS/AppDefaults.swift +++ b/iOS/AppDefaults.swift @@ -84,7 +84,7 @@ final class AppDefaults: Sendable { }() let isFirstRun: Bool = { - if let _ = AppDefaults.store.object(forKey: Key.firstRunDate) as? Date { + if AppDefaults.store.object(forKey: Key.firstRunDate) is Date { return false } firstRunDate = Date() @@ -443,8 +443,7 @@ private extension AppDefaults { static func setSortDirection(for key: String, _ value: ComparisonResult) { if value == .orderedAscending { setInt(for: key, ComparisonResult.orderedAscending.rawValue) - } - else { + } else { setInt(for: key, ComparisonResult.orderedDescending.rawValue) } } @@ -462,14 +461,14 @@ struct StateRestorationInfo { let isShowingExtractedArticle: Bool init(hideReadFeeds: Bool, - expandedContainers: Set, - selectedSidebarItem: SidebarItemIdentifier?, - smartFeedsHidingReadArticles: Set, - feedsHidingReadArticles: [String: Set], - foldersShowingReadArticles: [String: Set], - selectedArticle: ArticleSpecifier?, - articleWindowScrollY: Int, - isShowingExtractedArticle: Bool) { + expandedContainers: Set, + selectedSidebarItem: SidebarItemIdentifier?, + smartFeedsHidingReadArticles: Set, + feedsHidingReadArticles: [String: Set], + foldersShowingReadArticles: [String: Set], + selectedArticle: ArticleSpecifier?, + articleWindowScrollY: Int, + isShowingExtractedArticle: Bool) { self.hideReadFeeds = hideReadFeeds self.expandedContainers = expandedContainers self.selectedSidebarItem = selectedSidebarItem diff --git a/iOS/AppDelegate.swift b/iOS/AppDelegate.swift index bbe5a517a..583b0868f 100644 --- a/iOS/AppDelegate.swift +++ b/iOS/AppDelegate.swift @@ -82,7 +82,7 @@ import Secrets self.updateBadge() } - UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert]) { (granted, error) in + UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert]) { (granted, _) in if granted { DispatchQueue.main.async { UIApplication.shared.registerForRemoteNotifications() @@ -143,8 +143,8 @@ import Secrets // MARK: - API - func manualRefresh(errorHandler: @escaping @Sendable (Error) -> ()) { - UIApplication.shared.connectedScenes.compactMap( { $0.delegate as? SceneDelegate } ).forEach { + func manualRefresh(errorHandler: @escaping @Sendable (Error) -> Void) { + UIApplication.shared.connectedScenes.compactMap( { $0.delegate as? SceneDelegate }).forEach { $0.cleanUp(conditional: true) } AccountManager.shared.refreshAllWithoutWaiting(errorHandler: errorHandler) @@ -264,7 +264,7 @@ private extension AppDelegate { } DispatchQueue.main.async { [weak self] in - self?.waitToComplete() { [weak self] suspend in + self?.waitToComplete { [weak self] suspend in self?.completeProcessing(suspend) } } diff --git a/iOS/Article/ArticleIconSchemeHandler.swift b/iOS/Article/ArticleIconSchemeHandler.swift index 092c6e689..4c909b9a9 100644 --- a/iOS/Article/ArticleIconSchemeHandler.swift +++ b/iOS/Article/ArticleIconSchemeHandler.swift @@ -11,7 +11,6 @@ import WebKit import Articles final class ArticleIconSchemeHandler: NSObject, WKURLSchemeHandler { - weak var coordinator: SceneCoordinator? init(coordinator: SceneCoordinator) { @@ -49,12 +48,9 @@ final class ArticleIconSchemeHandler: NSObject, WKURLSchemeHandler { urlSchemeTask.didReceive(data) urlSchemeTask.didFinish() } - } func webView(_ webView: WKWebView, stop urlSchemeTask: WKURLSchemeTask) { urlSchemeTask.didFailWithError(URLError(.unknown)) } - } - diff --git a/iOS/Article/ArticleViewController.swift b/iOS/Article/ArticleViewController.swift index 254b8ac56..3830daf46 100644 --- a/iOS/Article/ArticleViewController.swift +++ b/iOS/Article/ArticleViewController.swift @@ -364,8 +364,7 @@ public extension Notification.Name { extension ArticleViewController: SearchBarDelegate { func searchBar(_ searchBar: ArticleSearchBar, textDidChange searchText: String) { - currentWebViewController?.searchText(searchText) { - found in + currentWebViewController?.searchText(searchText) { found in searchBar.resultsCount = found.count if let index = found.index { diff --git a/iOS/Article/FindInArticleActivity.swift b/iOS/Article/FindInArticleActivity.swift index c915432d4..6c9e7668f 100644 --- a/iOS/Article/FindInArticleActivity.swift +++ b/iOS/Article/FindInArticleActivity.swift @@ -21,7 +21,7 @@ final class FindInArticleActivity: UIActivity { UIImage(systemName: "magnifyingglass", withConfiguration: UIImage.SymbolConfiguration(pointSize: 20, weight: .regular)) } - override class var activityCategory: UIActivity.Category { + override static var activityCategory: UIActivity.Category { .action } diff --git a/iOS/Article/ImageTransition.swift b/iOS/Article/ImageTransition.swift index a4a861c02..941af5459 100644 --- a/iOS/Article/ImageTransition.swift +++ b/iOS/Article/ImageTransition.swift @@ -94,7 +94,7 @@ final class ImageTransition: NSObject, UIViewControllerAnimatedTransitioning { imageView.frame = self.originFrame }, completion: { _ in if let controller = self.webViewController { - controller.showClickedImage() { + controller.showClickedImage { DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { imageView.removeFromSuperview() transitionContext.completeTransition(true) diff --git a/iOS/Article/ImageViewController.swift b/iOS/Article/ImageViewController.swift index 16e95c206..1d4ad685d 100644 --- a/iOS/Article/ImageViewController.swift +++ b/iOS/Article/ImageViewController.swift @@ -58,7 +58,7 @@ final class ImageViewController: UIViewController { override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) - coordinator.animate(alongsideTransition: { [weak self] context in + coordinator.animate(alongsideTransition: { [weak self] _ in self?.imageScrollView.resize() }) } @@ -75,7 +75,7 @@ final class ImageViewController: UIViewController { dismiss(animated: true) } - private func layoutTitleLabel(){ + private func layoutTitleLabel() { let width = view.frame.width let multiplier = traitCollection.userInterfaceIdiom == .pad ? CGFloat(0.1) : CGFloat(0.04) titleLeading.constant += width * multiplier diff --git a/iOS/Article/OpenInSafariActivity.swift b/iOS/Article/OpenInSafariActivity.swift index e7a743d22..6e456be8a 100644 --- a/iOS/Article/OpenInSafariActivity.swift +++ b/iOS/Article/OpenInSafariActivity.swift @@ -24,7 +24,7 @@ final class OpenInBrowserActivity: UIActivity { return UIActivity.ActivityType(rawValue: "com.rancharo.NetNewsWire-Evergreen.safari") } - override class var activityCategory: UIActivity.Category { + override static var activityCategory: UIActivity.Category { return .action } @@ -45,7 +45,7 @@ final class OpenInBrowserActivity: UIActivity { Task { @MainActor in UIApplication.shared.open(url, options: [:], completionHandler: nil) } - + activityDidFinish(true) } } diff --git a/iOS/Article/WebViewController.swift b/iOS/Article/WebViewController.swift index 318080ecf..9f819c666 100644 --- a/iOS/Article/WebViewController.swift +++ b/iOS/Article/WebViewController.swift @@ -40,7 +40,7 @@ final class WebViewController: UIViewController { private var isFullScreenAvailable: Bool { return AppDefaults.shared.articleFullscreenAvailable && traitCollection.userInterfaceIdiom == .phone && coordinator.isRootSplitCollapsed } - private lazy var articleIconSchemeHandler = ArticleIconSchemeHandler(coordinator: coordinator); + private lazy var articleIconSchemeHandler = ArticleIconSchemeHandler(coordinator: coordinator) private lazy var transition = ImageTransition(controller: self) private var clickedImageCompletion: (() -> Void)? @@ -177,7 +177,7 @@ final class WebViewController: UIViewController { let overlap = 2 * UIFont.systemFont(ofSize: UIFont.systemFontSize).lineHeight * windowScene.screen.scale let scrollToY: CGFloat = { - let scrollDistance = webView.scrollView.layoutMarginsGuide.layoutFrame.height - overlap; + let scrollDistance = webView.scrollView.layoutMarginsGuide.layoutFrame.height - overlap let fullScroll = webView.scrollView.contentOffset.y + (scrollingUp ? -scrollDistance : scrollDistance) let final = finalScrollPosition(scrollingUp: scrollingUp) return (scrollingUp ? fullScroll > final : fullScroll < final) ? fullScroll : final @@ -321,7 +321,7 @@ extension WebViewController: ArticleExtractorDelegate { extension WebViewController: UIContextMenuInteractionDelegate { func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? { - return UIContextMenuConfiguration(identifier: nil, previewProvider: contextMenuPreviewProvider) { [weak self] suggestedActions in + return UIContextMenuConfiguration(identifier: nil, previewProvider: contextMenuPreviewProvider) { [weak self] _ in guard let self = self else { return nil } var menus = [UIMenu]() @@ -403,7 +403,7 @@ extension WebViewController: WKNavigationDelegate { } if UIApplication.shared.canOpenURL(emailAddress) { - UIApplication.shared.open(emailAddress, options: [.universalLinksOnly : false], completionHandler: nil) + UIApplication.shared.open(emailAddress, options: [.universalLinksOnly: false], completionHandler: nil) } else { let alert = UIAlertController(title: NSLocalizedString("Error", comment: "Error"), message: NSLocalizedString("This device cannot send emails.", comment: "This device cannot send emails."), preferredStyle: .alert) alert.addAction(.init(title: NSLocalizedString("Dismiss", comment: "Dismiss"), style: .cancel, handler: nil)) @@ -413,7 +413,7 @@ extension WebViewController: WKNavigationDelegate { decisionHandler(.cancel) if UIApplication.shared.canOpenURL(url) { - UIApplication.shared.open(url, options: [.universalLinksOnly : false], completionHandler: nil) + UIApplication.shared.open(url, options: [.universalLinksOnly: false], completionHandler: nil) } } else { @@ -530,7 +530,7 @@ private extension WebViewController { return } - coordinator.webViewProvider.dequeueWebView() { webView in + coordinator.webViewProvider.dequeueWebView { webView in webView.ready { @@ -658,7 +658,7 @@ private extension WebViewController { guard let imageURL = URL(string: clickMessage.imageURL) else { return } - Downloader.shared.download(imageURL) { [weak self] data, response, error in + Downloader.shared.download(imageURL) { [weak self] data, _, error in guard let self, let data, error == nil, !data.isEmpty, let image = UIImage(data: data) else { return @@ -751,7 +751,7 @@ private extension WebViewController { func prevArticleAction() -> UIAction? { guard coordinator.isPrevArticleAvailable else { return nil } let title = NSLocalizedString("Previous Article", comment: "Previous Article") - return UIAction(title: title, image: Assets.Images.prevArticle) { [weak self] action in + return UIAction(title: title, image: Assets.Images.prevArticle) { [weak self] _ in self?.coordinator.selectPrevArticle() } } @@ -759,7 +759,7 @@ private extension WebViewController { func nextArticleAction() -> UIAction? { guard coordinator.isNextArticleAvailable else { return nil } let title = NSLocalizedString("Next Article", comment: "Next Article") - return UIAction(title: title, image: Assets.Images.nextArticle) { [weak self] action in + return UIAction(title: title, image: Assets.Images.nextArticle) { [weak self] _ in self?.coordinator.selectNextArticle() } } @@ -769,7 +769,7 @@ private extension WebViewController { let title = article.status.read ? NSLocalizedString("Mark as Unread", comment: "Mark as Unread") : NSLocalizedString("Mark as Read", comment: "Mark as Read") let readImage = article.status.read ? Assets.Images.circleClosed : Assets.Images.circleOpen - return UIAction(title: title, image: readImage) { [weak self] action in + return UIAction(title: title, image: readImage) { [weak self] _ in self?.coordinator.toggleReadForCurrentArticle() } } @@ -778,7 +778,7 @@ private extension WebViewController { let starred = article?.status.starred ?? false let title = starred ? NSLocalizedString("Mark as Unstarred", comment: "Mark as Unstarred") : NSLocalizedString("Mark as Starred", comment: "Mark as Starred") let starredImage = starred ? Assets.Images.starOpen : Assets.Images.starClosed - return UIAction(title: title, image: starredImage) { [weak self] action in + return UIAction(title: title, image: starredImage) { [weak self] _ in self?.coordinator.toggleStarredForCurrentArticle() } } @@ -786,7 +786,7 @@ private extension WebViewController { func nextUnreadArticleAction() -> UIAction? { guard coordinator.isAnyUnreadAvailable else { return nil } let title = NSLocalizedString("Next Unread Article", comment: "Next Unread Article") - return UIAction(title: title, image: Assets.Images.nextUnread) { [weak self] action in + return UIAction(title: title, image: Assets.Images.nextUnread) { [weak self] _ in self?.coordinator.selectNextUnread() } } @@ -795,14 +795,14 @@ private extension WebViewController { let extracted = articleExtractorButtonState == .on let title = extracted ? NSLocalizedString("Show Feed Article", comment: "Show Feed Article") : NSLocalizedString("Show Reader View", comment: "Show Reader View") let extractorImage = extracted ? Assets.Images.articleExtractorOffSF : Assets.Images.articleExtractorOnSF - return UIAction(title: title, image: extractorImage) { [weak self] action in + return UIAction(title: title, image: extractorImage) { [weak self] _ in self?.toggleArticleExtractor() } } func shareAction() -> UIAction { let title = NSLocalizedString("Share", comment: "Share") - return UIAction(title: title, image: Assets.Images.share) { [weak self] action in + return UIAction(title: title, image: Assets.Images.share) { [weak self] _ in self?.showActivityDialog() } } @@ -862,8 +862,7 @@ extension WebViewController { } let encoded = json.base64EncodedString() - webView?.evaluateJavaScript("updateFind(\"\(encoded)\")") { - (result, error) in + webView?.evaluateJavaScript("updateFind(\"\(encoded)\")") { (result, error) in guard error == nil, let b64 = result as? String, let rawData = Data(base64Encoded: b64), diff --git a/iOS/Article/WebViewProvider.swift b/iOS/Article/WebViewProvider.swift index 5e038fbbf..25b5eab92 100644 --- a/iOS/Article/WebViewProvider.swift +++ b/iOS/Article/WebViewProvider.swift @@ -27,7 +27,7 @@ import WebKit operationQueue.add(WebViewProviderReplenishQueueOperation(queue: queue, articleIconSchemeHandler: articleIconSchemeHandler)) } - func dequeueWebView(completion: @escaping (PreloadedWebView) -> ()) { + func dequeueWebView(completion: @escaping (PreloadedWebView) -> Void) { operationQueue.add(WebViewProviderDequeueOperation(queue: queue, articleIconSchemeHandler: articleIconSchemeHandler, completion: completion)) operationQueue.add(WebViewProviderReplenishQueueOperation(queue: queue, articleIconSchemeHandler: articleIconSchemeHandler)) } @@ -58,9 +58,9 @@ final class WebViewProviderReplenishQueueOperation: MainThreadOperation, @unchec final class WebViewProviderDequeueOperation: MainThreadOperation, @unchecked Sendable { private var queue: NSMutableArray private var articleIconSchemeHandler: ArticleIconSchemeHandler - private var completion: (PreloadedWebView) -> () + private var completion: (PreloadedWebView) -> Void - init(queue: NSMutableArray, articleIconSchemeHandler: ArticleIconSchemeHandler, completion: @escaping (PreloadedWebView) -> ()) { + init(queue: NSMutableArray, articleIconSchemeHandler: ArticleIconSchemeHandler, completion: @escaping (PreloadedWebView) -> Void) { self.queue = queue self.articleIconSchemeHandler = articleIconSchemeHandler self.completion = completion diff --git a/iOS/ErrorHandler.swift b/iOS/ErrorHandler.swift index 7b6afbf6e..10f8517d4 100644 --- a/iOS/ErrorHandler.swift +++ b/iOS/ErrorHandler.swift @@ -14,7 +14,7 @@ struct ErrorHandler: Sendable { private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "ErrorHandler") - @Sendable public static func present(_ viewController: UIViewController) -> @Sendable (Error) -> () { + @Sendable public static func present(_ viewController: UIViewController) -> @Sendable (Error) -> Void { return { [weak viewController] error in Task { @MainActor in if UIApplication.shared.applicationState == .active { diff --git a/iOS/HidingReadArticlesState.swift b/iOS/HidingReadArticlesState.swift index 25e6b07c3..67a0b1aad 100644 --- a/iOS/HidingReadArticlesState.swift +++ b/iOS/HidingReadArticlesState.swift @@ -19,7 +19,7 @@ import Account feedsHidingReadArticles = stateRestorationInfo.feedsHidingReadArticles foldersShowingReadArticles = stateRestorationInfo.foldersShowingReadArticles } - + func save() { saveSmartFeedsHidingReadArticles() saveFeedsHidingReadArticles() @@ -28,7 +28,7 @@ import Account func toggleHidingReadArticles(for sidebarItemID: SidebarItemIdentifier) { assert(canToggleHidingReadArticles(for: sidebarItemID)) - if (!canToggleHidingReadArticles(for: sidebarItemID)) { + if !canToggleHidingReadArticles(for: sidebarItemID) { return } diff --git a/iOS/IconView.swift b/iOS/IconView.swift index 11ea4f64d..ef18e6496 100644 --- a/iOS/IconView.swift +++ b/iOS/IconView.swift @@ -12,7 +12,7 @@ import RSCore @IBDesignable final class IconView: UIView { - var iconImage: IconImage? = nil { + var iconImage: IconImage? { didSet { guard iconImage !== oldValue else { return @@ -21,8 +21,7 @@ final class IconView: UIView { if traitCollection.userInterfaceStyle == .dark { let isDark = iconImage?.isDark ?? false isDiscernable = !isDark - } - else { + } else { let isBright = iconImage?.isBright ?? false isDiscernable = !isBright } @@ -99,8 +98,7 @@ private extension IconView { } let offset = floor((viewSize.height - imageSize.height) / 2.0) return CGRect(x: offset, y: offset, width: imageSize.width, height: imageSize.height) - } - else if imageSize.height > imageSize.width { + } else if imageSize.height > imageSize.width { let factor = viewSize.height / imageSize.height let width = imageSize.width * factor let originX = floor((viewSize.width - width) / 2.0) @@ -122,4 +120,3 @@ private extension IconView { } } } - diff --git a/iOS/Inspector/FeedInspectorViewController.swift b/iOS/Inspector/FeedInspectorViewController.swift index 47cb1cc58..89a035624 100644 --- a/iOS/Inspector/FeedInspectorViewController.swift +++ b/iOS/Inspector/FeedInspectorViewController.swift @@ -84,7 +84,7 @@ final class FeedInspectorViewController: UITableViewController { } else if authorizationStatus == .authorized { feed.isNotifyAboutNewArticles = notifyAboutNewArticlesSwitch.isOn } else { - UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert]) { (granted, error) in + UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert]) { granted, _ in Task { @MainActor in self.updateNotificationSettings() if granted { @@ -122,8 +122,6 @@ final class FeedInspectorViewController: UITableViewController { } return section } - - } // MARK: Table View @@ -214,7 +212,7 @@ extension FeedInspectorViewController { func notificationUpdateErrorAlert() -> UIAlertController { let alert = UIAlertController(title: NSLocalizedString("Enable Notifications", comment: "Notifications"), message: NSLocalizedString("Notifications need to be enabled in the Settings app.", comment: "Notifications need to be enabled in the Settings app."), preferredStyle: .alert) - let openSettings = UIAlertAction(title: NSLocalizedString("Open Settings", comment: "Open Settings"), style: .default) { (action) in + let openSettings = UIAlertAction(title: NSLocalizedString("Open Settings", comment: "Open Settings"), style: .default) { _ in UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!, options: [UIApplication.OpenExternalURLOptionsKey.universalLinksOnly: false], completionHandler: nil) } let dismiss = UIAlertAction(title: NSLocalizedString("Dismiss", comment: "Dismiss"), style: .cancel, handler: nil) diff --git a/iOS/KeyboardManager.swift b/iOS/KeyboardManager.swift index 32c948109..96bbbdd6a 100644 --- a/iOS/KeyboardManager.swift +++ b/iOS/KeyboardManager.swift @@ -42,7 +42,7 @@ enum KeyboardType: String, Sendable { let specificFile = Bundle.main.path(forResource: type.rawValue, ofType: "plist")! let specificEntries = NSArray(contentsOfFile: specificFile)! as! [[String: Any]] - _keyCommands.append(contentsOf: specificEntries.compactMap { KeyboardManager.createKeyCommand(keyEntry: $0) } ) + _keyCommands.append(contentsOf: specificEntries.compactMap { KeyboardManager.createKeyCommand(keyEntry: $0) }) } static func createKeyCommand(title: String, action: String, input: String, modifiers: UIKeyModifierFlags) -> UIKeyCommand { @@ -74,9 +74,11 @@ private extension KeyboardManager { } static func createKeyCommandInput(keyEntry: [String: Any]) -> String? { - guard let key = keyEntry["key"] as? String else { return nil } + guard let key = keyEntry["key"] as? String else { + return nil + } - switch(key) { + switch key { case "[space]": return "\u{0020}" case "[uparrow]": diff --git a/iOS/MainFeed/Collection View Cells/MainFeedCollectionHeaderReusableView.swift b/iOS/MainFeed/Collection View Cells/MainFeedCollectionHeaderReusableView.swift index 6dba0814b..14b360fab 100644 --- a/iOS/MainFeed/Collection View Cells/MainFeedCollectionHeaderReusableView.swift +++ b/iOS/MainFeed/Collection View Cells/MainFeedCollectionHeaderReusableView.swift @@ -22,7 +22,6 @@ final class MainFeedCollectionHeaderReusableView: UICollectionReusableView { private var unreadLabelWidthConstraint: NSLayoutConstraint? override var accessibilityLabel: String? { - set {} get { if unreadCount > 0 { let unreadLabel = NSLocalizedString("unread", comment: "Unread label for accessibility") @@ -31,16 +30,14 @@ final class MainFeedCollectionHeaderReusableView: UICollectionReusableView { return "\(headerTitle.text ?? "") \(expandedStateMessage) " } } + set {} } private var expandedStateMessage: String { - set {} - get { - if disclosureExpanded { - return NSLocalizedString("Expanded", comment: "Disclosure button expanded state for accessibility") - } - return NSLocalizedString("Collapsed", comment: "Disclosure button collapsed state for accessibility") + if disclosureExpanded { + return NSLocalizedString("Expanded", comment: "Disclosure button expanded state for accessibility") } + return NSLocalizedString("Collapsed", comment: "Disclosure button collapsed state for accessibility") } private var _unreadCount: Int = 0 diff --git a/iOS/MainFeed/Collection View Cells/MainFeedCollectionViewCell.swift b/iOS/MainFeed/Collection View Cells/MainFeedCollectionViewCell.swift index 5c0e1c6dc..9f1612774 100644 --- a/iOS/MainFeed/Collection View Cells/MainFeedCollectionViewCell.swift +++ b/iOS/MainFeed/Collection View Cells/MainFeedCollectionViewCell.swift @@ -61,7 +61,6 @@ final class MainFeedCollectionViewCell: UICollectionViewCell { } override var accessibilityLabel: String? { - set {} get { if unreadCount > 0 { let unreadLabel = NSLocalizedString("unread", comment: "Unread label for accessibility") @@ -70,6 +69,7 @@ final class MainFeedCollectionViewCell: UICollectionViewCell { return (String(describing: feedTitle.text)) } } + set {} } override func awakeFromNib() { @@ -115,4 +115,3 @@ final class MainFeedCollectionViewCell: UICollectionViewCell { self.backgroundConfiguration = backgroundConfig } } - diff --git a/iOS/MainFeed/Collection View Cells/MainFeedCollectionViewFolderCell.swift b/iOS/MainFeed/Collection View Cells/MainFeedCollectionViewFolderCell.swift index 7db3bb55e..2e5d8bab7 100644 --- a/iOS/MainFeed/Collection View Cells/MainFeedCollectionViewFolderCell.swift +++ b/iOS/MainFeed/Collection View Cells/MainFeedCollectionViewFolderCell.swift @@ -98,7 +98,6 @@ class MainFeedCollectionViewFolderCell: UICollectionViewCell { } override var accessibilityLabel: String? { - set {} get { if unreadCount > 0 { let unreadLabel = NSLocalizedString("unread", comment: "Unread label for accessibility") @@ -107,6 +106,7 @@ class MainFeedCollectionViewFolderCell: UICollectionViewCell { return (String(describing: folderTitle.text)) } } + set {} } override func updateConfiguration(using state: UICellConfigurationState) { diff --git a/iOS/MainFeed/MainFeedCollectionViewController+Drop.swift b/iOS/MainFeed/MainFeedCollectionViewController+Drop.swift index 72e51d2d9..24d9fa219 100644 --- a/iOS/MainFeed/MainFeedCollectionViewController+Drop.swift +++ b/iOS/MainFeed/MainFeedCollectionViewController+Drop.swift @@ -71,7 +71,7 @@ extension MainFeedCollectionViewController: UICollectionViewDropDelegate { func collectionView(_ collectionView: UICollectionView, dropSessionDidUpdate session: any UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UICollectionViewDropProposal { - guard let destIndexPath = destinationIndexPath, destIndexPath.section > 0, collectionView.hasActiveDrag else { + guard let destIndexPath = destinationIndexPath, destIndexPath.section > 0, collectionView.hasActiveDrag else { return UICollectionViewDropProposal(operation: .forbidden) } diff --git a/iOS/MainFeed/MainFeedCollectionViewController.swift b/iOS/MainFeed/MainFeedCollectionViewController.swift index 3760e8d60..42e853946 100644 --- a/iOS/MainFeed/MainFeedCollectionViewController.swift +++ b/iOS/MainFeed/MainFeedCollectionViewController.swift @@ -83,7 +83,7 @@ final class MainFeedCollectionViewController: UICollectionViewController, Undoab /// /// `shouldSelectItemAt()` will not allow selection when `isAnimating` /// is `true.` - if let _ = collectionView.indexPathsForSelectedItems { + if collectionView.indexPathsForSelectedItems != nil { isAnimating = true } } @@ -95,7 +95,7 @@ final class MainFeedCollectionViewController: UICollectionViewController, Undoab /// On iPhone, once the deselection animation has completed, set `isAnimating` /// to false and this will allow selection. if traitCollection.userInterfaceIdiom == .phone { - if let _ = collectionView.indexPathsForSelectedItems { + if collectionView.indexPathsForSelectedItems != nil { coordinator.selectFeed(indexPath: nil, animations: [.select]) DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: { self.isAnimating = false @@ -130,7 +130,7 @@ final class MainFeedCollectionViewController: UICollectionViewController, Undoab // Set up the delete action let deleteTitle = NSLocalizedString("Delete", comment: "Delete") - let deleteAction = UIContextualAction(style: .destructive, title: nil) { [weak self] (action, view, completion) in + let deleteAction = UIContextualAction(style: .destructive, title: nil) { [weak self] _, _, completion in self?.delete(indexPath: indexPath) completion(true) } @@ -141,7 +141,7 @@ final class MainFeedCollectionViewController: UICollectionViewController, Undoab // Set up the rename action let renameTitle = NSLocalizedString("Rename", comment: "Rename") - let renameAction = UIContextualAction(style: .normal, title: nil) { [weak self] (action, view, completion) in + let renameAction = UIContextualAction(style: .normal, title: nil) { [weak self] _, _, completion in self?.rename(indexPath: indexPath) completion(true) } @@ -233,7 +233,7 @@ final class MainFeedCollectionViewController: UICollectionViewController, Undoab } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { - guard let node = coordinator.nodeFor(indexPath), let _ = node.representedObject as? Folder else { + guard let node = coordinator.nodeFor(indexPath), node.representedObject is Folder else { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as? MainFeedCollectionViewCell configure(cell!, indexPath: indexPath) return cell! @@ -324,7 +324,7 @@ final class MainFeedCollectionViewController: UICollectionViewController, Undoab return makeFeedContextMenu(indexPath: indexPath, includeDeleteRename: true) } else if sidebarItem is Folder { return makeFolderContextMenu(indexPath: indexPath) - } else if sidebarItem is PseudoFeed { + } else if sidebarItem is PseudoFeed { return makePseudoFeedContextMenu(indexPath: indexPath) } else { return nil @@ -516,7 +516,7 @@ final class MainFeedCollectionViewController: UICollectionViewController, Undoab } func configureCellsForRepresentedObject(_ representedObject: AnyObject) { - //applyToCellsForRepresentedObject(representedObject, configure) + // applyToCellsForRepresentedObject(representedObject, configure) } func applyToCellsForRepresentedObject(_ representedObject: AnyObject, _ completion: (MainFeedCollectionViewCell, IndexPath) -> Void) { @@ -546,7 +546,7 @@ final class MainFeedCollectionViewController: UICollectionViewController, Undoab func configure(_ cell: MainFeedCollectionViewCell, indexPath: IndexPath) { guard let node = coordinator.nodeFor(indexPath) else { return } var indentationLevel = 0 - if let _ = node.parent?.representedObject as? Folder { + if node.parent?.representedObject is Folder { indentationLevel = 1 } @@ -779,7 +779,7 @@ extension MainFeedCollectionViewController: UIContextMenuInteractionDelegate { return nil } - return UIContextMenuConfiguration(identifier: sectionIndex as NSCopying, previewProvider: nil) { suggestedActions in + return UIContextMenuConfiguration(identifier: sectionIndex as NSCopying, previewProvider: nil) { _ in var menuElements = [UIMenuElement]() menuElements.append(UIMenu(title: "", options: .displayInline, children: [self.getAccountInfoAction(account: account)])) @@ -806,7 +806,7 @@ extension MainFeedCollectionViewController: UIContextMenuInteractionDelegate { extension MainFeedCollectionViewController { func makeFeedContextMenu(indexPath: IndexPath, includeDeleteRename: Bool) -> UIContextMenuConfiguration { - return UIContextMenuConfiguration(identifier: MainFeedRowIdentifier(indexPath: indexPath), previewProvider: nil, actionProvider: { [ weak self] suggestedActions in + return UIContextMenuConfiguration(identifier: MainFeedRowIdentifier(indexPath: indexPath), previewProvider: nil, actionProvider: { [ weak self] _ in guard let self = self else { return nil } @@ -849,7 +849,7 @@ extension MainFeedCollectionViewController { } func makeFolderContextMenu(indexPath: IndexPath) -> UIContextMenuConfiguration { - return UIContextMenuConfiguration(identifier: MainFeedRowIdentifier(indexPath: indexPath), previewProvider: nil, actionProvider: { [weak self] suggestedActions in + return UIContextMenuConfiguration(identifier: MainFeedRowIdentifier(indexPath: indexPath), previewProvider: nil, actionProvider: { [weak self] _ in guard let self = self else { return nil } @@ -876,7 +876,7 @@ extension MainFeedCollectionViewController { return nil } - return UIContextMenuConfiguration(identifier: MainFeedRowIdentifier(indexPath: indexPath), previewProvider: nil, actionProvider: { suggestedActions in + return UIContextMenuConfiguration(identifier: MainFeedRowIdentifier(indexPath: indexPath), previewProvider: nil, actionProvider: { _ in return UIMenu(title: "", children: [markAllAction]) }) } @@ -887,7 +887,7 @@ extension MainFeedCollectionViewController { } let title = NSLocalizedString("Open Home Page", comment: "Open Home Page") - let action = UIAction(title: title, image: Assets.Images.safari) { [weak self] action in + let action = UIAction(title: title, image: Assets.Images.safari) { [weak self] _ in self?.coordinator.showBrowserForFeed(indexPath) } return action @@ -899,7 +899,7 @@ extension MainFeedCollectionViewController { } let title = NSLocalizedString("Open Home Page", comment: "Open Home Page") - let action = UIAlertAction(title: title, style: .default) { [weak self] action in + let action = UIAlertAction(title: title, style: .default) { [weak self] _ in self?.coordinator.showBrowserForFeed(indexPath) completion(true) } @@ -913,7 +913,7 @@ extension MainFeedCollectionViewController { } let title = NSLocalizedString("Copy Feed URL", comment: "Copy Feed URL") - let action = UIAction(title: title, image: Assets.Images.copy) { action in + let action = UIAction(title: title, image: Assets.Images.copy) { _ in UIPasteboard.general.url = url } return action @@ -926,7 +926,7 @@ extension MainFeedCollectionViewController { } let title = NSLocalizedString("Copy Feed URL", comment: "Copy Feed URL") - let action = UIAlertAction(title: title, style: .default) { action in + let action = UIAlertAction(title: title, style: .default) { _ in UIPasteboard.general.url = url completion(true) } @@ -941,7 +941,7 @@ extension MainFeedCollectionViewController { } let title = NSLocalizedString("Copy Home Page URL", comment: "Copy Home Page URL") - let action = UIAction(title: title, image: Assets.Images.copy) { action in + let action = UIAction(title: title, image: Assets.Images.copy) { _ in UIPasteboard.general.url = url } return action @@ -955,7 +955,7 @@ extension MainFeedCollectionViewController { } let title = NSLocalizedString("Copy Home Page URL", comment: "Copy Home Page URL") - let action = UIAlertAction(title: title, style: .default) { action in + let action = UIAlertAction(title: title, style: .default) { _ in UIPasteboard.general.url = url completion(true) } @@ -975,7 +975,7 @@ extension MainFeedCollectionViewController { completion(true) } - let action = UIAlertAction(title: title, style: .default) { [weak self] action in + let action = UIAlertAction(title: title, style: .default) { [weak self] _ in MarkAsReadAlertController.confirm(self, coordinator: self?.coordinator, confirmTitle: title, sourceType: contentView, cancelCompletion: cancel) { [weak self] in self?.coordinator.markAllAsRead(Array(articles)) completion(true) @@ -987,7 +987,7 @@ extension MainFeedCollectionViewController { func deleteAction(indexPath: IndexPath) -> UIAction { let title = NSLocalizedString("Delete", comment: "Delete") - let action = UIAction(title: title, image: Assets.Images.trash, attributes: .destructive) { [weak self] action in + let action = UIAction(title: title, image: Assets.Images.trash, attributes: .destructive) { [weak self] _ in self?.delete(indexPath: indexPath) } return action @@ -995,7 +995,7 @@ extension MainFeedCollectionViewController { func renameAction(indexPath: IndexPath) -> UIAction { let title = NSLocalizedString("Rename", comment: "Rename") - let action = UIAction(title: title, image: Assets.Images.edit) { [weak self] action in + let action = UIAction(title: title, image: Assets.Images.edit) { [weak self] _ in self?.rename(indexPath: indexPath) } return action @@ -1007,7 +1007,7 @@ extension MainFeedCollectionViewController { } let title = NSLocalizedString("Get Info", comment: "Get Info") - let action = UIAction(title: title, image: Assets.Images.info) { [weak self] action in + let action = UIAction(title: title, image: Assets.Images.info) { [weak self] _ in self?.coordinator.showFeedInspector(for: feed) } return action @@ -1015,7 +1015,7 @@ extension MainFeedCollectionViewController { func getAccountInfoAction(account: Account) -> UIAction { let title = NSLocalizedString("Get Info", comment: "Get Info") - let action = UIAction(title: title, image: Assets.Images.info) { [weak self] action in + let action = UIAction(title: title, image: Assets.Images.info) { [weak self] _ in self?.coordinator.showAccountInspector(for: account) } return action @@ -1023,7 +1023,7 @@ extension MainFeedCollectionViewController { func deactivateAccountAction(account: Account) -> UIAction { let title = NSLocalizedString("Deactivate", comment: "Deactivate") - let action = UIAction(title: title, image: Assets.Images.deactivate) { action in + let action = UIAction(title: title, image: Assets.Images.deactivate) { _ in account.isActive = false } return action @@ -1035,7 +1035,7 @@ extension MainFeedCollectionViewController { } let title = NSLocalizedString("Get Info", comment: "Get Info") - let action = UIAlertAction(title: title, style: .default) { [weak self] action in + let action = UIAlertAction(title: title, style: .default) { [weak self] _ in self?.coordinator.showFeedInspector(for: feed) completion(true) } @@ -1051,7 +1051,7 @@ extension MainFeedCollectionViewController { let localizedMenuText = NSLocalizedString("Mark All as Read in “%@”", comment: "Command") let title = NSString.localizedStringWithFormat(localizedMenuText as NSString, sidebarItem.nameForDisplay) as String - let action = UIAction(title: title, image: Assets.Images.markAllAsRead) { [weak self] action in + let action = UIAction(title: title, image: Assets.Images.markAllAsRead) { [weak self] _ in MarkAsReadAlertController.confirm(self, coordinator: self?.coordinator, confirmTitle: title, sourceType: contentView) { [weak self] in if let articles = try? sidebarItem.fetchUnreadArticles() { self?.coordinator.markAllAsRead(Array(articles)) @@ -1063,13 +1063,13 @@ extension MainFeedCollectionViewController { } func markAllAsReadAction(account: Account, contentView: UIView?) -> UIAction? { - guard account.unreadCount > 0, let contentView = contentView else { + guard account.unreadCount > 0, let contentView else { return nil } let localizedMenuText = NSLocalizedString("Mark All as Read in “%@”", comment: "Command") let title = NSString.localizedStringWithFormat(localizedMenuText as NSString, account.nameForDisplay) as String - let action = UIAction(title: title, image: Assets.Images.markAllAsRead) { [weak self] action in + let action = UIAction(title: title, image: Assets.Images.markAllAsRead) { [weak self] _ in MarkAsReadAlertController.confirm(self, coordinator: self?.coordinator, confirmTitle: title, sourceType: contentView) { [weak self] in // If you don't have this delay the screen flashes when it executes this code DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { @@ -1095,7 +1095,7 @@ extension MainFeedCollectionViewController { alertController.addAction(UIAlertAction(title: cancelTitle, style: .cancel)) let renameTitle = NSLocalizedString("Rename", comment: "Rename") - let renameAction = UIAlertAction(title: renameTitle, style: .default) { [weak self] action in + let renameAction = UIAlertAction(title: renameTitle, style: .default) { [weak self] _ in guard let name = alertController.textFields?[0].text, !name.isEmpty else { return @@ -1126,7 +1126,7 @@ extension MainFeedCollectionViewController { alertController.addAction(renameAction) alertController.preferredAction = renameAction - alertController.addTextField() { textField in + alertController.addTextField { textField in textField.text = sidebarItem.nameForDisplay textField.placeholder = NSLocalizedString("Name", comment: "Name") textField.clearButtonMode = .always @@ -1147,7 +1147,7 @@ extension MainFeedCollectionViewController { title = NSLocalizedString("Delete Folder", comment: "Delete folder") let localizedInformativeText = NSLocalizedString("Are you sure you want to delete the “%@” folder?", comment: "Folder delete text") message = NSString.localizedStringWithFormat(localizedInformativeText as NSString, sidebarItem.nameForDisplay) as String - } else { + } else { title = NSLocalizedString("Delete Feed", comment: "Delete feed") let localizedInformativeText = NSLocalizedString("Are you sure you want to delete the “%@” feed?", comment: "Feed delete text") message = NSString.localizedStringWithFormat(localizedInformativeText as NSString, sidebarItem.nameForDisplay) as String @@ -1159,7 +1159,7 @@ extension MainFeedCollectionViewController { alertController.addAction(UIAlertAction(title: cancelTitle, style: .cancel)) let deleteTitle = NSLocalizedString("Delete", comment: "Delete") - let deleteAction = UIAlertAction(title: deleteTitle, style: .destructive) { [weak self] action in + let deleteAction = UIAlertAction(title: deleteTitle, style: .destructive) { [weak self] _ in self?.performDelete(indexPath: indexPath) } alertController.addAction(deleteAction) diff --git a/iOS/MainFeed/RefreshProgressView.swift b/iOS/MainFeed/RefreshProgressView.swift index 6b2e25693..716820b16 100644 --- a/iOS/MainFeed/RefreshProgressView.swift +++ b/iOS/MainFeed/RefreshProgressView.swift @@ -15,12 +15,11 @@ final class RefreshProgressView: UIView { override func awakeFromNib() { MainActor.assumeIsolated { - NotificationCenter.default.addObserver(self, selector: #selector(progressDidChange(_:)), name: .combinedRefreshProgressDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(contentSizeCategoryDidChange(_:)), name: UIContentSizeCategory.didChangeNotification, object: nil) update() scheduleUpdateRefreshLabel() - + isAccessibilityElement = true accessibilityTraits = [.updatesFrequently, .notEnabled] } diff --git a/iOS/MainFeed/ShadowTableChanges.swift b/iOS/MainFeed/ShadowTableChanges.swift index ad5e9a73f..eb42aa4f4 100644 --- a/iOS/MainFeed/ShadowTableChanges.swift +++ b/iOS/MainFeed/ShadowTableChanges.swift @@ -66,10 +66,4 @@ struct ShadowTableChanges { var moves: Set? var rowChanges: [RowChanges]? - init(deletes: Set?, inserts: Set?, moves: Set?, rowChanges: [RowChanges]?) { - self.deletes = deletes - self.inserts = inserts - self.moves = moves - self.rowChanges = rowChanges - } } diff --git a/iOS/MainTimeline/Cells/MainTimelineCellData.swift b/iOS/MainTimeline/Cells/MainTimelineCellData.swift index 6a4fbf63f..aef136ef2 100644 --- a/iOS/MainTimeline/Cells/MainTimelineCellData.swift +++ b/iOS/MainTimeline/Cells/MainTimelineCellData.swift @@ -43,8 +43,7 @@ import Articles if let feedName = feedName { self.feedName = ArticleStringFormatter.truncatedFeedName(feedName) - } - else { + } else { self.feedName = "" } @@ -66,7 +65,7 @@ import Articles } - init() { //Empty + init() { // Empty self.title = "" self.attributedTitle = NSAttributedString() self.summary = "" diff --git a/iOS/MainTimeline/Cells/MainTimelineFeedCell.swift b/iOS/MainTimeline/Cells/MainTimelineFeedCell.swift index e2d65d018..1151fc521 100644 --- a/iOS/MainTimeline/Cells/MainTimelineFeedCell.swift +++ b/iOS/MainTimeline/Cells/MainTimelineFeedCell.swift @@ -100,8 +100,8 @@ class MainTimelineFeedCell: UITableViewCell { .font: UIFont.preferredFont(forTextStyle: .headline), .paragraphStyle: paragraphStyle, .foregroundColor: isSelected ? UIColor.white : UIColor.label - ] - let titleWithNewline = cellData.title + (cellData.summary != "" ? "\n" : "" ) + ] + let titleWithNewline = cellData.title + (cellData.summary != "" ? "\n" : "" ) let titleAttributed = NSAttributedString(string: titleWithNewline, attributes: titleAttributes) attributedCellText.append(titleAttributed) } diff --git a/iOS/MainTimeline/Cells/MainTimelineIconFeedCell.swift b/iOS/MainTimeline/Cells/MainTimelineIconFeedCell.swift index 17334af29..ff2d45bce 100644 --- a/iOS/MainTimeline/Cells/MainTimelineIconFeedCell.swift +++ b/iOS/MainTimeline/Cells/MainTimelineIconFeedCell.swift @@ -127,7 +127,7 @@ class MainTimelineIconFeedCell: UITableViewCell { .paragraphStyle: paragraphStyle, .foregroundColor: isSelected ? UIColor.white : UIColor.label ] - let titleWithNewline = cellData.title + (cellData.summary != "" ? "\n" : "" ) + let titleWithNewline = cellData.title + (cellData.summary != "" ? "\n" : "" ) let titleAttributed = NSAttributedString(string: titleWithNewline, attributes: titleAttributes) attributedCellText.append(titleAttributed) } diff --git a/iOS/MainTimeline/MainTimelineViewController.swift b/iOS/MainTimeline/MainTimelineViewController.swift index c24be2fa5..3f540b61e 100644 --- a/iOS/MainTimeline/MainTimelineViewController.swift +++ b/iOS/MainTimeline/MainTimelineViewController.swift @@ -217,7 +217,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu if navigationController?.navigationBar.isHidden ?? false { navigationController?.navigationBar.alpha = 0 } - //navigationItem.subtitle = "" // don't inherit feeds subtitle on push + // navigationItem.subtitle = "" // don't inherit feeds subtitle on push updateNavigationBarTitle(coordinator?.timelineFeed?.nameForDisplay ?? "") coordinator?.updateNavigationBarSubtitles(nil) } @@ -231,7 +231,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu } } if traitCollection.userInterfaceIdiom == .phone { - if let _ = coordinator?.currentArticle { + if coordinator?.currentArticle != nil { if let indexPath = tableView.indexPathForSelectedRow { tableView.deselectRow(at: indexPath, animated: true) } @@ -262,7 +262,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu coordinator?.markAllAsReadInTimeline() } - @IBAction func markAllAsRead(_ sender: Any) { + @IBAction func markAllAsRead(_ sender: Any?) { let title = NSLocalizedString("Mark All as Read", comment: "Mark All as Read") if let source = sender as? UIBarButtonItem { @@ -271,7 +271,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu } } - if let _ = sender as? UIKeyCommand { + if sender is UIKeyCommand { guard let indexPath = tableView.indexPathForSelectedRow, let contentView = tableView.cellForRow(at: indexPath)?.contentView else { return } @@ -402,7 +402,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu NSLocalizedString("Mark as Unread", comment: "Mark as Unread") : NSLocalizedString("Mark as Read", comment: "Mark as Read") - let readAction = UIContextualAction(style: .normal, title: readTitle) { [weak self] (action, view, completion) in + let readAction = UIContextualAction(style: .normal, title: readTitle) { [weak self] _, _, completion in self?.toggleRead(article) completion(true) } @@ -422,7 +422,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu NSLocalizedString("Unstar", comment: "Unstar") : NSLocalizedString("Star", comment: "Star") - let starAction = UIContextualAction(style: .normal, title: starTitle) { [weak self] (action, view, completion) in + let starAction = UIContextualAction(style: .normal, title: starTitle) { [weak self] _, _, completion in self?.toggleStar(article) completion(true) } @@ -488,7 +488,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu guard let article = dataSource.itemIdentifier(for: indexPath) else { return nil } - return UIContextMenuConfiguration(identifier: indexPath.row as NSCopying, previewProvider: nil, actionProvider: { [weak self] suggestedActions in + return UIContextMenuConfiguration(identifier: indexPath.row as NSCopying, previewProvider: nil, actionProvider: { [weak self] _ in guard let self = self else { return nil } @@ -855,7 +855,7 @@ private extension MainTimelineViewController { NSLocalizedString("Mark as Read", comment: "Mark as Read") let image = article.status.read ? Assets.Images.circleClosed : Assets.Images.circleOpen - let action = UIAction(title: title, image: image) { [weak self] action in + let action = UIAction(title: title, image: image) { [weak self] _ in self?.toggleRead(article) } @@ -874,7 +874,7 @@ private extension MainTimelineViewController { NSLocalizedString("Mark as Starred", comment: "Mark as Starred") let image = article.status.starred ? Assets.Images.starOpen : Assets.Images.starClosed - let action = UIAction(title: title, image: image) { [weak self] action in + let action = UIAction(title: title, image: image) { [weak self] _ in self?.toggleStar(article) } @@ -898,7 +898,7 @@ private extension MainTimelineViewController { let title = NSLocalizedString("Mark Above as Read", comment: "Mark Above as Read") let image = Assets.Images.markAboveAsRead - let action = UIAction(title: title, image: image) { [weak self] action in + let action = UIAction(title: title, image: image) { [weak self] _ in MarkAsReadAlertController.confirm(self, coordinator: self?.coordinator, confirmTitle: title, sourceType: contentView) { [weak self] in self?.markAboveAsRead(article) } @@ -923,7 +923,7 @@ private extension MainTimelineViewController { let title = NSLocalizedString("Mark Below as Read", comment: "Mark Below as Read") let image = Assets.Images.markBelowAsRead - let action = UIAction(title: title, image: image) { [weak self] action in + let action = UIAction(title: title, image: image) { [weak self] _ in MarkAsReadAlertController.confirm(self, coordinator: self?.coordinator, confirmTitle: title, sourceType: contentView) { [weak self] in self?.markBelowAsRead(article) } @@ -941,7 +941,7 @@ private extension MainTimelineViewController { completion(true) } - let action = UIAlertAction(title: title, style: .default) { [weak self] action in + let action = UIAlertAction(title: title, style: .default) { [weak self] _ in MarkAsReadAlertController.confirm(self, coordinator: self?.coordinator, confirmTitle: title, sourceType: contentView, cancelCompletion: cancel) { [weak self] in self?.markAboveAsRead(article) completion(true) @@ -960,7 +960,7 @@ private extension MainTimelineViewController { completion(true) } - let action = UIAlertAction(title: title, style: .default) { [weak self] action in + let action = UIAlertAction(title: title, style: .default) { [weak self] _ in MarkAsReadAlertController.confirm(self, coordinator: self?.coordinator, confirmTitle: title, sourceType: contentView, cancelCompletion: cancel) { [weak self] in self?.markBelowAsRead(article) completion(true) @@ -984,7 +984,7 @@ private extension MainTimelineViewController { !timelineFeedIsEqualTo(feed) else { return nil } let title = NSLocalizedString("Go to Feed", comment: "Go to Feed") - let action = UIAction(title: title, image: Assets.Images.openInSidebar) { [weak self] action in + let action = UIAction(title: title, image: Assets.Images.openInSidebar) { [weak self] _ in self?.discloseFeed(feed, animations: [.scroll, .navigation]) } return action @@ -995,7 +995,7 @@ private extension MainTimelineViewController { !timelineFeedIsEqualTo(feed) else { return nil } let title = NSLocalizedString("Go to Feed", comment: "Go to Feed") - let action = UIAlertAction(title: title, style: .default) { [weak self] action in + let action = UIAlertAction(title: title, style: .default) { [weak self] _ in self?.discloseFeed(feed, animations: [.scroll, .navigation]) completion(true) } @@ -1021,7 +1021,7 @@ private extension MainTimelineViewController { let localizedMenuText = NSLocalizedString("Mark All as Read in “%@”", comment: "Command") let title = NSString.localizedStringWithFormat(localizedMenuText as NSString, feed.nameForDisplay) as String - let action = UIAction(title: title, image: Assets.Images.markAllAsRead) { [weak self] action in + let action = UIAction(title: title, image: Assets.Images.markAllAsRead) { [weak self] _ in MarkAsReadAlertController.confirm(self, coordinator: self?.coordinator, confirmTitle: title, sourceType: contentView) { [weak self] in self?.markAllAsRead(articles) } @@ -1046,7 +1046,7 @@ private extension MainTimelineViewController { completion(true) } - let action = UIAlertAction(title: title, style: .default) { [weak self] action in + let action = UIAlertAction(title: title, style: .default) { [weak self] _ in MarkAsReadAlertController.confirm(self, coordinator: self?.coordinator, confirmTitle: title, sourceType: contentView, cancelCompletion: cancel) { [weak self] in self?.markAllAsRead(articles) completion(true) @@ -1058,7 +1058,7 @@ private extension MainTimelineViewController { func copyArticleURLAction(_ article: Article) -> UIAction? { guard let url = article.preferredURL else { return nil } let title = NSLocalizedString("Copy Article URL", comment: "Copy Article URL") - let action = UIAction(title: title, image: Assets.Images.copy) { action in + let action = UIAction(title: title, image: Assets.Images.copy) { _ in UIPasteboard.general.url = url } return action @@ -1067,7 +1067,7 @@ private extension MainTimelineViewController { func copyExternalURLAction(_ article: Article) -> UIAction? { guard let externalLink = article.externalLink, externalLink != article.preferredLink, let url = URL(string: externalLink) else { return nil } let title = NSLocalizedString("Copy External URL", comment: "Copy External URL") - let action = UIAction(title: title, image: Assets.Images.copy) { action in + let action = UIAction(title: title, image: Assets.Images.copy) { _ in UIPasteboard.general.url = url } return action @@ -1079,19 +1079,23 @@ private extension MainTimelineViewController { } func openInBrowserAction(_ article: Article) -> UIAction? { - guard let _ = article.preferredURL else { return nil } + guard article.preferredURL != nil else { + return nil + } let title = NSLocalizedString("Open in Browser", comment: "Open in Browser") - let action = UIAction(title: title, image: Assets.Images.safari) { [weak self] action in + let action = UIAction(title: title, image: Assets.Images.safari) { [weak self] _ in self?.showBrowserForArticle(article) } return action } func openInBrowserAlertAction(_ article: Article, completion: @escaping (Bool) -> Void) -> UIAlertAction? { - guard let _ = article.preferredURL else { return nil } + guard article.preferredURL != nil else { + return nil + } let title = NSLocalizedString("Open in Browser", comment: "Open in Browser") - let action = UIAlertAction(title: title, style: .default) { [weak self] action in + let action = UIAlertAction(title: title, style: .default) { [weak self] _ in self?.showBrowserForArticle(article) completion(true) } @@ -1101,7 +1105,9 @@ private extension MainTimelineViewController { func shareDialogForTableCell(indexPath: IndexPath, url: URL, title: String?) { let activityViewController = UIActivityViewController(url: url, title: title, applicationActivities: nil) - guard let cell = tableView.cellForRow(at: indexPath) else { return } + guard let cell = tableView.cellForRow(at: indexPath) else { + return + } let popoverController = activityViewController.popoverPresentationController popoverController?.sourceView = cell popoverController?.sourceRect = CGRect(x: 0, y: 0, width: cell.frame.size.width, height: cell.frame.size.height) @@ -1112,7 +1118,7 @@ private extension MainTimelineViewController { func shareAction(_ article: Article, indexPath: IndexPath) -> UIAction? { guard let url = article.preferredURL else { return nil } let title = NSLocalizedString("Share", comment: "Share") - let action = UIAction(title: title, image: Assets.Images.share) { [weak self] action in + let action = UIAction(title: title, image: Assets.Images.share) { [weak self] _ in self?.shareDialogForTableCell(indexPath: indexPath, url: url, title: article.title) } return action @@ -1121,7 +1127,7 @@ private extension MainTimelineViewController { func shareAlertAction(_ article: Article, indexPath: IndexPath, completion: @escaping (Bool) -> Void) -> UIAlertAction? { guard let url = article.preferredURL else { return nil } let title = NSLocalizedString("Share", comment: "Share") - let action = UIAlertAction(title: title, style: .default) { [weak self] action in + let action = UIAlertAction(title: title, style: .default) { [weak self] _ in completion(true) self?.shareDialogForTableCell(indexPath: indexPath, url: url, title: article.title) } diff --git a/iOS/MainTimeline/MarkAsReadAlertController.swift b/iOS/MainTimeline/MarkAsReadAlertController.swift index 2d89a8fb8..c6107c4da 100644 --- a/iOS/MainTimeline/MarkAsReadAlertController.swift +++ b/iOS/MainTimeline/MarkAsReadAlertController.swift @@ -17,13 +17,13 @@ extension UIBarButtonItem: MarkAsReadAlertControllerSourceType {} @MainActor struct MarkAsReadAlertController { static func confirm(_ controller: UIViewController?, - coordinator: SceneCoordinator?, - confirmTitle: String, - sourceType: T, - cancelCompletion: (() -> Void)? = nil, - completion: @escaping () -> Void) where T: MarkAsReadAlertControllerSourceType { + coordinator: SceneCoordinator?, + confirmTitle: String, + sourceType: T, + cancelCompletion: (() -> Void)? = nil, + completion: @escaping () -> Void) where T: MarkAsReadAlertControllerSourceType { - guard let controller = controller, let coordinator = coordinator else { + guard let controller, let coordinator else { completion() return } @@ -39,10 +39,10 @@ extension UIBarButtonItem: MarkAsReadAlertControllerSourceType {} } private static func alert(coordinator: SceneCoordinator, - confirmTitle: String, - cancelCompletion: (() -> Void)?, - sourceType: T, - completion: @escaping (UIAlertAction) -> Void) -> UIAlertController where T: MarkAsReadAlertControllerSourceType { + confirmTitle: String, + cancelCompletion: (() -> Void)?, + sourceType: T, + completion: @escaping (UIAlertAction) -> Void) -> UIAlertController where T: MarkAsReadAlertControllerSourceType { let title = NSLocalizedString("Mark As Read", comment: "Mark As Read") let message = NSLocalizedString("You can turn this confirmation off in Settings.", diff --git a/iOS/RootSplitViewController.swift b/iOS/RootSplitViewController.swift index ea45abc9e..1b5730fa6 100644 --- a/iOS/RootSplitViewController.swift +++ b/iOS/RootSplitViewController.swift @@ -58,7 +58,7 @@ final class RootSplitViewController: UISplitViewController { } @objc func markAllAsReadAndGoToNextUnread(_ sender: Any?) { - coordinator.markAllAsReadInTimeline() { + coordinator.markAllAsReadInTimeline { self.coordinator.selectNextUnread() } } diff --git a/iOS/SceneCoordinator.swift b/iOS/SceneCoordinator.swift index 2ed9040e2..257060226 100644 --- a/iOS/SceneCoordinator.swift +++ b/iOS/SceneCoordinator.swift @@ -454,7 +454,7 @@ struct FeedNode: Hashable, Sendable { @objc func unreadCountDidChange(_ note: Notification) { // We will handle the filtering of unread feeds in unreadCountDidInitialize after they have all be calculated guard AccountManager.shared.areUnreadCountsInitialized else { - return + return } queueRebuildBackingStores() @@ -616,7 +616,7 @@ struct FeedNode: Hashable, Sendable { self.mainFeedCollectionViewController?.navigationItem.subtitle = refreshText // If unread count > 0, add unread string to timeline - if let _ = timelineFeed, timelineUnreadCount > 0 { + if timelineFeed != nil, timelineUnreadCount > 0 { let localizedUnreadCount = NSLocalizedString("%i Unread", comment: "14 Unread") let unreadCount = NSString.localizedStringWithFormat(localizedUnreadCount as NSString, timelineUnreadCount) as String self.mainTimelineViewController?.updateNavigationBarSubtitle(unreadCount) @@ -633,7 +633,7 @@ struct FeedNode: Hashable, Sendable { self.mainFeedCollectionViewController?.navigationItem.subtitle = NSLocalizedString("Updated Just Now", comment: "Updated Just Now") // If unread count > 0, add unread string to timeline - if let _ = timelineFeed, timelineUnreadCount > 0 { + if timelineFeed != nil, timelineUnreadCount > 0 { let localizedUnreadCount = NSLocalizedString("%i Unread", comment: "14 Unread") let refreshTextWithUnreadCount = NSString.localizedStringWithFormat(localizedUnreadCount as NSString, timelineUnreadCount) as String self.mainTimelineViewController?.updateNavigationBarSubtitle(refreshTextWithUnreadCount) @@ -646,11 +646,10 @@ struct FeedNode: Hashable, Sendable { } } } - } - else { + } else { self.mainFeedCollectionViewController?.navigationItem.subtitle = "" // If unread count > 0, add unread string to timeline - if let _ = timelineFeed, timelineUnreadCount > 0 { + if timelineFeed != nil, timelineUnreadCount > 0 { let localizedUnreadCount = NSLocalizedString("%i Unread", comment: "14 Unread") let refreshTextWithUnreadCount = NSString.localizedStringWithFormat(localizedUnreadCount as NSString, timelineUnreadCount) as String self.mainTimelineViewController?.updateNavigationBarSubtitle(refreshTextWithUnreadCount) @@ -1122,7 +1121,7 @@ struct FeedNode: Hashable, Sendable { self.mainTimelineViewController?.hideSearch() } - selectNextUnreadFeed() { + selectNextUnreadFeed { self.selectNextUnreadArticleInTimeline() } } @@ -1385,8 +1384,7 @@ struct FeedNode: Hashable, Sendable { func showInAppBrowser() { if currentArticle != nil { articleViewController?.openInAppBrowser() - } - else { + } else { mainFeedCollectionViewController.openInAppBrowser() } } @@ -1421,7 +1419,7 @@ struct FeedNode: Hashable, Sendable { do { try ArticleThemeImporter.importTheme(controller: rootSplitViewController, url: URL(fileURLWithPath: filename)) } catch { - NotificationCenter.default.post(name: .didFailToImportThemeWithError, object: nil, userInfo: ["error" : error]) + NotificationCenter.default.post(name: .didFailToImportThemeWithError, object: nil, userInfo: ["error": error]) } } @@ -1551,7 +1549,7 @@ private extension SceneCoordinator { addToFilterExceptionsIfNecessary(sidebarItem) addShadowTableToFilterExceptions() - rebuildBackingStores(completion: { + rebuildBackingStores(completion: { self.treeControllerDelegate.resetFilterExceptions() completion() }) @@ -2195,9 +2193,9 @@ private extension SceneCoordinator { // MARK: NSUserActivity - func handleSelectFeed(_ userInfo: [AnyHashable : Any]?) { + func handleSelectFeed(_ userInfo: [AnyHashable: Any]?) { guard let userInfo = userInfo, - let sidebarItemIDUserInfo = userInfo[UserInfoKey.sidebarItemID] as? [String : String], + let sidebarItemIDUserInfo = userInfo[UserInfoKey.sidebarItemID] as? [String: String], let sidebarItemID = SidebarItemIdentifier(userInfo: sidebarItemIDUserInfo) else { return } @@ -2210,7 +2208,7 @@ private extension SceneCoordinator { guard let smartFeed = SmartFeedsController.shared.find(by: sidebarItemID) else { return } markExpanded(SmartFeedsController.shared) - rebuildBackingStores(initialLoad: true, completion: { + rebuildBackingStores(initialLoad: true, completion: { self.treeControllerDelegate.resetFilterExceptions() if let indexPath = self.indexPathFor(smartFeed) { self.selectFeed(indexPath: indexPath) { @@ -2227,7 +2225,7 @@ private extension SceneCoordinator { markExpanded(account) - rebuildBackingStores(initialLoad: true, completion: { + rebuildBackingStores(initialLoad: true, completion: { self.treeControllerDelegate.resetFilterExceptions() if let folderNode = self.findFolderNode(folderName: folderName, beginningAt: accountNode), let indexPath = self.indexPathFor(folderNode) { @@ -2250,10 +2248,10 @@ private extension SceneCoordinator { } } - func handleReadArticle(_ userInfo: [AnyHashable : Any]?) { + func handleReadArticle(_ userInfo: [AnyHashable: Any]?) { guard let userInfo = userInfo else { return } - guard let articlePathUserInfo = userInfo[UserInfoKey.articlePath] as? [AnyHashable : Any], + guard let articlePathUserInfo = userInfo[UserInfoKey.articlePath] as? [AnyHashable: Any], let accountID = articlePathUserInfo[ArticlePathKey.accountID] as? String, let accountName = articlePathUserInfo[ArticlePathKey.accountName] as? String, let feedID = articlePathUserInfo[ArticlePathKey.feedID] as? String, @@ -2278,7 +2276,7 @@ private extension SceneCoordinator { } } - func restoreFeedSelection(_ userInfo: [AnyHashable : Any], accountID: String, feedID: String, articleID: String) -> Bool { + func restoreFeedSelection(_ userInfo: [AnyHashable: Any], accountID: String, feedID: String, articleID: String) -> Bool { guard let sidebarItemIDUserInfo = (userInfo[UserInfoKey.sidebarItemID] ?? userInfo[UserInfoKey.feedIdentifier]) as? [String: String], let sidebarItemID = SidebarItemIdentifier(userInfo: sidebarItemIDUserInfo) else { return false diff --git a/iOS/SceneDelegate.swift b/iOS/SceneDelegate.swift index ef5d0159a..02e44b09f 100644 --- a/iOS/SceneDelegate.swift +++ b/iOS/SceneDelegate.swift @@ -43,7 +43,7 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate { NotificationCenter.default.addObserver(self, selector: #selector(handleUserInterfaceColorPaletteDidUpdate(_:)), name: .userInterfaceColorPaletteDidUpdate, object: AppDefaults.self) - if let _ = connectionOptions.urlContexts.first?.url { + if connectionOptions.urlContexts.first?.url != nil { self.scene(scene, openURLContexts: connectionOptions.urlContexts) return } @@ -136,10 +136,8 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate { if AccountManager.shared.isSuspended { AccountManager.shared.resumeAll() } - self.coordinator.selectAllUnreadFeed() { - DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: { - self.coordinator.selectArticleInCurrentFeed(id!) - }) + self.coordinator.selectAllUnreadFeed { + self.coordinator.selectArticleInCurrentFeed(id!) } } else { self.coordinator.selectAllUnreadFeed() @@ -154,10 +152,8 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate { if AccountManager.shared.isSuspended { AccountManager.shared.resumeAll() } - self.coordinator.selectTodayFeed() { - DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: { - self.coordinator.selectArticleInCurrentFeed(id!) - }) + self.coordinator.selectTodayFeed { + self.coordinator.selectArticleInCurrentFeed(id!) } } else { self.coordinator.selectTodayFeed() @@ -172,10 +168,8 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate { if AccountManager.shared.isSuspended { AccountManager.shared.resumeAll() } - self.coordinator.selectStarredFeed() { - DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: { - self.coordinator.selectArticleInCurrentFeed(id!) - }) + self.coordinator.selectStarredFeed { + self.coordinator.selectArticleInCurrentFeed(id!) } } else { self.coordinator.selectStarredFeed() @@ -202,7 +196,7 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate { DispatchQueue.main.async { NotificationCenter.default.post(name: .didBeginDownloadingTheme, object: nil) } - let task = URLSession.shared.downloadTask(with: request) { location, response, error in + let task = URLSession.shared.downloadTask(with: request) { location, _, error in guard let location = location else { return } diff --git a/iOS/Settings/AboutContributor.swift b/iOS/Settings/AboutContributor.swift new file mode 100644 index 000000000..a64b19817 --- /dev/null +++ b/iOS/Settings/AboutContributor.swift @@ -0,0 +1,69 @@ +// +// AboutContributor.swift +// NetNewsWire-iOS +// +// Created by Stuart Breckenridge on 01/01/2026. +// Copyright © 2026 Ranchero Software. All rights reserved. +// + +import Foundation + +public struct AboutContributor: Identifiable, Hashable { + public let id: UUID = UUID() + + let name: String + let url: URL +} + + +public enum Contributors: CaseIterable { + + case mauriceParker + case stuartBreckenridge + case bradEllis + case keilGillard + case anhDo + case nateWeaver + case andrewBrehaut + case danielJalkut + case joeHeck + case olofHellman + case rizwanMohamedIbrahim + case philViso + case ryanDotson + case others + + + public var contributor: AboutContributor { + switch self { + case .mauriceParker: + return AboutContributor(name: "Maurice Parker", url: URL(string: "https://vincode.io")!) + case .stuartBreckenridge: + return AboutContributor(name: "Stuart Breckenridge", url: URL(string: "https://stuartbreckenridge.net")!) + case .bradEllis: + return AboutContributor(name: "Brad Ellis", url: URL(string: "https://hachyderm.io/@bradellis")!) + case .keilGillard: + return AboutContributor(name: "Keil Gillard", url: URL(string: "https://twitter.com/kielgillard")!) + case .anhDo: + return AboutContributor(name: "Anh Do", url: URL(string:"https://mastodon.social/@anhdo")!) + case .nateWeaver: + return AboutContributor(name: "Nate Weaver", url: URL(string: "https://github.com/wevah")!) + case .andrewBrehaut: + return AboutContributor(name: "Andrew Brehaut", url: URL(string: "https://github.com/brehaut/")!) + case .danielJalkut: + return AboutContributor(name: "Daniel Jalkut", url: URL(string: "https://github.com/danielpunkass")!) + case .joeHeck: + return AboutContributor(name: "Joe Heck", url: URL(string: "https://rhonabwy.com/")!) + case .olofHellman: + return AboutContributor(name: "Olof Hellman", url: URL(string: "https://github.com/olofhellman")!) + case .rizwanMohamedIbrahim: + return AboutContributor(name: "Rizwan Mohamed Ibrahim", url: URL(string: "https://blog.rizwan.dev/")!) + case .philViso: + return AboutContributor(name: "Phil Viso", url: URL(string: "https://github.com/philviso")!) + case .ryanDotson: + return AboutContributor(name: "Ryan Dotson", url: URL(string: "https://github.com/nostodnayr")!) + case .others: + return AboutContributor(name: "and many more", url: URL(string: "https://github.com/Ranchero-Software/NetNewsWire/graphs/contributors")!) + } + } +} diff --git a/iOS/Settings/AboutCreditView.swift b/iOS/Settings/AboutCreditView.swift new file mode 100644 index 000000000..594f6665e --- /dev/null +++ b/iOS/Settings/AboutCreditView.swift @@ -0,0 +1,46 @@ +// +// AboutCreditView.swift +// NetNewsWire-iOS +// +// Created by Stuart Breckenridge on 15/09/2025. +// Copyright © 2025 Ranchero Software. All rights reserved. +// + +import SwiftUI + +struct AboutCreditView: View { + + let contributorType: String + let contributors: [Contributors] + + var body: some View { + HStack(alignment: .top) { + Spacer() + Text(verbatim: contributorType) + .foregroundStyle(.secondary) + .frame(maxWidth: .infinity, alignment: .trailing) + .lineLimit(3) + .multilineTextAlignment(.trailing) + .minimumScaleFactor(0.8) + VStack { + ForEach(contributors, id: \.self) { item in + Text(verbatim: item.contributor.name) + .frame(maxWidth: .infinity, alignment: .leading) + .lineLimit(2) + .multilineTextAlignment(.leading) + .minimumScaleFactor(0.8) + .foregroundStyle(.link) + .onTapGesture { + UIApplication.shared.open(item.contributor.url) + } + } + } + Spacer() + } + + } +} + +#Preview { + AboutCreditView(contributorType: "Contributing Developers", contributors: [Contributors.mauriceParker, Contributors.stuartBreckenridge]) +} diff --git a/iOS/Settings/AboutView.swift b/iOS/Settings/AboutView.swift new file mode 100644 index 000000000..78231051c --- /dev/null +++ b/iOS/Settings/AboutView.swift @@ -0,0 +1,74 @@ +// +// AboutView.swift +// NetNewsWire-iOS +// +// Created by Stuart Breckenridge on 15/09/2025. +// Copyright © 2025 Ranchero Software. All rights reserved. +// + +import SwiftUI + +struct AboutView: View { + var body: some View { + ScrollView(.vertical) { + VStack(alignment: .center, spacing: 12) { + Image("nnwFeedIcon") + .resizable() + .frame(width: 100, height: 100) + .clipShape(ConcentricRectangle(corners: .fixed(20))) + + Text(verbatim: "NetNewsWire") + .font(.largeTitle) + + Text(verbatim: "By Brent Simmons and the Ranchero Software Team") + .foregroundStyle(.secondary) + Text("[netnewswire.com](https://netnewswire.com)") + + + VStack(spacing: 6) { + Text(verbatim: "Credits") + .bold() + .foregroundStyle(.secondary) + .padding(.top, 16) + AboutCreditView(contributorType: "Contributing Developers", contributors: [Contributors.mauriceParker, Contributors.stuartBreckenridge]) + AboutCreditView(contributorType: "App Icon", contributors: [.bradEllis]) + AboutCreditView(contributorType: "Feedly Syncing", contributors: [.keilGillard]) + AboutCreditView(contributorType: "NewsBlur Synching", contributors: [.anhDo]) + AboutCreditView(contributorType: "Under-the-hood magic & CSS", contributors: [.nateWeaver]) + AboutCreditView(contributorType: "Newsfoot (JS footnote displayer)", contributors: [.andrewBrehaut]) + AboutCreditView(contributorType: "Help Book", contributors: [.ryanDotson]) + AboutCreditView(contributorType: "...and Featuring Additional Contributions from", contributors: [.danielJalkut, .joeHeck, .olofHellman, .rizwanMohamedIbrahim, .philViso, .others]) + } + + VStack(spacing: 6) { + Text(verbatim: "Thanks") + .bold() + .foregroundStyle(.secondary) + .padding(.top, 16) + Text("Thanks to Sheila and my family; thanks to my friends in Seattle and around the globe; thanks to the ever-patient and ever-awesome NetNewsWire beta testers.\n\nThanks to [Gus Mueller](https://shapeof.com/) for [FMDB](https://github.com/ccgus/fmdb) by [Flying Meat Software](http://flyingmeat.com/). Thanks to [GitHub](https://github.com) and [Discourse](https://discourse.com) for making open source collaboration easy and fun. Thanks to [Ben Ubois](https://benubois.com/) at [Feedbin](https://feedbin.com) for all the extra help with syncing and article rendering — and [for hosting the server for the Reader view](https://feedbin.com/blog/2019/03/11/the-future-of-full-content/).") + } + + VStack(spacing: 6) { + Text(verbatim: "Dedication") + .bold() + .foregroundStyle(.secondary) + .padding(.top, 16) + Text("NetNewsWire 7 is dedicated to everyone working to save democracy around the world.") + } + + + Text(verbatim: "Copyright © 2002-2025 Brent Simmons") + .font(.caption) + .foregroundStyle(.secondary) + } + .scenePadding(.horizontal) + } + .multilineTextAlignment(.center) + .background(Color(uiColor: .systemBackground)) + .navigationTitle(Text(verbatim: "About")) + } +} + +#Preview { + AboutView() +} diff --git a/iOS/Settings/AboutViewController.swift b/iOS/Settings/AboutViewController.swift deleted file mode 100644 index f6b7f3bd2..000000000 --- a/iOS/Settings/AboutViewController.swift +++ /dev/null @@ -1,60 +0,0 @@ -// -// AboutViewController.swift -// NetNewsWire-iOS -// -// Created by Maurice Parker on 4/25/19. -// Copyright © 2019 Ranchero Software. All rights reserved. -// - -import UIKit -import RSCore - -final class AboutViewController: UITableViewController { - - @IBOutlet var aboutTextView: UITextView! - @IBOutlet var creditsTextView: UITextView! - @IBOutlet var acknowledgmentsTextView: UITextView! - @IBOutlet var thanksTextView: UITextView! - @IBOutlet var dedicationTextView: UITextView! - - override func viewDidLoad() { - - super.viewDidLoad() - - configureCell(file: "About", textView: aboutTextView) - configureCell(file: "Credits", textView: creditsTextView) - configureCell(file: "Thanks", textView: thanksTextView) - configureCell(file: "Dedication", textView: dedicationTextView) - - let buildLabel = NonIntrinsicLabel(frame: CGRect(x: 32.0, y: 0.0, width: 0.0, height: 0.0)) - buildLabel.font = UIFont.systemFont(ofSize: 11.0) - buildLabel.textColor = UIColor.gray - buildLabel.text = NSLocalizedString("Copyright © 2002-2026 Brent Simmons", comment: "Copyright") - buildLabel.numberOfLines = 0 - buildLabel.sizeToFit() - buildLabel.translatesAutoresizingMaskIntoConstraints = false - - let wrapperView = UIView(frame: CGRect(x: 0, y: 0, width: buildLabel.frame.width, height: buildLabel.frame.height + 10.0)) - wrapperView.translatesAutoresizingMaskIntoConstraints = false - wrapperView.addSubview(buildLabel) - tableView.tableFooterView = wrapperView - } - - override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { - return UITableView.automaticDimension - } - -} - -private extension AboutViewController { - - func configureCell(file: String, textView: UITextView) { - let url = Bundle.main.url(forResource: file, withExtension: "rtf")! - let string = try! NSAttributedString(url: url, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.rtf], documentAttributes: nil) - textView.attributedText = string - textView.textColor = UIColor.label - textView.adjustsFontForContentSizeCategory = true - textView.font = .preferredFont(forTextStyle: .body) - } - -} diff --git a/iOS/Settings/Settings.storyboard b/iOS/Settings/Settings.storyboard index 0a83bf7c5..223482865 100644 --- a/iOS/Settings/Settings.storyboard +++ b/iOS/Settings/Settings.storyboard @@ -1,8 +1,8 @@ - + - + @@ -276,19 +276,19 @@ - + - + - - + - + - - + - + - + @@ -429,20 +429,20 @@ - + - +