From 05505fc2351d80278741deae7672a8e11d435f93 Mon Sep 17 00:00:00 2001 From: Abhishek Banthia Date: Sun, 5 May 2019 21:12:39 -0700 Subject: [PATCH] Swiftformatting. --- .swiftformat | 1 + Clocker/AppDelegate.swift | 47 ++-- Clocker/Clocker.xcodeproj/project.pbxproj | 8 +- Clocker/Clocker/LocationController.swift | 1 - .../ClockerUITests/FloatingWindowTests.swift | 2 +- .../NetworkDisconnectionTests.swift | 3 - Clocker/ClockerUITests/OnboardingTests.swift | 11 +- Clocker/ClockerUITests/PanelTests.swift | 9 +- Clocker/ClockerUITests/PreferencesTest.swift | 13 +- Clocker/ClockerUITests/ReviewTests.swift | 3 - Clocker/ClockerUITests/ShortcutTests.swift | 11 +- .../ClockerUnitTests/ClockerUnitTests.swift | 93 ++++---- Clocker/ClockerUnitTests/RateTests.swift | 4 +- .../Date Additions/Constants.swift | 16 +- .../Date Additions/Date+Bundle.swift | 9 +- .../Date Additions/Date+Comparators.swift | 93 ++++---- .../Date Additions/Date+Components.swift | 190 ++++++++------- .../Date Additions/Date+Format.swift | 1 - .../Date Additions/Date+Inits.swift | 67 +++--- .../Date Additions/Date+Manipulations.swift | 16 +- .../Date Additions/Date+TimeAgo.swift | 168 +++++++------- .../Dependencies/Date Additions/Enums.swift | 14 +- .../Date Additions/Integer+DateTools.swift | 1 - .../Date Additions/TimeChunk.swift | 88 ++++--- .../Date Additions/TimePeriod.swift | 217 +++++++++--------- .../Date Additions/TimePeriodChain.swift | 53 +++-- .../Date Additions/TimePeriodCollection.swift | 56 +++-- .../Date Additions/TimePeriodGroup.swift | 33 ++- Clocker/Dependencies/Solar.swift | 38 ++- .../CalendarHandler.swift | 17 +- .../Events and Reminders/EventCenter.swift | 2 +- .../RemindersHandler.swift | 5 +- Clocker/Menu Bar/MenubarHandler.swift | 12 +- Clocker/Menu Bar/StatusContainerView.swift | 8 +- Clocker/Menu Bar/StatusItemHandler.swift | 9 +- Clocker/Menu Bar/StatusItemView.swift | 23 +- .../OnboardingParentViewController.swift | 66 +++--- .../OnboardingPermissionsViewController.swift | 3 +- .../OnboardingSearchController.swift | 94 ++++---- Clocker/Overall App/AppDefaults.swift | 11 +- Clocker/Overall App/AppKit + Additions.swift | 6 +- .../Overall App/DateFormatterManager.swift | 2 +- Clocker/Overall App/Reach.swift | 2 +- Clocker/Overall App/Themer.swift | 5 - Clocker/Overall App/Timer.swift | 4 +- .../UserDefaults + KVOExtensions.swift | 1 - Clocker/Panel/Data Layer/TimezoneData.swift | 9 +- .../Data Layer/TimezoneDataOperations.swift | 19 +- Clocker/Panel/FloatingWindowController.swift | 2 +- .../Panel/Notes Popover/NotesPopover.swift | 8 +- .../TextViewWithPlaceholder.swift | 4 +- Clocker/Panel/PanelController.swift | 13 +- Clocker/Panel/ParentPanelController.swift | 42 ++-- .../Rate Controller/RateController.swift | 8 +- .../Panel/Rate Controller/ReviewView.swift | 4 +- Clocker/Panel/UI/CustomSliderCell.swift | 4 +- Clocker/Panel/UI/NoTimezoneView.swift | 12 +- Clocker/Panel/UI/PanelTableView.swift | 2 +- Clocker/Panel/UI/TimezoneCellView.swift | 2 +- Clocker/Panel/UI/TimezoneDataSource.swift | 4 +- .../About/AboutViewController.swift | 23 +- .../AppFeedbackWindowController.swift | 2 +- .../Appearance/AppearanceViewController.swift | 57 +++-- .../Calendar/CalendarViewController.swift | 70 +++--- .../General/PreferencesViewController.swift | 56 +++-- Clocker/Preferences/OneWindowController.swift | 20 +- .../PermissionsViewController.swift | 3 - 67 files changed, 868 insertions(+), 1032 deletions(-) create mode 100644 .swiftformat diff --git a/.swiftformat b/.swiftformat new file mode 100644 index 0000000..a690919 --- /dev/null +++ b/.swiftformat @@ -0,0 +1 @@ +--disable \ No newline at end of file diff --git a/Clocker/AppDelegate.swift b/Clocker/AppDelegate.swift index 025631a..603b397 100644 --- a/Clocker/AppDelegate.swift +++ b/Clocker/AppDelegate.swift @@ -3,9 +3,8 @@ import Cocoa open class AppDelegate: NSObject, NSApplicationDelegate { - - lazy private var floatingWindow: FloatingWindowController = FloatingWindowController.shared() - lazy private var panelController: PanelController = PanelController.shared() + private lazy var floatingWindow: FloatingWindowController = FloatingWindowController.shared() + private lazy var panelController: PanelController = PanelController.shared() private var statusBarHandler: StatusItemHandler! private var panelObserver: NSKeyValueObservation? @@ -13,10 +12,8 @@ open class AppDelegate: NSObject, NSApplicationDelegate { panelObserver?.invalidate() } - open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { - + open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change _: [NSKeyValueChangeKey: Any]?, context _: UnsafeMutableRawPointer?) { if let path = keyPath, path == "values.globalPing" { - let hotKeyCenter = PTHotKeyCenter.shared() // Unregister old hot key @@ -36,16 +33,14 @@ open class AppDelegate: NSObject, NSApplicationDelegate { hotKeyCenter?.register(newHotKey) } - } - public func applicationWillFinishLaunching(_ notification: Notification) { + public func applicationWillFinishLaunching(_: Notification) { iVersion.sharedInstance().useAllAvailableLanguages = true iVersion.sharedInstance().verboseLogging = false } - public func applicationDidFinishLaunching(_ notification: Notification) { - + public func applicationDidFinishLaunching(_: Notification) { // Initializing the event store takes really long EventCenter.sharedCenter() @@ -64,7 +59,7 @@ open class AppDelegate: NSObject, NSApplicationDelegate { #endif } - public func applicationDockMenu(_ sender: NSApplication) -> NSMenu? { + public func applicationDockMenu(_: NSApplication) -> NSMenu? { let menu = NSMenu(title: "Quick Access") Logger.log(object: ["Dock Menu Triggered": "YES"], for: "Dock Menu Triggered") @@ -93,13 +88,13 @@ open class AppDelegate: NSObject, NSApplicationDelegate { } private lazy var controller: OnboardingController? = { - let onboardingStoryboard = NSStoryboard(name: NSStoryboard.Name("Onboarding"), bundle: nil) - return onboardingStoryboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier("onboardingFlow")) as? OnboardingController + let onboardingStoryboard = NSStoryboard(name: NSStoryboard.Name("Onboarding"), bundle: nil) + return onboardingStoryboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier("onboardingFlow")) as? OnboardingController }() private func showOnboardingFlow() { let shouldLaunchOnboarding = (DataStore.shared().retrieve(key: CLShowOnboardingFlow) == nil && DataStore.shared().timezones().isEmpty) - || (ProcessInfo.processInfo.arguments.contains(CLOnboaringTestsLaunchArgument)) + || ProcessInfo.processInfo.arguments.contains(CLOnboaringTestsLaunchArgument) shouldLaunchOnboarding ? controller?.launch() : continueUsually() } @@ -127,8 +122,8 @@ open class AppDelegate: NSObject, NSApplicationDelegate { assignShortcut() - panelObserver = panelController.observe(\.hasActivePanel, options: [.new]) { (obj, _) in - self.statusBarHandler.setHasActiveIcon(obj.hasActivePanelGetter()) + panelObserver = panelController.observe(\.hasActivePanel, options: [.new]) { obj, _ in + self.statusBarHandler.setHasActiveIcon(obj.hasActivePanelGetter()) } let defaults = UserDefaults.standard @@ -153,7 +148,7 @@ open class AppDelegate: NSObject, NSApplicationDelegate { private func checkIfAppIsAlreadyOpen() { guard let bundleID = Bundle.main.bundleIdentifier else { - return + return } let apps = NSRunningApplication.runningApplications(withBundleIdentifier: bundleID) @@ -218,13 +213,12 @@ open class AppDelegate: NSObject, NSApplicationDelegate { private func assignShortcut() { NSUserDefaultsController.shared.addObserver(self, - forKeyPath: "values.globalPing", - options: [.initial, .new], - context: nil) + forKeyPath: "values.globalPing", + options: [.initial, .new], + context: nil) } private func checkIfRunFromApplicationsFolder() { - if let shortCircuit = UserDefaults.standard.object(forKey: "AllowOutsideApplicationsFolder") as? Bool, shortCircuit == true { return } @@ -240,10 +234,10 @@ open class AppDelegate: NSObject, NSApplicationDelegate { } let informativeText = """ - Clocker must be run from the Applications folder in order to work properly. - Please quit Clocker, move it to the Applications folder, and relaunch. - Current folder: \(applicationDirectory)" - """ + Clocker must be run from the Applications folder in order to work properly. + Please quit Clocker, move it to the Applications folder, and relaunch. + Current folder: \(applicationDirectory)" + """ // Clocker is installed out of Applications directory // This breaks start at login! Time to show an alert and terminate @@ -255,8 +249,7 @@ open class AppDelegate: NSObject, NSApplicationDelegate { NSApp.terminate(nil) } - @IBAction open func togglePanel(_ sender: Any) { - + @IBAction open func togglePanel(_: Any) { let displayMode = UserDefaults.standard.integer(forKey: CLShowAppInForeground) if displayMode == 1 { diff --git a/Clocker/Clocker.xcodeproj/project.pbxproj b/Clocker/Clocker.xcodeproj/project.pbxproj index e612db4..a5b3d71 100755 --- a/Clocker/Clocker.xcodeproj/project.pbxproj +++ b/Clocker/Clocker.xcodeproj/project.pbxproj @@ -896,7 +896,7 @@ 9A4379201BEC220200F4E27F /* ShellScript */, 9A20A0711C4E808500FB45AB /* Login Item Helper */, 9A5E75EC204CC39700119939 /* Embed Frameworks */, - C2A632A020EAC5EE00EB6BEA /* Move .app to Applications */, + C2A632A020EAC5EE00EB6BEA /* SwiftFormat */, ); buildRules = ( ); @@ -1070,19 +1070,19 @@ shellScript = ""; showEnvVarsInLog = 0; }; - C2A632A020EAC5EE00EB6BEA /* Move .app to Applications */ = { + C2A632A020EAC5EE00EB6BEA /* SwiftFormat */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "Move .app to Applications"; + name = SwiftFormat; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "# sh /Users/abhishek_banthia/Documents/GitLab/Check/Clocker-Private/Clocker/Move.sh\n"; + shellScript = "if which swiftformat >/dev/null; then\n swiftformat . --swiftversion 5\nelse\n echo \"warning: SwiftFormat not installed, download from https://github.com/nicklockwood/SwiftFormat\"\nfi\n"; }; /* End PBXShellScriptBuildPhase section */ diff --git a/Clocker/Clocker/LocationController.swift b/Clocker/Clocker/LocationController.swift index cd78d6b..8161d79 100644 --- a/Clocker/Clocker/LocationController.swift +++ b/Clocker/Clocker/LocationController.swift @@ -87,7 +87,6 @@ class LocationController: NSObject { extension LocationController: CLLocationManagerDelegate { func locationManager(_: CLLocationManager, didUpdateLocations locations: [CLLocation]) { - guard !locations.isEmpty, let coordinates = locations.first?.coordinate else { return } let reverseGeoCoder = CLGeocoder() diff --git a/Clocker/ClockerUITests/FloatingWindowTests.swift b/Clocker/ClockerUITests/FloatingWindowTests.swift index 16f2332..4f825fe 100644 --- a/Clocker/ClockerUITests/FloatingWindowTests.swift +++ b/Clocker/ClockerUITests/FloatingWindowTests.swift @@ -114,7 +114,7 @@ class FloatingWindowTests: XCTestCase { let menubarDisplayQuery = app.tables.checkBoxes.matching(NSPredicate(format: "value == 1", "")) let menubarDisplayQueryCount = menubarDisplayQuery.count - for index in 0.. 0) } - } diff --git a/Clocker/ClockerUITests/PreferencesTest.swift b/Clocker/ClockerUITests/PreferencesTest.swift index 41da0e3..13bc3ba 100644 --- a/Clocker/ClockerUITests/PreferencesTest.swift +++ b/Clocker/ClockerUITests/PreferencesTest.swift @@ -3,7 +3,6 @@ import XCTest class PreferencesTest: XCTestCase { - var app: XCUIApplication! override func setUp() { @@ -56,7 +55,6 @@ class PreferencesTest: XCTestCase { } func testEditingLabel() { - let placeToAdd = "Auckland" app.tapMenubarIcon() @@ -83,7 +81,6 @@ class PreferencesTest: XCTestCase { app.tables["mainTableView"].typeKey(",", modifierFlags: .command) deleteAPlace(place: placeToAdd, for: app) - } func testSortingByTimezoneDifference() { @@ -312,7 +309,7 @@ class PreferencesTest: XCTestCase { let favouritedMenubarsQuery = preferencesTable.checkBoxes.matching(NSPredicate(format: "value == 1", "")) if favouritedMenubarsQuery.count > 1 { - for _ in 0.. 1 { - for _ in 0..<2 { + for _ in 0 ..< 2 { let checkbox = unfavouritedMenubarsQuery.element(boundBy: 0) checkbox.click() } @@ -337,8 +334,8 @@ class PreferencesTest: XCTestCase { let compactModeButton = app.dialogs.buttons["Enable Compact Mode"] if compactModeButton.isHittable { - compactModeButton.click() - XCTAssertTrue(app.dialogs.count == 0) + compactModeButton.click() + XCTAssertTrue(app.dialogs.count == 0) } } @@ -347,7 +344,6 @@ class PreferencesTest: XCTestCase { let rowQueryCount = clockerWindow.tables["TimezoneTableView"].tableRows.count if rowQueryCount > 0 { - let currentElement = clockerWindow.tables["TimezoneTableView"].tableRows.firstMatch currentElement.click() @@ -355,7 +351,6 @@ class PreferencesTest: XCTestCase { clockerWindow.typeKey(XCUIKeyboardKey.delete, modifierFlags: XCUIElement.KeyModifierFlags()) } - } } } diff --git a/Clocker/ClockerUITests/ReviewTests.swift b/Clocker/ClockerUITests/ReviewTests.swift index fd516d0..69c8245 100644 --- a/Clocker/ClockerUITests/ReviewTests.swift +++ b/Clocker/ClockerUITests/ReviewTests.swift @@ -3,7 +3,6 @@ import XCTest class ReviewTests: XCTestCase { - var app: XCUIApplication! override func setUp() { @@ -19,7 +18,6 @@ class ReviewTests: XCTestCase { } func testIfReviewIsNegativeAndUserWantsToProvideFeedback() { - guard app.buttons["Not Really"].exists else { return } XCTAssertTrue(app.staticTexts["ReviewLabel"].exists) app.buttons["Not Really"].click() @@ -55,5 +53,4 @@ class ReviewTests: XCTestCase { app.buttons["Yes"].click() XCTAssertFalse(app.staticTexts["ReviewLabel"].exists) } - } diff --git a/Clocker/ClockerUITests/ShortcutTests.swift b/Clocker/ClockerUITests/ShortcutTests.swift index 79f19c6..aaddb23 100644 --- a/Clocker/ClockerUITests/ShortcutTests.swift +++ b/Clocker/ClockerUITests/ShortcutTests.swift @@ -3,7 +3,6 @@ import XCTest class ShortcutTests: XCTestCase { - var app: XCUIApplication! let randomIndex = Int(arc4random_uniform(26)) @@ -22,7 +21,6 @@ class ShortcutTests: XCTestCase { } func testShortcuts() { - app.tables["mainTableView"].typeKey(",", modifierFlags: .command) XCTAssertFalse(app.tables["mainTableView"].exists) @@ -45,16 +43,15 @@ class ShortcutTests: XCTestCase { XCTAssertTrue(app.tables["mainTableView"].exists) // Reset the shortcut - app.tables["mainTableView"].typeKey(",", modifierFlags: .command) - app.windows["Clocker"].buttons["ShortcutControl"].click() + app.tables["mainTableView"].typeKey(",", modifierFlags: .command) + app.windows["Clocker"].buttons["ShortcutControl"].click() app.windows["Clocker"].typeKey(XCUIKeyboardKey.delete, modifierFlags: []) - app.windows["Clocker"].typeKey(randomAlphabet, modifierFlags: [.shift, .command]) - XCTAssertFalse(app.tables["mainTableView"].exists) + app.windows["Clocker"].typeKey(randomAlphabet, modifierFlags: [.shift, .command]) + XCTAssertFalse(app.tables["mainTableView"].exists) } private func randomLetter() -> String { let alphabet: [String] = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] return alphabet[randomIndex] } - } diff --git a/Clocker/ClockerUnitTests/ClockerUnitTests.swift b/Clocker/ClockerUnitTests/ClockerUnitTests.swift index 840cfae..c6b1a6d 100644 --- a/Clocker/ClockerUnitTests/ClockerUnitTests.swift +++ b/Clocker/ClockerUnitTests/ClockerUnitTests.swift @@ -1,55 +1,54 @@ // Copyright © 2015 Abhishek Banthia -import XCTest @testable import Clocker +import XCTest class ClockerUnitTests: XCTestCase { - - private let california = ["customLabel" : "Test", - "formattedAddress" : "San Francisco", - "place_id" : "TestIdentifier", - "timezoneID" : "America/Los_Angeles", - "nextUpdate" : "", - "latitude" : "37.7749295", - "longitude" : "-122.4194155"] - - private let mumbai = ["customLabel" : "Ghar", - "formattedAddress" : "Mumbai", - "place_id" : "ChIJwe1EZjDG5zsRaYxkjY_tpF0", - "timezoneID" : "Asia/Calcutta", - "nextUpdate" : "", - "latitude" : "19.0759837", - "longitude" : "72.8776559"] - - private let auckland = ["customLabel" : "Auckland", - "formattedAddress" : "New Zealand", - "place_id" : "ChIJh5Z3Fw4gLG0RM0dqdeIY1rE", - "timezoneID" : "Pacific/Auckland", - "nextUpdate" : "", - "latitude" : "-40.900557", - "longitude" : "174.885971"] - - private let florida = ["customLabel" : "Gainesville", - "formattedAddress" : "Florida", - "place_id" : "ChIJvypWkWV2wYgR0E7HW9MTLvc", - "timezoneID" : "America/New_York", - "nextUpdate" : "", - "latitude" : "27.664827", - "longitude" : "-81.5157535"] + private let california = ["customLabel": "Test", + "formattedAddress": "San Francisco", + "place_id": "TestIdentifier", + "timezoneID": "America/Los_Angeles", + "nextUpdate": "", + "latitude": "37.7749295", + "longitude": "-122.4194155"] + + private let mumbai = ["customLabel": "Ghar", + "formattedAddress": "Mumbai", + "place_id": "ChIJwe1EZjDG5zsRaYxkjY_tpF0", + "timezoneID": "Asia/Calcutta", + "nextUpdate": "", + "latitude": "19.0759837", + "longitude": "72.8776559"] + + private let auckland = ["customLabel": "Auckland", + "formattedAddress": "New Zealand", + "place_id": "ChIJh5Z3Fw4gLG0RM0dqdeIY1rE", + "timezoneID": "Pacific/Auckland", + "nextUpdate": "", + "latitude": "-40.900557", + "longitude": "174.885971"] + + private let florida = ["customLabel": "Gainesville", + "formattedAddress": "Florida", + "place_id": "ChIJvypWkWV2wYgR0E7HW9MTLvc", + "timezoneID": "America/New_York", + "nextUpdate": "", + "latitude": "27.664827", + "longitude": "-81.5157535"] private let onlyTimezone: [String: Any] = ["timezoneID": "Africa/Algiers", - "formattedAddress" : "Africa/Algiers", + "formattedAddress": "Africa/Algiers", "place_id": "", "customLabel": "", "latitude": "", "longitude": ""] private let omaha: [String: Any] = ["timezoneID": "America/Chicago", - "formattedAddress" : "Omaha", - "place_id": "ChIJ7fwMtciNk4cRBLY3rk9NQkY", - "customLabel": "", - "latitude": "41.2565369", - "longitude": "-95.9345034"] + "formattedAddress": "Omaha", + "place_id": "ChIJ7fwMtciNk4cRBLY3rk9NQkY", + "customLabel": "", + "latitude": "41.2565369", + "longitude": "-95.9345034"] private var operations: TimezoneDataOperations { return TimezoneDataOperations(with: TimezoneData(with: mumbai)) @@ -72,7 +71,6 @@ class ClockerUnitTests: XCTestCase { } func testAddingATimezoneToDefaults() { - let timezoneData = TimezoneData(with: california) let defaults = UserDefaults.standard @@ -134,7 +132,6 @@ class ClockerUnitTests: XCTestCase { } func testDateWithSliderValue() { - let dataObject = TimezoneData(with: mumbai) let operations = TimezoneDataOperations(with: dataObject) @@ -174,7 +171,6 @@ class ClockerUnitTests: XCTestCase { } func testFormattedLabel() { - let dataObject = TimezoneData(with: mumbai) XCTAssertTrue(dataObject.formattedTimezoneLabel() == "Ghar", "Incorrect custom label returned by model.") @@ -200,7 +196,6 @@ class ClockerUnitTests: XCTestCase { } func testWithAllLocales() { - let dataObject1 = TimezoneData(with: mumbai) let operations = TimezoneDataOperations(with: dataObject1) @@ -212,17 +207,16 @@ class ClockerUnitTests: XCTestCase { } func testTimeWithAllLocales() { - let dataObject = TimezoneData(with: mumbai) let cal = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian) guard let newDate = cal?.date(byAdding: .minute, - value: 0, - to: Date(), - options: .matchFirst) else { - XCTFail("Unable to add dates!") - return + value: 0, + to: Date(), + options: .matchFirst) else { + XCTFail("Unable to add dates!") + return } for locale in Locale.availableIdentifiers { @@ -235,5 +229,4 @@ class ClockerUnitTests: XCTestCase { XCTAssertNotNil(convertedDate) } } - } diff --git a/Clocker/ClockerUnitTests/RateTests.swift b/Clocker/ClockerUnitTests/RateTests.swift index 27f1572..eada6a3 100644 --- a/Clocker/ClockerUnitTests/RateTests.swift +++ b/Clocker/ClockerUnitTests/RateTests.swift @@ -1,10 +1,9 @@ // Copyright © 2015 Abhishek Banthia -import XCTest @testable import Clocker +import XCTest class RateTests: XCTestCase { - let rateController = RateController.applicationDidLaunch(UserDefaults()) override func setUp() { @@ -15,5 +14,4 @@ class RateTests: XCTestCase { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } - } diff --git a/Clocker/Dependencies/Date Additions/Constants.swift b/Clocker/Dependencies/Date Additions/Constants.swift index 5df94f0..1aba151 100755 --- a/Clocker/Dependencies/Date Additions/Constants.swift +++ b/Clocker/Dependencies/Date Additions/Constants.swift @@ -12,17 +12,17 @@ import Foundation * Time conversions used across DateTools */ public class Constants { - public static let SecondsInYear: TimeInterval = 31536000 - public static let SecondsInLeapYear: TimeInterval = 31622400 - public static let SecondsInMonth28: TimeInterval = 2419200 - public static let SecondsInMonth29: TimeInterval = 2505600 - public static let SecondsInMonth30: TimeInterval = 2592000 - public static let SecondsInMonth31: TimeInterval = 2678400 - public static let SecondsInWeek: TimeInterval = 604800 + public static let SecondsInYear: TimeInterval = 31_536_000 + public static let SecondsInLeapYear: TimeInterval = 31_622_400 + public static let SecondsInMonth28: TimeInterval = 2_419_200 + public static let SecondsInMonth29: TimeInterval = 2_505_600 + public static let SecondsInMonth30: TimeInterval = 2_592_000 + public static let SecondsInMonth31: TimeInterval = 2_678_400 + public static let SecondsInWeek: TimeInterval = 604_800 public static let SecondsInDay: TimeInterval = 86400 public static let SecondsInHour: TimeInterval = 3600 public static let SecondsInMinute: TimeInterval = 60 - public static let MillisecondsInDay: TimeInterval = 86400000 + public static let MillisecondsInDay: TimeInterval = 86_400_000 public static let AllCalendarUnitFlags: Set = [.year, .quarter, .month, .weekOfYear, .weekOfMonth, .day, .hour, .minute, .second, .era, .weekday, .weekdayOrdinal, .weekOfYear] } diff --git a/Clocker/Dependencies/Date Additions/Date+Bundle.swift b/Clocker/Dependencies/Date Additions/Date+Bundle.swift index 33cfd42..9b3ad10 100755 --- a/Clocker/Dependencies/Date Additions/Date+Bundle.swift +++ b/Clocker/Dependencies/Date Additions/Date+Bundle.swift @@ -9,9 +9,8 @@ import Foundation public extension Bundle { - - class func dateToolsBundle() -> Bundle { - let assetPath = Bundle(for: Constants.self).resourcePath! - return Bundle(path: NSString(string: assetPath).appendingPathComponent("DateTools.bundle"))! - } + class func dateToolsBundle() -> Bundle { + let assetPath = Bundle(for: Constants.self).resourcePath! + return Bundle(path: NSString(string: assetPath).appendingPathComponent("DateTools.bundle"))! + } } diff --git a/Clocker/Dependencies/Date Additions/Date+Comparators.swift b/Clocker/Dependencies/Date Additions/Date+Comparators.swift index aa56ec2..b358221 100755 --- a/Clocker/Dependencies/Date Additions/Date+Comparators.swift +++ b/Clocker/Dependencies/Date Additions/Date+Comparators.swift @@ -15,7 +15,6 @@ import Foundation * for a given unit of time. */ public extension Date { - // MARK: - Comparisons /** @@ -28,15 +27,15 @@ public extension Date { * let age = birthday.chunkBetween(date: formatter.date(from: "2016 10 07 15:27:12.000")!) * ``` * - * The age variable will have a chunk of time with year, month, day, hour, minute, - * and second components (note that we do not use weeks since they are not components + * The age variable will have a chunk of time with year, month, day, hour, minute, + * and second components (note that we do not use weeks since they are not components * of `Calendar`). So if you just wanted the age in years, you could then say: age.years. * - * The chunk is calculated exactly as you'd say it in real life, always converting up - * when a lower unit equals 1 of the unit above it. The above example returns + * The chunk is calculated exactly as you'd say it in real life, always converting up + * when a lower unit equals 1 of the unit above it. The above example returns * `TimeChunk(seconds: 0, minutes: 37, hours: 0, days: 13, weeks: 0, months: 10, years: 0)`. * - * Passing a future date returns a TimeChunk with all positive components and passing + * Passing a future date returns a TimeChunk with all positive components and passing * a date in the past returns one with all negative components. * * - parameter date: The date of reference from the date called on @@ -56,9 +55,9 @@ public extension Date { * * - returns: Bool representing comparison result */ - func equals(_ date: Date) -> Bool { - return self.compare(date) == .orderedSame - } + func equals(_ date: Date) -> Bool { + return compare(date) == .orderedSame + } /** * Returns a true if receiver is later than provided comparison date, otherwise @@ -68,9 +67,9 @@ public extension Date { * * - returns: Bool representing comparison result */ - func isLater(than date: Date) -> Bool { - return self.compare(date) == .orderedDescending - } + func isLater(than date: Date) -> Bool { + return compare(date) == .orderedDescending + } /** * Returns a true if receiver is later than or equal to provided comparison date, @@ -81,7 +80,7 @@ public extension Date { * - returns: Bool representing comparison result */ func isLaterThanOrEqual(to date: Date) -> Bool { - return self.compare(date) == .orderedDescending || self.compare(date) == .orderedSame + return compare(date) == .orderedDescending || compare(date) == .orderedSame } /** @@ -92,9 +91,9 @@ public extension Date { * * - returns: Bool representing comparison result */ - func isEarlier(than date: Date) -> Bool { - return self.compare(date) == .orderedAscending - } + func isEarlier(than date: Date) -> Bool { + return compare(date) == .orderedAscending + } /** * Returns a true if receiver is earlier than or equal to the provided comparison date, @@ -105,7 +104,7 @@ public extension Date { * - returns: Bool representing comparison result */ func isEarlierThanOrEqual(to date: Date) -> Bool { - return self.compare(date) == .orderedAscending || self.compare(date) == .orderedSame + return compare(date) == .orderedAscending || compare(date) == .orderedSame } /** @@ -115,7 +114,7 @@ public extension Date { * * - returns: True if both paramter dates fall on the same day, false otherwise */ - func isSameDay(date : Date ) -> Bool { + func isSameDay(date: Date) -> Bool { return Date.isSameDay(date: self, as: date) } @@ -154,7 +153,7 @@ public extension Date { * - returns: The years between receiver and provided date */ func years(from date: Date) -> Int { - return years(from: date, calendar:nil) + return years(from: date, calendar: nil) } /** @@ -169,7 +168,7 @@ public extension Date { * - returns: The years between receiver and provided date */ func months(from date: Date) -> Int { - return months(from: date, calendar:nil) + return months(from: date, calendar: nil) } /** @@ -184,7 +183,7 @@ public extension Date { * - returns: The weeks between receiver and provided date */ func weeks(from date: Date) -> Int { - return weeks(from: date, calendar:nil) + return weeks(from: date, calendar: nil) } /** @@ -199,7 +198,7 @@ public extension Date { * - returns: The days between receiver and provided date */ func days(from date: Date) -> Int { - return days(from: date, calendar:nil) + return days(from: date, calendar: nil) } /** @@ -213,7 +212,7 @@ public extension Date { * - returns: The hours between receiver and provided date */ func hours(from date: Date) -> Int { - return Int(self.timeIntervalSince(date)/Constants.SecondsInHour) + return Int(timeIntervalSince(date) / Constants.SecondsInHour) } /** @@ -227,7 +226,7 @@ public extension Date { * - returns: The minutes between receiver and provided date */ func minutes(from date: Date) -> Int { - return Int(self.timeIntervalSince(date)/Constants.SecondsInMinute) + return Int(timeIntervalSince(date) / Constants.SecondsInMinute) } /** @@ -259,7 +258,7 @@ public extension Date { */ func years(from date: Date, calendar: Calendar?) -> Int { var calendarCopy = calendar - if (calendar == nil) { + if calendar == nil { calendarCopy = Calendar.autoupdatingCurrent } @@ -283,7 +282,7 @@ public extension Date { */ func months(from date: Date, calendar: Calendar?) -> Int { var calendarCopy = calendar - if (calendar == nil) { + if calendar == nil { calendarCopy = Calendar.autoupdatingCurrent } @@ -291,7 +290,7 @@ public extension Date { let latest = (earliest == self) ? date : self let multiplier = (earliest == self) ? -1 : 1 let components = calendarCopy!.dateComponents(Constants.AllCalendarUnitFlags, from: earliest, to: latest) - return multiplier*(components.month! + 12*components.year!) + return multiplier * (components.month! + 12 * components.year!) } /** @@ -307,7 +306,7 @@ public extension Date { */ func weeks(from date: Date, calendar: Calendar?) -> Int { var calendarCopy = calendar - if (calendar == nil) { + if calendar == nil { calendarCopy = Calendar.autoupdatingCurrent } @@ -315,7 +314,7 @@ public extension Date { let latest = (earliest == self) ? date : self let multiplier = (earliest == self) ? -1 : 1 let components = calendarCopy!.dateComponents([.weekOfYear], from: earliest, to: latest) - return multiplier*components.weekOfYear! + return multiplier * components.weekOfYear! } /** @@ -331,7 +330,7 @@ public extension Date { */ func days(from date: Date, calendar: Calendar?) -> Int { var calendarCopy = calendar - if (calendar == nil) { + if calendar == nil { calendarCopy = Calendar.autoupdatingCurrent } @@ -339,13 +338,13 @@ public extension Date { let latest = (earliest == self) ? date : self let multiplier = (earliest == self) ? -1 : 1 let components = calendarCopy!.dateComponents([.day], from: earliest, to: latest) - return multiplier*components.day! + return multiplier * components.day! } // MARK: Time Until /** - * The number of years until the receiver's date (0 if the receiver is the same or + * The number of years until the receiver's date (0 if the receiver is the same or * earlier than now). */ var yearsUntil: Int { @@ -353,7 +352,7 @@ public extension Date { } /** - * The number of months until the receiver's date (0 if the receiver is the same or + * The number of months until the receiver's date (0 if the receiver is the same or * earlier than now). */ var monthsUntil: Int { @@ -361,7 +360,7 @@ public extension Date { } /** - * The number of weeks until the receiver's date (0 if the receiver is the same or + * The number of weeks until the receiver's date (0 if the receiver is the same or * earlier than now). */ var weeksUntil: Int { @@ -369,7 +368,7 @@ public extension Date { } /** - * The number of days until the receiver's date (0 if the receiver is the same or + * The number of days until the receiver's date (0 if the receiver is the same or * earlier than now). */ var daysUntil: Int { @@ -377,7 +376,7 @@ public extension Date { } /** - * The number of hours until the receiver's date (0 if the receiver is the same or + * The number of hours until the receiver's date (0 if the receiver is the same or * earlier than now). */ var hoursUntil: Int { @@ -385,7 +384,7 @@ public extension Date { } /** - * The number of minutes until the receiver's date (0 if the receiver is the same or + * The number of minutes until the receiver's date (0 if the receiver is the same or * earlier than now). */ var minutesUntil: Int { @@ -393,7 +392,7 @@ public extension Date { } /** - * The number of seconds until the receiver's date (0 if the receiver is the same or + * The number of seconds until the receiver's date (0 if the receiver is the same or * earlier than now). */ var secondsUntil: Int { @@ -403,7 +402,7 @@ public extension Date { // MARK: Time Ago /** - * The number of years the receiver's date is earlier than now (0 if the receiver is + * The number of years the receiver's date is earlier than now (0 if the receiver is * the same or earlier than now). */ var yearsAgo: Int { @@ -411,7 +410,7 @@ public extension Date { } /** - * The number of months the receiver's date is earlier than now (0 if the receiver is + * The number of months the receiver's date is earlier than now (0 if the receiver is * the same or earlier than now). */ var monthsAgo: Int { @@ -419,7 +418,7 @@ public extension Date { } /** - * The number of weeks the receiver's date is earlier than now (0 if the receiver is + * The number of weeks the receiver's date is earlier than now (0 if the receiver is * the same or earlier than now). */ var weeksAgo: Int { @@ -427,7 +426,7 @@ public extension Date { } /** - * The number of days the receiver's date is earlier than now (0 if the receiver is + * The number of days the receiver's date is earlier than now (0 if the receiver is * the same or earlier than now). */ var daysAgo: Int { @@ -435,7 +434,7 @@ public extension Date { } /** - * The number of hours the receiver's date is earlier than now (0 if the receiver is + * The number of hours the receiver's date is earlier than now (0 if the receiver is * the same or earlier than now). */ var hoursAgo: Int { @@ -443,7 +442,7 @@ public extension Date { } /** - * The number of minutes the receiver's date is earlier than now (0 if the receiver is + * The number of minutes the receiver's date is earlier than now (0 if the receiver is * the same or earlier than now). */ var minutesAgo: Int { @@ -451,7 +450,7 @@ public extension Date { } /** - * The number of seconds the receiver's date is earlier than now (0 if the receiver is + * The number of seconds the receiver's date is earlier than now (0 if the receiver is * the same or earlier than now). */ var secondsAgo: Int { @@ -548,7 +547,7 @@ public extension Date { /** * Returns the number of years the receiver's date is later than the provided - * comparison date, 0 if the receiver's date is earlier than or equal to the provided + * comparison date, 0 if the receiver's date is earlier than or equal to the provided * comparison date. * * - parameter date: Provided date for comparison @@ -561,7 +560,7 @@ public extension Date { /** * Returns the number of months the receiver's date is later than the provided - * comparison date, 0 if the receiver's date is earlier than or equal to the provided + * comparison date, 0 if the receiver's date is earlier than or equal to the provided * comparison date. * * - parameter date: Provided date for comparison diff --git a/Clocker/Dependencies/Date Additions/Date+Components.swift b/Clocker/Dependencies/Date Additions/Date+Components.swift index 6766ef4..79bfeec 100755 --- a/Clocker/Dependencies/Date Additions/Date+Components.swift +++ b/Clocker/Dependencies/Date Additions/Date+Components.swift @@ -14,7 +14,6 @@ import Foundation * several computed Bools. */ public extension Date { - /** * Convenient accessor of the date's `Calendar` components. * @@ -24,9 +23,9 @@ public extension Date { * */ func component(_ component: Calendar.Component) -> Int { - let calendar = Calendar.autoupdatingCurrent - return calendar.component(component, from: self) - } + let calendar = Calendar.autoupdatingCurrent + return calendar.component(component, from: self) + } /** * Convenient accessor of the date's `Calendar` components ordinality. @@ -37,10 +36,10 @@ public extension Date { * - returns: The ordinal number of a smaller calendar component within a specified larger calendar component * */ - func ordinality(of smaller: Calendar.Component, in larger: Calendar.Component) -> Int? { - let calendar = Calendar.autoupdatingCurrent - return calendar.ordinality(of: smaller, in: larger, for: self) - } + func ordinality(of smaller: Calendar.Component, in larger: Calendar.Component) -> Int? { + let calendar = Calendar.autoupdatingCurrent + return calendar.ordinality(of: smaller, in: larger, for: self) + } /** * Use calendar components to determine how many units of a smaller component are inside 1 larger unit. @@ -54,17 +53,16 @@ public extension Date { * - returns: The number of smaller units required to equal in 1 larger unit, given the date called on * */ - func unit(of smaller: Calendar.Component, in larger: Calendar.Component) -> Int? { - let calendar = Calendar.autoupdatingCurrent + func unit(of smaller: Calendar.Component, in larger: Calendar.Component) -> Int? { + let calendar = Calendar.autoupdatingCurrent var units = 1 var unitRange: Range? if larger.hashValue < smaller.hashValue { - for x in larger.hashValue.. Date { var newDate = self if component == .second { - newDate.second(self.second) + newDate.second(second) } else if component == .minute { newDate.second(0) } else if component == .hour { @@ -99,10 +98,10 @@ public extension Date { if month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 { // 31 day month return 31 - } else if month == 2 && date.isInLeapYear { + } else if month == 2, date.isInLeapYear { // February with leap year return 29 - } else if month == 2 && !date.isInLeapYear { + } else if month == 2, !date.isInLeapYear { // February without leap year return 28 } else { @@ -127,7 +126,7 @@ public extension Date { var components = DateComponents() components.year = chunk.years components.month = chunk.months - components.day = chunk.days + (chunk.weeks*7) + components.day = chunk.days + (chunk.weeks * 7) components.hour = chunk.hours components.minute = chunk.minutes components.second = chunk.seconds @@ -148,7 +147,7 @@ public extension Date { var components = DateComponents() components.year = -chunk.years components.month = -chunk.months - components.day = -(chunk.days + (chunk.weeks*7)) + components.day = -(chunk.days + (chunk.weeks * 7)) components.hour = -chunk.hours components.minute = -chunk.minutes components.second = -chunk.seconds @@ -175,14 +174,13 @@ public extension Date { * Operator overload for adding a `TimeInterval` to a date. */ static func + (leftAddend: Date, rightAddend: Int) -> Date { - return leftAddend.addingTimeInterval((TimeInterval(rightAddend))) + return leftAddend.addingTimeInterval(TimeInterval(rightAddend)) } /** * Operator overload for subtracting a `TimeInterval` from a date. */ static func - (minuend: Date, subtrahend: Int) -> Date { - return minuend.addingTimeInterval(-(TimeInterval(subtrahend))) + return minuend.addingTimeInterval(-TimeInterval(subtrahend)) } - } diff --git a/Clocker/Dependencies/Date Additions/Date+TimeAgo.swift b/Clocker/Dependencies/Date Additions/Date+TimeAgo.swift index 734972d..a058bd7 100755 --- a/Clocker/Dependencies/Date Additions/Date+TimeAgo.swift +++ b/Clocker/Dependencies/Date Additions/Date+TimeAgo.swift @@ -13,7 +13,6 @@ import Foundation * time in String format. */ public extension Date { - // MARK: - Time Ago /** @@ -24,7 +23,7 @@ public extension Date { * * - returns String - Formatted return string */ - static func timeAgo(since date:Date) -> String { + static func timeAgo(since date: Date) -> String { return date.timeAgo(since: Date(), numericDates: false, numericTimes: false) } @@ -36,8 +35,8 @@ public extension Date { * * - returns String - Formatted return string */ - static func shortTimeAgo(since date:Date) -> String { - return date.shortTimeAgo(since:Date()) + static func shortTimeAgo(since date: Date) -> String { + return date.shortTimeAgo(since: Date()) } /** @@ -47,7 +46,7 @@ public extension Date { * - returns String - Formatted return string */ var timeAgoSinceNow: String { - return self.timeAgo(since:Date()) + return timeAgo(since: Date()) } /** @@ -57,82 +56,76 @@ public extension Date { * - returns String - Formatted return string */ var shortTimeAgoSinceNow: String { - return self.shortTimeAgo(since:Date()) + return shortTimeAgo(since: Date()) } - func timeAgo(since date:Date, numericDates: Bool = false, numericTimes: Bool = false) -> String { + func timeAgo(since date: Date, numericDates: Bool = false, numericTimes: Bool = false) -> String { let calendar = NSCalendar.current - let unitFlags = Set([.second,.minute,.hour,.day,.weekOfYear,.month,.year]) - let earliest = self.earlierDate(date) - let latest = (earliest == self) ? date : self //Should be triple equals, but not extended to Date at this time + let unitFlags = Set([.second, .minute, .hour, .day, .weekOfYear, .month, .year]) + let earliest = earlierDate(date) + let latest = (earliest == self) ? date : self // Should be triple equals, but not extended to Date at this time let components = calendar.dateComponents(unitFlags, from: earliest, to: latest) let yesterday = date.subtract(1.days) - let isYesterday = yesterday.day == self.day - - //Not Yet Implemented/Optional - //The following strings are present in the translation files but lack logic as of 2014.04.05 - //@"Today", @"This week", @"This month", @"This year" - //and @"This morning", @"This afternoon" + let isYesterday = yesterday.day == day - if (components.year! >= 2) { - return self.logicalLocalizedStringFromFormat(format: "%%d %@years ago", value: components.year!) - } else if (components.year! >= 1) { + // Not Yet Implemented/Optional + // The following strings are present in the translation files but lack logic as of 2014.04.05 + // @"Today", @"This week", @"This month", @"This year" + // and @"This morning", @"This afternoon" - if (numericDates) { + if components.year! >= 2 { + return logicalLocalizedStringFromFormat(format: "%%d %@years ago", value: components.year!) + } else if components.year! >= 1 { + if numericDates { return DateToolsLocalizedStrings("1 year ago") } return DateToolsLocalizedStrings("Last year") - } else if (components.month! >= 2) { - return self.logicalLocalizedStringFromFormat(format: "%%d %@months ago", value: components.month!) - } else if (components.month! >= 1) { - - if (numericDates) { + } else if components.month! >= 2 { + return logicalLocalizedStringFromFormat(format: "%%d %@months ago", value: components.month!) + } else if components.month! >= 1 { + if numericDates { return DateToolsLocalizedStrings("1 month ago") } return DateToolsLocalizedStrings("Last month") - } else if (components.weekOfYear! >= 2) { - return self.logicalLocalizedStringFromFormat(format: "%%d %@weeks ago", value: components.weekOfYear!) - } else if (components.weekOfYear! >= 1) { - - if (numericDates) { + } else if components.weekOfYear! >= 2 { + return logicalLocalizedStringFromFormat(format: "%%d %@weeks ago", value: components.weekOfYear!) + } else if components.weekOfYear! >= 1 { + if numericDates { return DateToolsLocalizedStrings("1 week ago") } return DateToolsLocalizedStrings("Last week") - } else if (components.day! >= 2) { - return self.logicalLocalizedStringFromFormat(format: "%%d %@days ago", value: components.day!) - } else if (isYesterday) { - if (numericDates) { + } else if components.day! >= 2 { + return logicalLocalizedStringFromFormat(format: "%%d %@days ago", value: components.day!) + } else if isYesterday { + if numericDates { return DateToolsLocalizedStrings("1 day ago") } return DateToolsLocalizedStrings("Yesterday") - } else if (components.hour! >= 2) { - return self.logicalLocalizedStringFromFormat(format: "%%d %@hours ago", value: components.hour!) - } else if (components.hour! >= 1) { - - if (numericTimes) { + } else if components.hour! >= 2 { + return logicalLocalizedStringFromFormat(format: "%%d %@hours ago", value: components.hour!) + } else if components.hour! >= 1 { + if numericTimes { return DateToolsLocalizedStrings("1 hour ago") } return DateToolsLocalizedStrings("An hour ago") - } else if (components.minute! >= 2) { - return self.logicalLocalizedStringFromFormat(format: "%%d %@minutes ago", value: components.minute!) - } else if (components.minute! >= 1) { - - if (numericTimes) { + } else if components.minute! >= 2 { + return logicalLocalizedStringFromFormat(format: "%%d %@minutes ago", value: components.minute!) + } else if components.minute! >= 1 { + if numericTimes { return DateToolsLocalizedStrings("1 minute ago") } return DateToolsLocalizedStrings("A minute ago") - } else if (components.second! >= 3) { - return self.logicalLocalizedStringFromFormat(format: "%%d %@seconds ago", value: components.second!) + } else if components.second! >= 3 { + return logicalLocalizedStringFromFormat(format: "%%d %@seconds ago", value: components.second!) } else { - - if (numericTimes) { + if numericTimes { return DateToolsLocalizedStrings("1 second ago") } @@ -140,58 +133,58 @@ public extension Date { } } - func shortTimeAgo(since date:Date) -> String { + func shortTimeAgo(since date: Date) -> String { let calendar = NSCalendar.current - let unitFlags = Set([.second,.minute,.hour,.day,.weekOfYear,.month,.year]) - let earliest = self.earlierDate(date) - let latest = (earliest == self) ? date : self //Should pbe triple equals, but not extended to Date at this time + let unitFlags = Set([.second, .minute, .hour, .day, .weekOfYear, .month, .year]) + let earliest = earlierDate(date) + let latest = (earliest == self) ? date : self // Should pbe triple equals, but not extended to Date at this time let components = calendar.dateComponents(unitFlags, from: earliest, to: latest) let yesterday = date.subtract(1.days) - let isYesterday = yesterday.day == self.day - - if (components.year! >= 1) { - return self.logicalLocalizedStringFromFormat(format: "%%d%@y", value: components.year!) - } else if (components.month! >= 1) { - return self.logicalLocalizedStringFromFormat(format: "%%d%@M", value: components.month!) - } else if (components.weekOfYear! >= 1) { - return self.logicalLocalizedStringFromFormat(format: "%%d%@w", value: components.weekOfYear!) - } else if (components.day! >= 2) { - return self.logicalLocalizedStringFromFormat(format: "%%d%@d", value: components.day!) - } else if (isYesterday) { - return self.logicalLocalizedStringFromFormat(format: "%%d%@d", value: 1) - } else if (components.hour! >= 1) { - return self.logicalLocalizedStringFromFormat(format: "%%d%@h", value: components.hour!) - } else if (components.minute! >= 1) { - return self.logicalLocalizedStringFromFormat(format: "%%d%@m", value: components.minute!) - } else if (components.second! >= 3) { - return self.logicalLocalizedStringFromFormat(format: "%%d%@s", value: components.second!) + let isYesterday = yesterday.day == day + + if components.year! >= 1 { + return logicalLocalizedStringFromFormat(format: "%%d%@y", value: components.year!) + } else if components.month! >= 1 { + return logicalLocalizedStringFromFormat(format: "%%d%@M", value: components.month!) + } else if components.weekOfYear! >= 1 { + return logicalLocalizedStringFromFormat(format: "%%d%@w", value: components.weekOfYear!) + } else if components.day! >= 2 { + return logicalLocalizedStringFromFormat(format: "%%d%@d", value: components.day!) + } else if isYesterday { + return logicalLocalizedStringFromFormat(format: "%%d%@d", value: 1) + } else if components.hour! >= 1 { + return logicalLocalizedStringFromFormat(format: "%%d%@h", value: components.hour!) + } else if components.minute! >= 1 { + return logicalLocalizedStringFromFormat(format: "%%d%@m", value: components.minute!) + } else if components.second! >= 3 { + return logicalLocalizedStringFromFormat(format: "%%d%@s", value: components.second!) } else { - return self.logicalLocalizedStringFromFormat(format: "%%d%@s", value: components.second!) - //return DateToolsLocalizedStrings(@"Now"); //string not yet translated 2014.04.05 + return logicalLocalizedStringFromFormat(format: "%%d%@s", value: components.second!) + // return DateToolsLocalizedStrings(@"Now"); //string not yet translated 2014.04.05 } } private func logicalLocalizedStringFromFormat(format: String, value: Int) -> String { - let localeFormat = String.init(format: format, getLocaleFormatUnderscoresWithValue(Double(value))) - return String.init(format: DateToolsLocalizedStrings(localeFormat), value) + let localeFormat = String(format: format, getLocaleFormatUnderscoresWithValue(Double(value))) + return String(format: DateToolsLocalizedStrings(localeFormat), value) } private func getLocaleFormatUnderscoresWithValue(_ value: Double) -> String { let localCode = Bundle.main.preferredLocalizations[0] - if (localCode == "ru" || localCode == "uk") { + if localCode == "ru" || localCode == "uk" { let XY = Int(floor(value).truncatingRemainder(dividingBy: 100)) let Y = Int(floor(value).truncatingRemainder(dividingBy: 10)) - if(Y == 0 || Y > 4 || (XY > 10 && XY < 15)) { + if Y == 0 || Y > 4 || (XY > 10 && XY < 15) { return "" } - if(Y > 1 && Y < 5 && (XY < 10 || XY > 20)) { + if Y > 1, Y < 5, XY < 10 || XY > 20 { return "_" } - if(Y == 1 && XY != 11) { + if Y == 1, XY != 11 { return "__" } } @@ -202,12 +195,12 @@ public extension Date { // MARK: - Localization private func DateToolsLocalizedStrings(_ string: String) -> String { - //let classBundle = Bundle(for:TimeChunk.self as! AnyClass.Type).resourcePath!.appending("DateTools.bundle") + // let classBundle = Bundle(for:TimeChunk.self as! AnyClass.Type).resourcePath!.appending("DateTools.bundle") - //let bundelPath = Bundle(path:classBundle)! + // let bundelPath = Bundle(path:classBundle)! #if os(Linux) - // NSLocalizedString() is not available yet, see: https://github.com/apple/swift-corelibs-foundation/blob/16f83ddcd311b768e30a93637af161676b0a5f2f/Foundation/NSData.swift - // However, a seemingly-equivalent method from NSBundle is: https://github.com/apple/swift-corelibs-foundation/blob/master/Foundation/NSBundle.swift + // NSLocalizedString() is not available yet, see: https://github.com/apple/swift-corelibs-foundation/blob/16f83ddcd311b768e30a93637af161676b0a5f2f/Foundation/NSData.swift + // However, a seemingly-equivalent method from NSBundle is: https://github.com/apple/swift-corelibs-foundation/blob/master/Foundation/NSBundle.swift return Bundle.main.localizedString(forKey: string, value: "", table: "DateTools") #else return NSLocalizedString(string, tableName: "DateTools", bundle: Bundle.dateToolsBundle(), value: "", comment: "") @@ -218,13 +211,13 @@ public extension Date { /** * Return the earlier of two dates, between self and a given date. - * + * * - parameter date: The date to compare to self * * - returns: The date that is earlier */ - func earlierDate(_ date:Date) -> Date { - return (self.timeIntervalSince1970 <= date.timeIntervalSince1970) ? self : date + func earlierDate(_ date: Date) -> Date { + return (timeIntervalSince1970 <= date.timeIntervalSince1970) ? self : date } /** @@ -234,8 +227,7 @@ public extension Date { * * - returns: The date that is later */ - func laterDate(_ date:Date) -> Date { - return (self.timeIntervalSince1970 >= date.timeIntervalSince1970) ? self : date + func laterDate(_ date: Date) -> Date { + return (timeIntervalSince1970 >= date.timeIntervalSince1970) ? self : date } - } diff --git a/Clocker/Dependencies/Date Additions/Enums.swift b/Clocker/Dependencies/Date Additions/Enums.swift index 2c26fa9..2cc566d 100755 --- a/Clocker/Dependencies/Date Additions/Enums.swift +++ b/Clocker/Dependencies/Date Additions/Enums.swift @@ -9,12 +9,12 @@ // MARK: - Enums /** - * There may come a need, say when you are making a scheduling app, when - * it might be good to know how two time periods relate to one another. - * Are they the same? Is one inside of another? All these questions may be + * There may come a need, say when you are making a scheduling app, when + * it might be good to know how two time periods relate to one another. + * Are they the same? Is one inside of another? All these questions may be * asked using the relationship methods of DTTimePeriod. * - * Further reading: [GitHub](https://github.com/MatthewYork/DateTools#relationships), + * Further reading: [GitHub](https://github.com/MatthewYork/DateTools#relationships), * [CodeProject](http://www.codeproject.com/Articles/168662/Time-Period-Library-for-NET) */ public enum Relation { @@ -48,7 +48,7 @@ public enum Interval { /** * When a time periods is lengthened or shortened, it does so anchoring one date - * of the time period and then changing the other one. There is also an option to + * of the time period and then changing the other one. There is also an option to * anchor the centerpoint of the time period, changing both the start and end dates. */ public enum Anchor { @@ -58,8 +58,8 @@ public enum Anchor { } /** - * When a time periods is lengthened or shortened, it does so anchoring one date - * of the time period and then changing the other one. There is also an option to + * When a time periods is lengthened or shortened, it does so anchoring one date + * of the time period and then changing the other one. There is also an option to * anchor the centerpoint of the time period, changing both the start and end dates. */ public enum Component { diff --git a/Clocker/Dependencies/Date Additions/Integer+DateTools.swift b/Clocker/Dependencies/Date Additions/Integer+DateTools.swift index efed5e6..a090061 100755 --- a/Clocker/Dependencies/Date Additions/Integer+DateTools.swift +++ b/Clocker/Dependencies/Date Additions/Integer+DateTools.swift @@ -9,7 +9,6 @@ import Foundation public extension Int { - // MARK: TimePeriod /** diff --git a/Clocker/Dependencies/Date Additions/TimeChunk.swift b/Clocker/Dependencies/Date Additions/TimeChunk.swift index 6decb02..956188a 100755 --- a/Clocker/Dependencies/Date Additions/TimeChunk.swift +++ b/Clocker/Dependencies/Date Additions/TimeChunk.swift @@ -11,7 +11,7 @@ import Foundation /** * TimeChunk represents an abstract collection of `DateComponent`s intended for use in date manipulation. A `TimeChunk` differs from a * TimeInterval in that the former depends on the `Calendar` class (and takes into account daylight savings, leap year, etc.) while the - * latter depends on hard, second based adjustments that are independent from calendar constructs. + * latter depends on hard, second based adjustments that are independent from calendar constructs. * * In essence, TimeChunk is meant to be a thin, more flexible layer over the `Calender` and `DateComponent` classes for ease of use. * `TimeChunk`s may be created either by calling the provided initializer or shorthand like `2.days`. TimeChunks are manipulable and combine @@ -20,7 +20,6 @@ import Foundation * For more information about the utility of TimeChunks in relation to Dates, see the `Date+Manipulations` class. */ public struct TimeChunk { - // MARK: - Variables public var seconds = 0 @@ -67,57 +66,57 @@ public struct TimeChunk { * well defined unit of time without the context of a calendar. ! */ public func to(_ unit: TimeUnits) -> Int { - if self.months != 0 { + if months != 0 { print("Months are not supported for conversion due to their uncertain number of days.") return 0 } - if (unit == .seconds) { - var total = self.seconds - total += self.minutes * 60 - total += self.hours * 60 * 60 - total += self.days * 24 * 60 * 60 - total += self.weeks * 7 * 24 * 60 * 60 - total += self.years * 365 * 24 * 60 * 60 + if unit == .seconds { + var total = seconds + total += minutes * 60 + total += hours * 60 * 60 + total += days * 24 * 60 * 60 + total += weeks * 7 * 24 * 60 * 60 + total += years * 365 * 24 * 60 * 60 return total - } else if (unit == .minutes) { - var total = self.minutes - total += self.seconds / 60 - total += self.hours * 60 - total += self.days * 24 * 60 - total += self.weeks * 7 * 24 * 60 - total += self.years * 365 * 24 * 60 + } else if unit == .minutes { + var total = minutes + total += seconds / 60 + total += hours * 60 + total += days * 24 * 60 + total += weeks * 7 * 24 * 60 + total += years * 365 * 24 * 60 return total - } else if (unit == .hours) { - var total = self.hours - let secondsToMinutes = self.seconds / 60 - total += (self.minutes + secondsToMinutes) / 60 - total += self.days * 24 - total += self.weeks * 7 * 24 - total += self.years * 365 * 24 + } else if unit == .hours { + var total = hours + let secondsToMinutes = seconds / 60 + total += (minutes + secondsToMinutes) / 60 + total += days * 24 + total += weeks * 7 * 24 + total += years * 365 * 24 return total - } else if (unit == .days) { - var total = self.days - let secondsToMinutes = self.seconds / 60 - let minutesToHours = (self.minutes + secondsToMinutes) / 60 - total += (self.hours + minutesToHours) / 24 - total += self.weeks * 7 - total += self.years * 365 + } else if unit == .days { + var total = days + let secondsToMinutes = seconds / 60 + let minutesToHours = (minutes + secondsToMinutes) / 60 + total += (hours + minutesToHours) / 24 + total += weeks * 7 + total += years * 365 return total - } else if (unit == .weeks) { - var total = self.weeks - let secondsToMinutes = self.seconds / 60 - let minutesToHours = (self.minutes + secondsToMinutes) / 60 - let hoursToDays = (self.hours + minutesToHours) / 24 - total += (self.days + hoursToDays) / 7 - total += self.years * 52 + } else if unit == .weeks { + var total = weeks + let secondsToMinutes = seconds / 60 + let minutesToHours = (minutes + secondsToMinutes) / 60 + let hoursToDays = (hours + minutesToHours) / 24 + total += (days + hoursToDays) / 7 + total += years * 52 return total - } else if (unit == .years) { - var total = self.years - let secondsToMinutes = self.seconds / 60 - let minutesToHours = (self.minutes + secondsToMinutes) / 60 - let hoursToDays = (self.hours + minutesToHours) / 24 + } else if unit == .years { + var total = years + let secondsToMinutes = seconds / 60 + let minutesToHours = (minutes + secondsToMinutes) / 60 + let hoursToDays = (hours + minutesToHours) / 24 let weeksToDays = weeks * 7 - total += (self.days + hoursToDays + weeksToDays) / 365 + total += (days + hoursToDays + weeksToDays) / 365 return total } return 0 @@ -274,5 +273,4 @@ public struct TimeChunk { invertedChunk.years = -chunk.years return invertedChunk } - } diff --git a/Clocker/Dependencies/Date Additions/TimePeriod.swift b/Clocker/Dependencies/Date Additions/TimePeriod.swift index 901fd88..c78c810 100755 --- a/Clocker/Dependencies/Date Additions/TimePeriod.swift +++ b/Clocker/Dependencies/Date Additions/TimePeriod.swift @@ -9,36 +9,34 @@ import Foundation /** - * In DateTools, time periods are represented by the TimePeriod protocol. - * Required variables and method impleementations are bound below. An inheritable + * In DateTools, time periods are represented by the TimePeriod protocol. + * Required variables and method impleementations are bound below. An inheritable * implementation of the TimePeriodProtocol is available through the TimePeriodClass * * [Visit our github page](https://github.com/MatthewYork/DateTools#time-periods) for more information. */ public protocol TimePeriodProtocol { - // MARK: - Variables /** * The start date for a TimePeriod representing the starting boundary of the time period */ - var beginning: Date? {get set} + var beginning: Date? { get set } /** * The end date for a TimePeriod representing the ending boundary of the time period */ - var end: Date? {get set} + var end: Date? { get set } } public extension TimePeriodProtocol { - // MARK: - Information /** * True if the `TimePeriod`'s duration is zero */ var isMoment: Bool { - return self.beginning == self.end + return beginning == end } /** @@ -46,8 +44,8 @@ public extension TimePeriodProtocol { * Returns the max int if beginning or end are nil. */ var years: Int { - if self.beginning != nil && self.end != nil { - return self.beginning!.yearsEarlier(than: self.end!) + if beginning != nil, end != nil { + return beginning!.yearsEarlier(than: end!) } return Int.max } @@ -57,8 +55,8 @@ public extension TimePeriodProtocol { * Returns the max int if beginning or end are nil. */ var weeks: Int { - if self.beginning != nil && self.end != nil { - return self.beginning!.weeksEarlier(than: self.end!) + if beginning != nil, end != nil { + return beginning!.weeksEarlier(than: end!) } return Int.max } @@ -68,8 +66,8 @@ public extension TimePeriodProtocol { * Returns the max int if beginning or end are nil. */ var days: Int { - if self.beginning != nil && self.end != nil { - return self.beginning!.daysEarlier(than: self.end!) + if beginning != nil, end != nil { + return beginning!.daysEarlier(than: end!) } return Int.max } @@ -79,8 +77,8 @@ public extension TimePeriodProtocol { * Returns the max int if beginning or end are nil. */ var hours: Int { - if self.beginning != nil && self.end != nil { - return self.beginning!.hoursEarlier(than: self.end!) + if beginning != nil, end != nil { + return beginning!.hoursEarlier(than: end!) } return Int.max } @@ -90,8 +88,8 @@ public extension TimePeriodProtocol { * Returns the max int if beginning or end are nil. */ var minutes: Int { - if self.beginning != nil && self.end != nil { - return self.beginning!.minutesEarlier(than: self.end!) + if beginning != nil, end != nil { + return beginning!.minutesEarlier(than: end!) } return Int.max } @@ -101,8 +99,8 @@ public extension TimePeriodProtocol { * Returns the max int if beginning or end are nil. */ var seconds: Int { - if self.beginning != nil && self.end != nil { - return self.beginning!.secondsEarlier(than: self.end!) + if beginning != nil, end != nil { + return beginning!.secondsEarlier(than: end!) } return Int.max } @@ -112,7 +110,7 @@ public extension TimePeriodProtocol { * Returns a time chunk with all zeroes if beginning or end are nil. */ var chunk: TimeChunk { - if beginning != nil && end != nil { + if beginning != nil, end != nil { return beginning!.chunkBetween(date: end!) } return TimeChunk(seconds: 0, minutes: 0, hours: 0, days: 0, weeks: 0, months: 0, years: 0) @@ -123,8 +121,8 @@ public extension TimePeriodProtocol { * `TimePeriod` as a `TimeInterval`. */ var duration: TimeInterval { - if self.beginning != nil && self.end != nil { - return abs(self.beginning!.timeIntervalSince(self.end!)) + if beginning != nil, end != nil { + return abs(beginning!.timeIntervalSince(end!)) } return TimeInterval(Double.greatestFiniteMagnitude) @@ -138,43 +136,42 @@ public extension TimePeriodProtocol { * links: * [GitHub](https://github.com/MatthewYork/DateTools#relationships), * [CodeProject](http://www.codeproject.com/Articles/168662/Time-Period-Library-for-NET) - * + * * - parameter period: The time period to compare to self - * + * * - returns: The relationship between self and the given time period */ func relation(to period: TimePeriodProtocol) -> Relation { - //Make sure that all start and end points exist for comparison - if (self.beginning != nil && self.end != nil && period.beginning != nil && period.end != nil) { - //Make sure time periods are of positive durations - if (self.beginning!.isEarlier(than: self.end!) && period.beginning!.isEarlier(than: period.end!)) { - - //Make comparisons - if (period.end!.isEarlier(than: self.beginning!)) { + // Make sure that all start and end points exist for comparison + if beginning != nil, end != nil, period.beginning != nil, period.end != nil { + // Make sure time periods are of positive durations + if beginning!.isEarlier(than: end!), period.beginning!.isEarlier(than: period.end!) { + // Make comparisons + if period.end!.isEarlier(than: beginning!) { return .after - } else if (period.end!.equals(self.beginning!)) { + } else if period.end!.equals(beginning!) { return .startTouching - } else if (period.beginning!.isEarlier(than: self.beginning!) && period.end!.isEarlier(than: self.end!)) { + } else if period.beginning!.isEarlier(than: beginning!), period.end!.isEarlier(than: end!) { return .startInside - } else if (period.beginning!.equals(self.beginning!) && period.end!.isLater(than: self.end!)) { + } else if period.beginning!.equals(beginning!), period.end!.isLater(than: end!) { return .insideStartTouching - } else if (period.beginning!.equals(self.beginning!) && period.end!.isEarlier(than: self.end!)) { + } else if period.beginning!.equals(beginning!), period.end!.isEarlier(than: end!) { return .enclosingStartTouching - } else if (period.beginning!.isLater(than: self.beginning!) && period.end!.isEarlier(than: self.end!)) { + } else if period.beginning!.isLater(than: beginning!), period.end!.isEarlier(than: end!) { return .enclosing - } else if (period.beginning!.isLater(than: self.beginning!) && period.end!.equals(self.end!)) { + } else if period.beginning!.isLater(than: beginning!), period.end!.equals(end!) { return .enclosingEndTouching - } else if (period.beginning!.equals(self.beginning!) && period.end!.equals(self.end!)) { + } else if period.beginning!.equals(beginning!), period.end!.equals(end!) { return .exactMatch - } else if (period.beginning!.isEarlier(than: self.beginning!) && period.end!.isLater(than: self.end!)) { + } else if period.beginning!.isEarlier(than: beginning!), period.end!.isLater(than: end!) { return .inside - } else if (period.beginning!.isEarlier(than: self.beginning!) && period.end!.equals(self.end!)) { + } else if period.beginning!.isEarlier(than: beginning!), period.end!.equals(end!) { return .insideEndTouching - } else if (period.beginning!.isEarlier(than: self.end!) && period.end!.isLater(than: self.end!)) { + } else if period.beginning!.isEarlier(than: end!), period.end!.isLater(than: end!) { return .endInside - } else if (period.beginning!.equals(self.end!) && period.end!.isLater(than: self.end!)) { + } else if period.beginning!.equals(end!), period.end!.isLater(than: end!) { return .endTouching - } else if (period.beginning!.isLater(than: self.end!)) { + } else if period.beginning!.isLater(than: end!) { return .before } } @@ -192,7 +189,7 @@ public extension TimePeriodProtocol { * - returns: True if the periods are the same */ func equals(_ period: TimePeriodProtocol) -> Bool { - return self.beginning == period.beginning && self.end == period.end + return beginning == period.beginning && end == period.end } /** @@ -204,7 +201,7 @@ public extension TimePeriodProtocol { * - returns: True if self is inside of the given `TimePeriod` */ func isInside(of period: TimePeriodProtocol) -> Bool { - return period.beginning!.isEarlierThanOrEqual(to: self.beginning!) && period.end!.isLaterThanOrEqual(to: self.end!) + return period.beginning!.isEarlierThanOrEqual(to: beginning!) && period.end!.isLaterThanOrEqual(to: end!) } /** @@ -216,10 +213,10 @@ public extension TimePeriodProtocol { * - returns: True if the given `TimePeriod` is inside of self */ func contains(_ date: Date, interval: Interval) -> Bool { - if (interval == .open) { - return self.beginning!.isEarlier(than: date) && self.end!.isLater(than: date) - } else if (interval == .closed) { - return (self.beginning!.isEarlierThanOrEqual(to: date) && self.end!.isLaterThanOrEqual(to: date)) + if interval == .open { + return beginning!.isEarlier(than: date) && end!.isLater(than: date) + } else if interval == .closed { + return (beginning!.isEarlierThanOrEqual(to: date) && end!.isLaterThanOrEqual(to: date)) } return false @@ -234,7 +231,7 @@ public extension TimePeriodProtocol { * - returns: True if the given `TimePeriod` is inside of self */ func contains(_ period: TimePeriodProtocol) -> Bool { - return self.beginning!.isEarlierThanOrEqual(to: period.beginning!) && self.end!.isLaterThanOrEqual(to: period.end!) + return beginning!.isEarlierThanOrEqual(to: period.beginning!) && end!.isLaterThanOrEqual(to: period.end!) } /** @@ -245,16 +242,16 @@ public extension TimePeriodProtocol { * - returns: True if there is a period of time that is shared by both `TimePeriod`s */ func overlaps(with period: TimePeriodProtocol) -> Bool { - //Outside -> Inside - if (period.beginning!.isEarlier(than: self.beginning!) && period.end!.isLater(than: self.beginning!)) { + // Outside -> Inside + if period.beginning!.isEarlier(than: beginning!), period.end!.isLater(than: beginning!) { return true } - //Enclosing - else if (period.beginning!.isLaterThanOrEqual(to: self.beginning!) && period.end!.isEarlierThanOrEqual(to: self.end!)) { + // Enclosing + else if period.beginning!.isLaterThanOrEqual(to: beginning!), period.end!.isEarlierThanOrEqual(to: end!) { return true } - //Inside -> Out - else if(period.beginning!.isEarlier(than: self.end!) && period.end!.isLater(than: self.end!)) { + // Inside -> Out + else if period.beginning!.isEarlier(than: end!), period.end!.isLater(than: end!) { return true } return false @@ -268,7 +265,7 @@ public extension TimePeriodProtocol { * - returns: True if there is a period of time or moment that is shared by both `TimePeriod`s */ func intersects(with period: TimePeriodProtocol) -> Bool { - return self.relation(to: period) != .after && self.relation(to: period) != .before + return relation(to: period) != .after && relation(to: period) != .before } /** @@ -279,7 +276,7 @@ public extension TimePeriodProtocol { * - returns: True if there is a period of time between self and the given `TimePeriod` not contained by either period */ func hasGap(between period: TimePeriodProtocol) -> Bool { - return self.isBefore(period: period) || self.isAfter(period: period) + return isBefore(period: period) || isAfter(period: period) } /** @@ -290,10 +287,10 @@ public extension TimePeriodProtocol { * - returns: The gap between the periods. Zero if there is no gap. */ func gap(between period: TimePeriodProtocol) -> TimeInterval { - if (self.end!.isEarlier(than: period.beginning!)) { - return abs(self.end!.timeIntervalSince(period.beginning!)) - } else if (period.end!.isEarlier(than: self.beginning!)) { - return abs(period.end!.timeIntervalSince(self.beginning!)) + if end!.isEarlier(than: period.beginning!) { + return abs(end!.timeIntervalSince(period.beginning!)) + } else if period.end!.isEarlier(than: beginning!) { + return abs(period.end!.timeIntervalSince(beginning!)) } return 0 } @@ -307,8 +304,8 @@ public extension TimePeriodProtocol { * - returns: The gap between the periods, zero if there is no gap */ func gap(between period: TimePeriodProtocol) -> TimeChunk? { - if self.end != nil && period.beginning != nil { - return (self.end?.chunkBetween(date: period.beginning!))! + if end != nil, period.beginning != nil { + return (end?.chunkBetween(date: period.beginning!))! } return nil } @@ -321,7 +318,7 @@ public extension TimePeriodProtocol { * - returns: True if self is after the given `TimePeriod` */ func isAfter(period: TimePeriodProtocol) -> Bool { - return self.relation(to: period) == .after + return relation(to: period) == .after } /** @@ -332,7 +329,7 @@ public extension TimePeriodProtocol { * - returns: True if self is after the given `TimePeriod` */ func isBefore(period: TimePeriodProtocol) -> Bool { - return self.relation(to: period) == .before + return relation(to: period) == .before } // MARK: - Shifts @@ -345,8 +342,8 @@ public extension TimePeriodProtocol { * - parameter timeInterval: The time interval to shift the period by */ mutating func shift(by timeInterval: TimeInterval) { - self.beginning?.addTimeInterval(timeInterval) - self.end?.addTimeInterval(timeInterval) + beginning?.addTimeInterval(timeInterval) + end?.addTimeInterval(timeInterval) } /** @@ -355,8 +352,8 @@ public extension TimePeriodProtocol { * - parameter chunk: The time chunk to shift the period by */ mutating func shift(by chunk: TimeChunk) { - self.beginning = self.beginning?.add(chunk) - self.end = self.end?.add(chunk) + beginning = beginning?.add(chunk) + end = end?.add(chunk) } // MARK: - Lengthen / Shorten @@ -372,12 +369,12 @@ public extension TimePeriodProtocol { mutating func lengthen(by timeInterval: TimeInterval, at anchor: Anchor) { switch anchor { case .beginning: - self.end = self.end?.addingTimeInterval(timeInterval) + end = end?.addingTimeInterval(timeInterval) case .center: - self.beginning = self.beginning?.addingTimeInterval(-timeInterval/2.0) - self.end = self.end?.addingTimeInterval(timeInterval/2.0) + beginning = beginning?.addingTimeInterval(-timeInterval / 2.0) + end = end?.addingTimeInterval(timeInterval / 2.0) case .end: - self.beginning = self.beginning?.addingTimeInterval(-timeInterval) + beginning = beginning?.addingTimeInterval(-timeInterval) } } @@ -390,12 +387,12 @@ public extension TimePeriodProtocol { mutating func lengthen(by chunk: TimeChunk, at anchor: Anchor) { switch anchor { case .beginning: - self.end = self.end?.add(chunk) + end = end?.add(chunk) case .center: // Do not lengthen by TimeChunk at center print("Mutation via chunk from center anchor is not supported.") case .end: - self.beginning = self.beginning?.subtract(chunk) + beginning = beginning?.subtract(chunk) } } @@ -408,12 +405,12 @@ public extension TimePeriodProtocol { mutating func shorten(by timeInterval: TimeInterval, at anchor: Anchor) { switch anchor { case .beginning: - self.end = self.end?.addingTimeInterval(-timeInterval) + end = end?.addingTimeInterval(-timeInterval) case .center: - self.beginning = self.beginning?.addingTimeInterval(timeInterval/2.0) - self.end = self.end?.addingTimeInterval(-timeInterval/2.0) + beginning = beginning?.addingTimeInterval(timeInterval / 2.0) + end = end?.addingTimeInterval(-timeInterval / 2.0) case .end: - self.beginning = self.beginning?.addingTimeInterval(timeInterval) + beginning = beginning?.addingTimeInterval(timeInterval) } } @@ -426,26 +423,26 @@ public extension TimePeriodProtocol { mutating func shorten(by chunk: TimeChunk, at anchor: Anchor) { switch anchor { case .beginning: - self.end = self.end?.subtract(chunk) + end = end?.subtract(chunk) case .center: // Do not shorten by TimeChunk at center print("Mutation via chunk from center anchor is not supported.") case .end: - self.beginning = self.beginning?.add(chunk) + beginning = beginning?.add(chunk) } } } /** * In DateTools, time periods are represented by the case TimePeriod class - * and come with a suite of initializaiton, manipulation, and comparison methods + * and come with a suite of initializaiton, manipulation, and comparison methods * to make working with them a breeze. * * [Visit our github page](https://github.com/MatthewYork/DateTools#time-periods) for more information. */ open class TimePeriod: TimePeriodProtocol { - // MARK: - Variables + /** * The start date for a TimePeriod representing the starting boundary of the time period */ @@ -458,9 +455,7 @@ open class TimePeriod: TimePeriodProtocol { // MARK: - Initializers - init() { - - } + init() {} init(beginning: Date?, end: Date?) { self.beginning = beginning @@ -469,27 +464,27 @@ open class TimePeriod: TimePeriodProtocol { init(beginning: Date, duration: TimeInterval) { self.beginning = beginning - self.end = beginning + duration + end = beginning + duration } init(end: Date, duration: TimeInterval) { self.end = end - self.beginning = end.addingTimeInterval(-duration) + beginning = end.addingTimeInterval(-duration) } init(beginning: Date, chunk: TimeChunk) { self.beginning = beginning - self.end = beginning + chunk + end = beginning + chunk } init(end: Date, chunk: TimeChunk) { self.end = end - self.beginning = end - chunk + beginning = end - chunk } init(chunk: TimeChunk) { - self.beginning = Date() - self.end = self.beginning?.add(chunk) + beginning = Date() + end = beginning?.add(chunk) } // MARK: - Shifted @@ -503,8 +498,8 @@ open class TimePeriod: TimePeriodProtocol { */ func shifted(by timeInterval: TimeInterval) -> TimePeriod { let timePeriod = TimePeriod() - timePeriod.beginning = self.beginning?.addingTimeInterval(timeInterval) - timePeriod.end = self.end?.addingTimeInterval(timeInterval) + timePeriod.beginning = beginning?.addingTimeInterval(timeInterval) + timePeriod.end = end?.addingTimeInterval(timeInterval) return timePeriod } @@ -517,8 +512,8 @@ open class TimePeriod: TimePeriodProtocol { */ func shifted(by chunk: TimeChunk) -> TimePeriod { let timePeriod = TimePeriod() - timePeriod.beginning = self.beginning?.add(chunk) - timePeriod.end = self.end?.add(chunk) + timePeriod.beginning = beginning?.add(chunk) + timePeriod.end = end?.add(chunk) return timePeriod } @@ -538,14 +533,14 @@ open class TimePeriod: TimePeriodProtocol { let timePeriod = TimePeriod() switch anchor { case .beginning: - timePeriod.beginning = self.beginning - timePeriod.end = self.end?.addingTimeInterval(timeInterval) + timePeriod.beginning = beginning + timePeriod.end = end?.addingTimeInterval(timeInterval) case .center: - timePeriod.beginning = self.beginning?.addingTimeInterval(-timeInterval) - timePeriod.end = self.end?.addingTimeInterval(timeInterval) + timePeriod.beginning = beginning?.addingTimeInterval(-timeInterval) + timePeriod.end = end?.addingTimeInterval(timeInterval) case .end: - timePeriod.beginning = self.beginning?.addingTimeInterval(-timeInterval) - timePeriod.end = self.end + timePeriod.beginning = beginning?.addingTimeInterval(-timeInterval) + timePeriod.end = end } return timePeriod @@ -590,8 +585,8 @@ open class TimePeriod: TimePeriodProtocol { timePeriod.beginning = beginning timePeriod.end = end?.addingTimeInterval(-timeInterval) case .center: - timePeriod.beginning = beginning?.addingTimeInterval(-timeInterval/2) - timePeriod.end = end?.addingTimeInterval(timeInterval/2) + timePeriod.beginning = beginning?.addingTimeInterval(-timeInterval / 2) + timePeriod.end = end?.addingTimeInterval(timeInterval / 2) case .end: timePeriod.beginning = beginning?.addingTimeInterval(timeInterval) timePeriod.end = end @@ -629,7 +624,7 @@ open class TimePeriod: TimePeriodProtocol { /** * Operator overload for checking if two `TimePeriod`s are equal */ - static func ==(leftAddend: TimePeriod, rightAddend: TimePeriod) -> Bool { + static func == (leftAddend: TimePeriod, rightAddend: TimePeriod) -> Bool { return leftAddend.equals(rightAddend) } @@ -637,14 +632,14 @@ open class TimePeriod: TimePeriodProtocol { /** * Operator overload for lengthening a `TimePeriod` by a `TimeInterval` */ - static func +(leftAddend: TimePeriod, rightAddend: TimeInterval) -> TimePeriod { + static func + (leftAddend: TimePeriod, rightAddend: TimeInterval) -> TimePeriod { return leftAddend.lengthened(by: rightAddend, at: .beginning) } /** * Operator overload for lengthening a `TimePeriod` by a `TimeChunk` */ - static func +(leftAddend: TimePeriod, rightAddend: TimeChunk) -> TimePeriod { + static func + (leftAddend: TimePeriod, rightAddend: TimeChunk) -> TimePeriod { return leftAddend.lengthened(by: rightAddend, at: .beginning) } @@ -652,21 +647,21 @@ open class TimePeriod: TimePeriodProtocol { /** * Operator overload for shortening a `TimePeriod` by a `TimeInterval` */ - static func -(minuend: TimePeriod, subtrahend: TimeInterval) -> TimePeriod { + static func - (minuend: TimePeriod, subtrahend: TimeInterval) -> TimePeriod { return minuend.shortened(by: subtrahend, at: .beginning) } /** * Operator overload for shortening a `TimePeriod` by a `TimeChunk` */ - static func -(minuend: TimePeriod, subtrahend: TimeChunk) -> TimePeriod { + static func - (minuend: TimePeriod, subtrahend: TimeChunk) -> TimePeriod { return minuend.shortened(by: subtrahend, at: .beginning) } /** * Operator overload for checking if a `TimePeriod` is equal to a `TimePeriodProtocol` */ - static func ==(left: TimePeriod, right: TimePeriodProtocol) -> Bool { + static func == (left: TimePeriod, right: TimePeriodProtocol) -> Bool { return left.equals(right) } } diff --git a/Clocker/Dependencies/Date Additions/TimePeriodChain.swift b/Clocker/Dependencies/Date Additions/TimePeriodChain.swift index 0df3f8a..54df9bd 100755 --- a/Clocker/Dependencies/Date Additions/TimePeriodChain.swift +++ b/Clocker/Dependencies/Date Additions/TimePeriodChain.swift @@ -11,14 +11,13 @@ import Foundation /** * Time period chains serve as a tightly coupled set of time periods. They are * always organized by start and end date, and have their own characteristics like - * a StartDate and EndDate that are extrapolated from the time periods within. Time - * period chains do not allow overlaps within their set of time periods. This type of + * a StartDate and EndDate that are extrapolated from the time periods within. Time + * period chains do not allow overlaps within their set of time periods. This type of * group is ideal for modeling schedules like sequential meetings or appointments. * * [Visit our github page](https://github.com/MatthewYork/DateTools#time-period-chains) for more information. */ open class TimePeriodChain: TimePeriodGroup { - // MARK: - Chain Existence Manipulation /** @@ -28,12 +27,12 @@ open class TimePeriodChain: TimePeriodGroup { * - parameter period: TimePeriodProtocol to add to the collection */ public func append(_ period: TimePeriodProtocol) { - let beginning = (self.periods.isEmpty == false) ? self.periods.last!.end! : period.beginning + let beginning = (periods.isEmpty == false) ? periods.last!.end! : period.beginning let newPeriod = TimePeriod(beginning: beginning!, duration: period.duration) - self.periods.append(newPeriod) + periods.append(newPeriod) - //Update updateExtremes + // Update updateExtremes if periods.count == 1 { _beginning = period.beginning _end = period.end @@ -50,12 +49,12 @@ open class TimePeriodChain: TimePeriodGroup { */ public func append(contentsOf group: G) { for period in group.periods { - let beginning = (self.periods.isEmpty == false) ? self.periods.last!.end! : period.beginning + let beginning = (periods.isEmpty == false) ? periods.last!.end! : period.beginning let newPeriod = TimePeriod(beginning: beginning!, duration: period.duration) - self.periods.append(newPeriod) + periods.append(newPeriod) - //Update updateExtremes + // Update updateExtremes if periods.count == 1 { _beginning = period.beginning _end = period.end @@ -72,23 +71,23 @@ open class TimePeriodChain: TimePeriodGroup { * - parameter index: Index to insert period at */ public func insert(_ period: TimePeriodProtocol, at index: Int) { - //Check for special zero case which takes the beginning date - if index == 0 && period.beginning != nil && period.end != nil { - //Insert new period + // Check for special zero case which takes the beginning date + if index == 0, period.beginning != nil, period.end != nil { + // Insert new period periods.insert(period, at: index) - } else if period.beginning != nil && period.end != nil { - //Insert new period + } else if period.beginning != nil, period.end != nil { + // Insert new period periods.insert(period, at: index) } else { print("All TimePeriods in a TimePeriodChain must contain a defined start and end date") return } - //Shift all periods after inserted period - for i in 0.. index && i > 0 { + // Shift all periods after inserted period + for i in 0 ..< periods.count { + if i > index, i > 0 { let currentPeriod = TimePeriod(beginning: period.beginning, end: period.end) - periods[i].beginning = periods[i-1].end + periods[i].beginning = periods[i - 1].end periods[i].end = periods[i].beginning!.addingTimeInterval(currentPeriod.duration) } } @@ -102,14 +101,14 @@ open class TimePeriodChain: TimePeriodGroup { * - parameter at: The index in the collection to remove */ public func remove(at index: Int) { - //Retrieve duration of period to be removed + // Retrieve duration of period to be removed let duration = periods[index].duration - //Remove period + // Remove period periods.remove(at: index) - //Shift all periods after inserted period - for i in index.. TimePeriodProtocol? { - let period = self.periods.popLast() + let period = periods.popLast() updateExtremes() return period @@ -172,7 +171,7 @@ open class TimePeriodChain: TimePeriodGroup { /** * Operator overload for comparing `TimePeriodChain`s to each other */ - public static func ==(left: TimePeriodChain, right: TimePeriodChain) -> Bool { + public static func == (left: TimePeriodChain, right: TimePeriodChain) -> Bool { return left.equals(right) } } diff --git a/Clocker/Dependencies/Date Additions/TimePeriodCollection.swift b/Clocker/Dependencies/Date Additions/TimePeriodCollection.swift index 5fbaa60..349d1ce 100755 --- a/Clocker/Dependencies/Date Additions/TimePeriodCollection.swift +++ b/Clocker/Dependencies/Date Additions/TimePeriodCollection.swift @@ -17,13 +17,12 @@ import Foundation * [Visit our github page](https://github.com/MatthewYork/DateTools#time-period-collections) for more information. */ open class TimePeriodCollection: TimePeriodGroup { - // MARK: - Collection Manipulation /** * Append a TimePeriodProtocol to the periods array and check if the Collection's * beginning and end should change. - * + * * - parameter period: TimePeriodProtocol to add to the collection */ public func append(_ period: TimePeriodProtocol) { @@ -93,12 +92,12 @@ open class TimePeriodCollection: TimePeriodGroup { * Sort periods array in place by beginning */ public func sortByBeginning() { - self.sort { (period1: TimePeriodProtocol, period2: TimePeriodProtocol) -> Bool in - if period1.beginning == nil && period2.beginning == nil { + sort { (period1: TimePeriodProtocol, period2: TimePeriodProtocol) -> Bool in + if period1.beginning == nil, period2.beginning == nil { return false - } else if (period1.beginning == nil) { + } else if period1.beginning == nil { return true - } else if (period2.beginning == nil) { + } else if period2.beginning == nil { return false } else { return period2.beginning! < period1.beginning! @@ -110,7 +109,7 @@ open class TimePeriodCollection: TimePeriodGroup { * Sort periods array in place */ public func sort(by areInIncreasingOrder: (TimePeriodProtocol, TimePeriodProtocol) -> Bool) { - self.periods.sort(by: areInIncreasingOrder) + periods.sort(by: areInIncreasingOrder) } // New collection @@ -120,12 +119,12 @@ open class TimePeriodCollection: TimePeriodGroup { * - returns: Collection with sorted periods */ public func sortedByBeginning() -> TimePeriodCollection { - let array = self.periods.sorted { (period1: TimePeriodProtocol, period2: TimePeriodProtocol) -> Bool in - if period1.beginning == nil && period2.beginning == nil { + let array = periods.sorted { (period1: TimePeriodProtocol, period2: TimePeriodProtocol) -> Bool in + if period1.beginning == nil, period2.beginning == nil { return false - } else if (period1.beginning == nil) { + } else if period1.beginning == nil { return true - } else if (period2.beginning == nil) { + } else if period2.beginning == nil { return false } else { return period2.beginning! < period1.beginning! @@ -143,7 +142,7 @@ open class TimePeriodCollection: TimePeriodGroup { */ public func sorted(by areInIncreasingOrder: (TimePeriodProtocol, TimePeriodProtocol) -> Bool) -> TimePeriodCollection { let collection = TimePeriodCollection() - collection.append(self.periods.sorted(by: areInIncreasingOrder)) + collection.append(periods.sorted(by: areInIncreasingOrder)) return collection } @@ -161,14 +160,14 @@ open class TimePeriodCollection: TimePeriodGroup { public func allInside(in period: TimePeriodProtocol) -> TimePeriodCollection { let collection = TimePeriodCollection() // Filter by period - collection.periods = self.periods.filter({ (timePeriod: TimePeriodProtocol) -> Bool in - return timePeriod.isInside(of: period) - }) + collection.periods = periods.filter { (timePeriod: TimePeriodProtocol) -> Bool in + timePeriod.isInside(of: period) + } return collection } /** - * Returns from the `TimePeriodCollection` a sub-collection of `TimePeriod`s containing + * Returns from the `TimePeriodCollection` a sub-collection of `TimePeriod`s containing * the given date. * * - parameter date: The date to compare each period to @@ -178,14 +177,14 @@ open class TimePeriodCollection: TimePeriodGroup { public func periodsIntersected(by date: Date) -> TimePeriodCollection { let collection = TimePeriodCollection() // Filter by period - collection.periods = self.periods.filter({ (timePeriod: TimePeriodProtocol) -> Bool in - return timePeriod.contains(date, interval: .closed) - }) + collection.periods = periods.filter { (timePeriod: TimePeriodProtocol) -> Bool in + timePeriod.contains(date, interval: .closed) + } return collection } /** - * Returns from the `TimePeriodCollection` a sub-collection of `TimePeriod`s + * Returns from the `TimePeriodCollection` a sub-collection of `TimePeriod`s * containing either the start date or the end date--or both--of the given `TimePeriod`. * * - parameter period: The period to compare each other period to @@ -194,10 +193,10 @@ open class TimePeriodCollection: TimePeriodGroup { */ public func periodsIntersected(by period: TimePeriodProtocol) -> TimePeriodCollection { let collection = TimePeriodCollection() - //Filter by periop - collection.periods = self.periods.filter({ (timePeriod: TimePeriodProtocol) -> Bool in - return timePeriod.intersects(with: period) - }) + // Filter by periop + collection.periods = periods.filter { (timePeriod: TimePeriodProtocol) -> Bool in + timePeriod.intersects(with: period) + } return collection } @@ -219,22 +218,21 @@ open class TimePeriodCollection: TimePeriodGroup { /** * Operator overload for comparing `TimePeriodCollection`s to each other */ - public static func ==(left: TimePeriodCollection, right: TimePeriodCollection) -> Bool { + public static func == (left: TimePeriodCollection, right: TimePeriodCollection) -> Bool { return left.equals(right) } // MARK: - Helpers internal func updateExtremes(period: TimePeriodProtocol) { - //Check incoming period against previous beginning and end date - if self.count == 1 { + // Check incoming period against previous beginning and end date + if count == 1 { _beginning = period.beginning _end = period.end } else { _beginning = nilOrEarlier(date1: _beginning, date2: period.beginning) _end = nilOrLater(date1: _end, date2: period.end) } - } internal func updateExtremes() { @@ -244,7 +242,7 @@ open class TimePeriodCollection: TimePeriodGroup { } else { _beginning = periods[0].beginning _end = periods[0].end - for i in 1.. Bool { - return containSameElements(array1: self.periods, group.periods) + return containSameElements(array1: periods, group.periods) } // MARK: - Sequence Protocol - public func makeIterator() -> IndexingIterator> { + public func makeIterator() -> IndexingIterator<[TimePeriodProtocol]> { return periods.makeIterator() } @@ -105,9 +102,7 @@ open class TimePeriodGroup: Sequence { } subscript(index: Int) -> TimePeriodProtocol { - get { - return periods[index] - } + return periods[index] } internal func reduce(_ initialResult: Result, _ nextPartialResult: (Result, TimePeriodProtocol) throws -> Result) rethrows -> Result { @@ -120,28 +115,28 @@ open class TimePeriodGroup: Sequence { } var compArray1: [TimePeriodProtocol] = array1.sorted { (period1: TimePeriodProtocol, period2: TimePeriodProtocol) -> Bool in - if period1.beginning == nil && period2.beginning == nil { + if period1.beginning == nil, period2.beginning == nil { return false - } else if (period1.beginning == nil) { + } else if period1.beginning == nil { return true - } else if (period2.beginning == nil) { + } else if period2.beginning == nil { return false } else { return period2.beginning! < period1.beginning! } } var compArray2: [TimePeriodProtocol] = array2.sorted { (period1: TimePeriodProtocol, period2: TimePeriodProtocol) -> Bool in - if period1.beginning == nil && period2.beginning == nil { + if period1.beginning == nil, period2.beginning == nil { return false - } else if (period1.beginning == nil) { + } else if period1.beginning == nil { return true - } else if (period2.beginning == nil) { + } else if period2.beginning == nil { return false } else { return period2.beginning! < period1.beginning! } } - for x in 0.. Date? { + private func calculate(_ sunriseSunset: SunriseSunset, for date: Date, and zenith: Zenith) -> Date? { guard let utcTimezone = TimeZone(identifier: "UTC") else { return nil } // Get the day of the year @@ -147,7 +146,7 @@ public struct Solar { if shouldBeYesterday { setDate = Date(timeInterval: -(60 * 60 * 24), since: date) } else if shouldBeTomorrow { - setDate = Date(timeInterval: (60 * 60 * 24), since: date) + setDate = Date(timeInterval: 60 * 60 * 24, since: date) } else { setDate = date } @@ -162,7 +161,7 @@ public struct Solar { } /// Normalises a value between 0 and `maximum`, by adding or subtracting `maximum` - fileprivate func normalise(_ value: Double, withMaximum maximum: Double) -> Double { + private func normalise(_ value: Double, withMaximum maximum: Double) -> Double { var value = value if value < 0 { @@ -175,24 +174,22 @@ public struct Solar { return value } - } extension Solar { - /// Whether the location specified by the `latitude` and `longitude` is in daytime on `date` /// - Complexity: O(1) public var isDaytime: Bool { guard let sunrise = sunrise, let sunset = sunset - else { - return false + else { + return false } let beginningOfDay = sunrise.timeIntervalSince1970 let endOfDay = sunset.timeIntervalSince1970 - let currentTime = self.date.timeIntervalSince1970 + let currentTime = date.timeIntervalSince1970 let isSunriseOrLater = currentTime >= beginningOfDay let isBeforeSunset = currentTime < endOfDay @@ -205,7 +202,6 @@ extension Solar { public var isNighttime: Bool { return !isDaytime } - } // MARK: - Helper extensions diff --git a/Clocker/Events and Reminders/CalendarHandler.swift b/Clocker/Events and Reminders/CalendarHandler.swift index 4c8b01f..c3d1311 100644 --- a/Clocker/Events and Reminders/CalendarHandler.swift +++ b/Clocker/Events and Reminders/CalendarHandler.swift @@ -94,17 +94,17 @@ extension EventCenter { let relevantEvents = filteredEvents[autoupdatingCalendar.startOfDay(for: Date())] ?? [] - let filteredEvent = relevantEvents.filter({ + let filteredEvent = relevantEvents.filter { $0.event.isAllDay == false && $0.event.startDate.timeIntervalSinceNow > 0 - }).first + }.first if let firstEvent = filteredEvent { return firstEvent.event } - let filteredAllDayEvent = relevantEvents.filter({ + let filteredAllDayEvent = relevantEvents.filter { $0.isAllDay - }).first + }.first return filteredAllDayEvent?.event } @@ -113,7 +113,7 @@ extension EventCenter { store.requestAccess(to: entity) { [weak self] granted, _ in // On successful granting of calendar permission, we default to showing events from all calendars - if let `self` = self, entity == .event, granted { + if let self = self, entity == .event, granted { self.saveDefaultIdentifiersList() } @@ -149,7 +149,7 @@ extension EventCenter { func saveDefaultIdentifiersList() { OperationQueue.main.addOperation { [weak self] in - guard let `self` = self else { return } + guard let self = self else { return } let allCalendars = self.retrieveAllCalendarIdentifiers() if !allCalendars.isEmpty { @@ -162,7 +162,7 @@ extension EventCenter { func retrieveAllCalendarIdentifiers() -> [String] { return store.calendars(for: .event).map { (calendar) -> String in - return calendar.calendarIdentifier + calendar.calendarIdentifier } } @@ -172,7 +172,7 @@ extension EventCenter { guard let convertedDate = calendar?.date(byAdding: dateComps, to: Date(), options: NSCalendar.Options.matchFirst) else { - return Date() + return Date() } return convertedDate } @@ -211,7 +211,6 @@ extension EventCenter { // We map eachDate to array of events happening on that day for event in events where shouldSkipEvent(event) == false { - // Iterate through the days this event spans. We only care about // days for this event that are between startDate and endDate let eventStartDate = event.startDate as NSDate diff --git a/Clocker/Events and Reminders/EventCenter.swift b/Clocker/Events and Reminders/EventCenter.swift index 5a04cb7..287f30c 100644 --- a/Clocker/Events and Reminders/EventCenter.swift +++ b/Clocker/Events and Reminders/EventCenter.swift @@ -29,7 +29,7 @@ class EventCenter: NSObject { object: nil) } - @objc func eventStoreDidChange(_ sender: Any) { + @objc func eventStoreDidChange(_: Any) { refetchAll() } diff --git a/Clocker/Events and Reminders/RemindersHandler.swift b/Clocker/Events and Reminders/RemindersHandler.swift index 5b00d8f..1c43b79 100644 --- a/Clocker/Events and Reminders/RemindersHandler.swift +++ b/Clocker/Events and Reminders/RemindersHandler.swift @@ -3,7 +3,6 @@ import EventKit extension EventCenter { - // MARK: Private helper methods private func retrieveCalendar() -> EKCalendar? { @@ -11,7 +10,7 @@ extension EventCenter { let calendars = store.calendars(for: .reminder) let calendarTitle = "Clocker Reminders" let predicate = NSPredicate(format: "title matches %@", calendarTitle) - let filtered = calendars.filter({ predicate.evaluate(with: $0) }) + let filtered = calendars.filter { predicate.evaluate(with: $0) } if !filtered.isEmpty { calendar = filtered.first @@ -83,7 +82,7 @@ extension EventCenter { private func addAlarmIfNeccesary(for event: EKReminder, _ selection: Int) { if selection != 0 { - var offset: TimeInterval = 0 + var offset: TimeInterval = 0 switch selection { case 2: offset = -300 diff --git a/Clocker/Menu Bar/MenubarHandler.swift b/Clocker/Menu Bar/MenubarHandler.swift index 5fc3555..e96eefa 100644 --- a/Clocker/Menu Bar/MenubarHandler.swift +++ b/Clocker/Menu Bar/MenubarHandler.swift @@ -5,7 +5,6 @@ import EventKit class MenubarHandler: NSObject { @objc func titleForMenubar() -> String? { - if let nextEvent = checkForUpcomingEvents() { return nextEvent } @@ -20,11 +19,11 @@ class MenubarHandler: NSObject { } if menubarTitles.isEmpty == false { - let titles = menubarTitles.map({ (data) -> String? in + let titles = menubarTitles.map { (data) -> String? in let timezone = TimezoneData.customObject(from: data) let operationsObject = TimezoneDataOperations(with: timezone!) return "\(operationsObject.menuTitle().trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines))" - }) + } let titlesStringified = titles.compactMap { $0 } return titlesStringified.joined(separator: " ") @@ -34,9 +33,7 @@ class MenubarHandler: NSObject { } private func checkForUpcomingEvents() -> String? { - if DataStore.shared().shouldDisplay(.showMeetingInMenubar) { - let filteredDates = EventCenter.sharedCenter().eventsForDate let autoupdatingCal = EventCenter.sharedCenter().autoupdatingCalendar guard let events = filteredDates[autoupdatingCal.startOfDay(for: Date())] else { @@ -44,13 +41,10 @@ class MenubarHandler: NSObject { } for event in events { - - if event.event.startDate.timeIntervalSinceNow > 0 && !event.isAllDay { - + if event.event.startDate.timeIntervalSinceNow > 0, !event.isAllDay { let timeForEventToStart = event.event.startDate.timeIntervalSinceNow / 60 if timeForEventToStart > 30 { - print("Our next event: \(event.event.title ?? "Error") starts in \(timeForEventToStart) mins") continue diff --git a/Clocker/Menu Bar/StatusContainerView.swift b/Clocker/Menu Bar/StatusContainerView.swift index f5e3891..d3ca6b5 100644 --- a/Clocker/Menu Bar/StatusContainerView.swift +++ b/Clocker/Menu Bar/StatusContainerView.swift @@ -21,7 +21,6 @@ func bufferCalculatedWidth() -> Int { } func compactWidth(for timezone: TimezoneData) -> Int { - var totalWidth = 55 let timeFormat = timezone.timezoneFormat() @@ -47,7 +46,6 @@ func compactWidth(for timezone: TimezoneData) -> Int { let bufferWidth: CGFloat = 9.5 class StatusContainerView: NSView { - private var previousX: Int = 0 override func awakeFromNib() { @@ -57,7 +55,6 @@ class StatusContainerView: NSView { } init(with timezones: [Data]) { - func addSubviews() { timezones.forEach { if let timezoneObject = TimezoneData.customObject(from: $0) { @@ -91,12 +88,11 @@ class StatusContainerView: NSView { addSubviews() } - required init?(coder decoder: NSCoder) { + required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } func addTimezone(_ timezone: TimezoneData) { - let calculatedWidth = bestWidth(for: timezone) let frame = NSRect(x: previousX, y: 0, width: calculatedWidth, height: 30) @@ -118,7 +114,6 @@ class StatusContainerView: NSView { } func updateTime() { - if subviews.isEmpty { assertionFailure("Subviews count should > 0") } @@ -129,5 +124,4 @@ class StatusContainerView: NSView { } } } - } diff --git a/Clocker/Menu Bar/StatusItemHandler.swift b/Clocker/Menu Bar/StatusItemHandler.swift index fb6bb8c..75a6fbe 100644 --- a/Clocker/Menu Bar/StatusItemHandler.swift +++ b/Clocker/Menu Bar/StatusItemHandler.swift @@ -9,7 +9,6 @@ private enum MenubarState { } class StatusItemHandler: NSObject { - var hasActiveIcon: Bool = false var menubarTimer: Timer? @@ -112,8 +111,8 @@ class StatusItemHandler: NSObject { object: nil) userNotificationsDidChangeNotif = center.addObserver(forName: UserDefaults.didChangeNotification, - object: self, - queue: mainQueue) { _ in + object: self, + queue: mainQueue) { _ in self.setupStatusItem() } } @@ -219,7 +218,7 @@ class StatusItemHandler: NSObject { let shouldDisplaySeconds = shouldDisplaySecondsInMenubar() let menubarFavourites = DataStore.shared().retrieve(key: CLMenubarFavorites) - if !units.contains(.second) && shouldDisplaySeconds { + if !units.contains(.second), shouldDisplaySeconds { units.insert(.second) } @@ -281,7 +280,7 @@ class StatusItemHandler: NSObject { let menubarFavourites = (DataStore.shared().retrieve(key: CLMenubarFavorites) as? [Data]) ?? [] - if menubarFavourites.isEmpty && DataStore.shared().shouldDisplay(.showMeetingInMenubar) == false { + if menubarFavourites.isEmpty, DataStore.shared().shouldDisplay(.showMeetingInMenubar) == false { print("Invalidating menubar timer!") invalidation() diff --git a/Clocker/Menu Bar/StatusItemView.swift b/Clocker/Menu Bar/StatusItemView.swift index 7cd910c..f25af03 100644 --- a/Clocker/Menu Bar/StatusItemView.swift +++ b/Clocker/Menu Bar/StatusItemView.swift @@ -14,26 +14,26 @@ var compactModeTimeFont: NSFont { } var timeAttributes: [NSAttributedString.Key: AnyObject] { - let textColor = UserDefaults.standard.string(forKey: "AppleInterfaceStyle") == "Dark" ? NSColor.white : NSColor.black let attributes = [ NSAttributedString.Key.font: compactModeTimeFont, NSAttributedString.Key.foregroundColor: textColor, NSAttributedString.Key.backgroundColor: NSColor.clear, - NSAttributedString.Key.paragraphStyle: defaultParagraphStyle - ] + NSAttributedString.Key.paragraphStyle: defaultParagraphStyle, + ] return attributes } class StatusItemView: NSView { - // MARK: Private variables + private let locationView: NSTextField = NSTextField(labelWithString: "Hello") private let timeView: NSTextField = NSTextField(labelWithString: "Mon 19:14 PM") private var operationsObject: TimezoneDataOperations { return TimezoneDataOperations(with: dataObject) } + private var textFontAttributes: [NSAttributedString.Key: Any] { let textColor = UserDefaults.standard.string(forKey: "AppleInterfaceStyle") == "Dark" ? NSColor.white : NSColor.black @@ -41,12 +41,13 @@ class StatusItemView: NSView { NSAttributedString.Key.font: NSFont.boldSystemFont(ofSize: 10), NSAttributedString.Key.foregroundColor: textColor, NSAttributedString.Key.backgroundColor: NSColor.clear, - NSAttributedString.Key.paragraphStyle: defaultParagraphStyle + NSAttributedString.Key.paragraphStyle: defaultParagraphStyle, ] return textFontAttributes } - // MARK: Public + // MARK: Public + var dataObject: TimezoneData! { didSet { initialSetup() @@ -69,15 +70,15 @@ class StatusItemView: NSView { locationView.leadingAnchor.constraint(equalTo: leadingAnchor), locationView.trailingAnchor.constraint(equalTo: trailingAnchor), locationView.topAnchor.constraint(equalTo: topAnchor, constant: 7), - locationView.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 0.35) - ]) + locationView.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 0.35), + ]) NSLayoutConstraint.activate([ timeView.leadingAnchor.constraint(equalTo: leadingAnchor), timeView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: 0), timeView.topAnchor.constraint(equalTo: locationView.bottomAnchor), - timeView.bottomAnchor.constraint(equalTo: bottomAnchor) - ]) + timeView.bottomAnchor.constraint(equalTo: bottomAnchor), + ]) } func updateTimeInMenubar() { @@ -89,7 +90,7 @@ class StatusItemView: NSView { timeView.attributedStringValue = NSAttributedString(string: operationsObject.compactMenuHeader(), attributes: timeAttributes) } - required init?(coder decoder: NSCoder) { + required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } diff --git a/Clocker/Onboarding/OnboardingParentViewController.swift b/Clocker/Onboarding/OnboardingParentViewController.swift index 682e8c6..1bb0664 100644 --- a/Clocker/Onboarding/OnboardingParentViewController.swift +++ b/Clocker/Onboarding/OnboardingParentViewController.swift @@ -58,7 +58,6 @@ class OnboardingParentViewController: NSViewController { } private func setupUI() { - setIdentifiersForTests() positiveButton.title = "Get Started" @@ -119,9 +118,9 @@ class OnboardingParentViewController: NSViewController { transition(from: fromViewController, to: toViewController, options: .slideLeft) { - self.positiveButton.tag = OnboardingType.permissions.rawValue - self.positiveButton.title = "Continue" - self.backButton.isHidden = false + self.positiveButton.tag = OnboardingType.permissions.rawValue + self.positiveButton.title = "Continue" + self.backButton.isHidden = false } } @@ -136,10 +135,10 @@ class OnboardingParentViewController: NSViewController { transition(from: fromViewController, to: toViewController, options: .slideLeft) { - self.backButton.tag = OnboardingType.permissions.rawValue - self.positiveButton.tag = OnboardingType.launchAtLogin.rawValue - self.positiveButton.title = "Open Clocker At Login" - self.negativeButton.isHidden = false + self.backButton.tag = OnboardingType.permissions.rawValue + self.positiveButton.tag = OnboardingType.launchAtLogin.rawValue + self.positiveButton.title = "Open Clocker At Login" + self.negativeButton.isHidden = false } } @@ -156,10 +155,10 @@ class OnboardingParentViewController: NSViewController { transition(from: fromViewController, to: toViewController, options: .slideLeft) { - self.backButton.tag = OnboardingType.launchAtLogin.rawValue - self.positiveButton.tag = OnboardingType.search.rawValue - self.positiveButton.title = "Continue" - self.negativeButton.isHidden = true + self.backButton.tag = OnboardingType.launchAtLogin.rawValue + self.positiveButton.tag = OnboardingType.search.rawValue + self.positiveButton.title = "Continue" + self.negativeButton.isHidden = true } } @@ -174,15 +173,14 @@ class OnboardingParentViewController: NSViewController { transition(from: fromViewController, to: toViewController, options: .slideLeft) { - self.backButton.tag = OnboardingType.search.rawValue - self.positiveButton.tag = OnboardingType.final.rawValue - self.positiveButton.title = "Launch Clocker" + self.backButton.tag = OnboardingType.search.rawValue + self.positiveButton.tag = OnboardingType.final.rawValue + self.positiveButton.title = "Launch Clocker" } - } private func performFinalStepsBeforeFinishing() { - self.positiveButton.tag = OnboardingType.complete.rawValue + positiveButton.tag = OnboardingType.complete.rawValue // Install the menubar option! let appDelegate = NSApplication.shared.delegate as? AppDelegate @@ -222,10 +220,10 @@ class OnboardingParentViewController: NSViewController { transition(from: fromViewController, to: toViewController, options: .slideRight) { - self.positiveButton.tag = OnboardingType.search.rawValue - self.backButton.tag = OnboardingType.launchAtLogin.rawValue - self.positiveButton.title = "Continue" - self.negativeButton.isHidden = true + self.positiveButton.tag = OnboardingType.search.rawValue + self.backButton.tag = OnboardingType.launchAtLogin.rawValue + self.positiveButton.title = "Continue" + self.negativeButton.isHidden = true } } @@ -238,10 +236,10 @@ class OnboardingParentViewController: NSViewController { transition(from: fromViewController, to: toViewController, options: .slideRight) { - self.positiveButton.tag = OnboardingType.launchAtLogin.rawValue - self.backButton.tag = OnboardingType.permissions.rawValue - self.positiveButton.title = "Open Clocker At Login" - self.negativeButton.isHidden = false + self.positiveButton.tag = OnboardingType.launchAtLogin.rawValue + self.backButton.tag = OnboardingType.permissions.rawValue + self.positiveButton.title = "Open Clocker At Login" + self.negativeButton.isHidden = false } } @@ -256,10 +254,10 @@ class OnboardingParentViewController: NSViewController { transition(from: fromViewController, to: toViewController, options: .slideRight) { - self.positiveButton.tag = OnboardingType.permissions.rawValue - self.backButton.tag = OnboardingType.welcome.rawValue - self.negativeButton.isHidden = true - self.positiveButton.title = "Continue" + self.positiveButton.tag = OnboardingType.permissions.rawValue + self.backButton.tag = OnboardingType.welcome.rawValue + self.negativeButton.isHidden = true + self.positiveButton.title = "Continue" } } @@ -272,14 +270,13 @@ class OnboardingParentViewController: NSViewController { transition(from: fromViewController, to: toViewController, options: .slideRight) { - self.positiveButton.tag = OnboardingType.welcome.rawValue - self.backButton.isHidden = true - self.positiveButton.title = "Get Started" + self.positiveButton.tag = OnboardingType.welcome.rawValue + self.backButton.isHidden = true + self.positiveButton.title = "Get Started" } } private func shouldStartAtLogin(_ shouldStart: Bool) { - // If tests are going on, we don't want to enable/disable launch at login! if ProcessInfo.processInfo.arguments.contains(CLOnboaringTestsLaunchArgument) { return @@ -307,7 +304,6 @@ class OnboardingParentViewController: NSViewController { } private func currentController() -> [String: String] { - switch positiveButton.tag { case 0: return ["Onboarding Process Interrupted": "Welcome View"] @@ -322,7 +318,7 @@ class OnboardingParentViewController: NSViewController { case 5: return ["Onboarding Process Completed": "Successfully"] default: - return ["Onboarding Process Interrupted": "Error"] + return ["Onboarding Process Interrupted": "Error"] } } } diff --git a/Clocker/Onboarding/OnboardingPermissionsViewController.swift b/Clocker/Onboarding/OnboardingPermissionsViewController.swift index 2f53763..ece0bca 100644 --- a/Clocker/Onboarding/OnboardingPermissionsViewController.swift +++ b/Clocker/Onboarding/OnboardingPermissionsViewController.swift @@ -91,7 +91,7 @@ class OnboardingPermissionsViewController: NSViewController { eventCenter.requestAccess(to: .event, completionHandler: { [weak self] granted in OperationQueue.main.addOperation { - guard let `self` = self else { return } + guard let self = self else { return } self.calendarActivityIndicator.stopAnimation(nil) @@ -130,7 +130,6 @@ class OnboardingPermissionsViewController: NSViewController { if granted { OperationQueue.main.addOperation { - self.view.window?.orderBack(nil) NSApp.activate(ignoringOtherApps: true) diff --git a/Clocker/Onboarding/OnboardingSearchController.swift b/Clocker/Onboarding/OnboardingSearchController.swift index 8d31ab7..60fd0f5 100644 --- a/Clocker/Onboarding/OnboardingSearchController.swift +++ b/Clocker/Onboarding/OnboardingSearchController.swift @@ -14,7 +14,7 @@ class OnboardingSearchController: NSViewController { @IBOutlet private var searchBar: ClockerSearchField! @IBOutlet private var resultsTableView: NSTableView! @IBOutlet private var accessoryLabel: NSTextField! - @IBOutlet weak var undoButton: NSButton! + @IBOutlet var undoButton: NSButton! private var results: [TimezoneData] = [] private var dataTask: URLSessionDataTask? = .none @@ -57,7 +57,7 @@ class OnboardingSearchController: NSViewController { @objc func doubleClickAction(_: NSTableView?) { [accessoryLabel].forEach { $0?.isHidden = false } - if resultsTableView.selectedRow >= 0 && resultsTableView.selectedRow < results.count { + if resultsTableView.selectedRow >= 0, resultsTableView.selectedRow < results.count { let selectedTimezone = results[resultsTableView.selectedRow] addTimezoneToDefaults(selectedTimezone) @@ -65,13 +65,12 @@ class OnboardingSearchController: NSViewController { } private func addTimezoneToDefaults(_ timezone: TimezoneData) { - func setupLabelHidingTimer() { Timer.scheduledTimer(withTimeInterval: 5, repeats: false) { _ in - OperationQueue.main.addOperation { - self.accessoryLabel.stringValue = CLEmptyString - } + OperationQueue.main.addOperation { + self.accessoryLabel.stringValue = CLEmptyString + } } } @@ -104,7 +103,6 @@ class OnboardingSearchController: NSViewController { /// Returns true if there's an error. private func handleEdgeCase(for response: Data?) -> Bool { - func setErrorPlaceholders() { setInfoLabel("No timezone found! Try entering an exact name.") searchBar.placeholderString = placeholders.randomElement() @@ -150,7 +148,7 @@ class OnboardingSearchController: NSViewController { NetworkManager.task(with: urlString) { [weak self] response, error in - guard let `self` = self else { return } + guard let self = self else { return } OperationQueue.main.addOperation { if self.handleEdgeCase(for: response) == true { @@ -158,7 +156,7 @@ class OnboardingSearchController: NSViewController { } if error == nil, let json = response, let response = self.decodeTimezone(from: json) { - if self.resultsTableView.selectedRow >= 0 && self.resultsTableView.selectedRow < self.results.count { + if self.resultsTableView.selectedRow >= 0, self.resultsTableView.selectedRow < self.results.count { var filteredAddress = "Error" if let address = dataObject.formattedAddress { @@ -172,7 +170,7 @@ class OnboardingSearchController: NSViewController { "latitude": latitude, "longitude": longitude, "nextUpdate": CLEmptyString, - CLCustomLabel: filteredAddress + CLCustomLabel: filteredAddress, ] as [String: Any] DataStore.shared().addTimezone(TimezoneData(with: newTimeZone)) @@ -222,7 +220,6 @@ class OnboardingSearchController: NSViewController { } @IBAction func search(_ sender: NSSearchField) { - resultsTableView.deselectAll(nil) let searchString = sender.stringValue @@ -249,9 +246,8 @@ class OnboardingSearchController: NSViewController { } @objc func actualSearch() { - func setupForError() { - self.resultsTableView.isHidden = true + resultsTableView.isHidden = true } let userPreferredLanguage = Locale.preferredLanguages.first ?? "en-US" @@ -267,56 +263,55 @@ class OnboardingSearchController: NSViewController { dataTask = NetworkManager.task(with: urlString, completionHandler: { [weak self] response, error in - guard let `self` = self else { return } - - OperationQueue.main.addOperation { + guard let self = self else { return } - print("Search string was: \(searchString)") + OperationQueue.main.addOperation { + print("Search string was: \(searchString)") - let currentSearchBarValue = self.searchBar.stringValue + let currentSearchBarValue = self.searchBar.stringValue - let words = currentSearchBarValue.components(separatedBy: CharacterSet.whitespacesAndNewlines) + let words = currentSearchBarValue.components(separatedBy: CharacterSet.whitespacesAndNewlines) - if words.joined(separator: CLEmptyString) != searchString { - return - } + if words.joined(separator: CLEmptyString) != searchString { + return + } - self.results = [] + self.results = [] - if let errorPresent = error { - self.presentErrorMessage(errorPresent.localizedDescription) - setupForError() - return - } + if let errorPresent = error { + self.presentErrorMessage(errorPresent.localizedDescription) + setupForError() + return + } - guard let data = response else { - self.setInfoLabel(PreferencesConstants.tryAgainMessage) - setupForError() - return - } + guard let data = response else { + self.setInfoLabel(PreferencesConstants.tryAgainMessage) + setupForError() + return + } - let searchResults = self.decode(from: data) + let searchResults = self.decode(from: data) - if searchResults?.status == "ZERO_RESULTS" { - self.setInfoLabel("No results! 😔 Try entering the exact name.") - setupForError() - return - } + if searchResults?.status == "ZERO_RESULTS" { + self.setInfoLabel("No results! 😔 Try entering the exact name.") + setupForError() + return + } - self.appendResultsToFilteredArray(searchResults!.results) + self.appendResultsToFilteredArray(searchResults!.results) - self.setInfoLabel(CLEmptyString) + self.setInfoLabel(CLEmptyString) - self.resultsTableView.reloadData() - } + self.resultsTableView.reloadData() + } }) } private func presentErrorMessage(_ errorMessage: String) { if errorMessage == PreferencesConstants.offlineErrorMessage { - self.setInfoLabel(PreferencesConstants.noInternetConnectivityError) + setInfoLabel(PreferencesConstants.noInternetConnectivityError) } else { - self.setInfoLabel(PreferencesConstants.tryAgainMessage) + setInfoLabel(PreferencesConstants.tryAgainMessage) } } @@ -333,8 +328,8 @@ class OnboardingSearchController: NSViewController { CLTimezoneName: formattedAddress, CLCustomLabel: formattedAddress, CLTimezoneID: CLEmptyString, - CLPlaceIdentifier: $0.placeId - ] as [String: Any] + CLPlaceIdentifier: $0.placeId, + ] as [String: Any] self.results.append(TimezoneData(with: totalPackage)) } @@ -359,11 +354,10 @@ class OnboardingSearchController: NSViewController { searchBar.placeholderString = placeholders.randomElement() } - @IBAction func undoAction(_ sender: Any) { + @IBAction func undoAction(_: Any) { DataStore.shared().removeLastTimezone() setInfoLabel("Removed.") } - } extension OnboardingSearchController: NSTableViewDataSource { @@ -385,7 +379,7 @@ extension OnboardingSearchController: NSTableViewDataSource { extension OnboardingSearchController: NSTableViewDelegate { func tableView(_: NSTableView, heightOfRow row: Int) -> CGFloat { - if row == 0 && results.isEmpty { + if row == 0, results.isEmpty { return 30 } diff --git a/Clocker/Overall App/AppDefaults.swift b/Clocker/Overall App/AppDefaults.swift index cf61a46..3c85e50 100644 --- a/Clocker/Overall App/AppDefaults.swift +++ b/Clocker/Overall App/AppDefaults.swift @@ -3,13 +3,12 @@ import Cocoa class AppDefaults { - class func initialize() { initializeDefaults() } private class func deleteOldUserDefaults() { - let userDefaults = UserDefaults.standard + let userDefaults = UserDefaults.standard // Now delete the old preferences if let bundleID = Bundle.main.bundleIdentifier, userDefaults.object(forKey: "PreferencesHaveBeenWiped") == nil { @@ -19,7 +18,6 @@ class AppDefaults { } private class func initializeDefaults() { - let userDefaults = UserDefaults.standard let menubarFavourites = userDefaults.object(forKey: CLMenubarFavorites) @@ -43,7 +41,6 @@ class AppDefaults { // If we already have timezones to display in menubar, do nothing. // Else, we switch the menubar mode default to compact mode for new users if userDefaults.bool(forKey: CLDefaultMenubarMode) == false { - if let menubarFavourites = userDefaults.object(forKey: CLDefaultPreferenceKey) as? [Data], menubarFavourites.isEmpty == false { userDefaults.set(1, forKey: CLMenubarCompactMode) } else { @@ -54,11 +51,9 @@ class AppDefaults { } if userDefaults.bool(forKey: CLSwitchToCompactModeAlert) == false { - userDefaults.set(true, forKey: CLSwitchToCompactModeAlert) if let menubarFavourites = DataStore.shared().retrieve(key: CLMenubarFavorites) as? [Data], menubarFavourites.count > 1 { - // If the user is already using the compact mode, abort. if DataStore.shared().shouldDisplay(.menubarCompactMode) { return @@ -78,7 +73,6 @@ class AppDefaults { // Set default to System theme for Mojave if #available(macOS 10.14, *) { - if defaults.bool(forKey: CLDefaultThemeOnMojave) == false { if isDarkModeOn() { Themer.shared().set(theme: 2) @@ -139,16 +133,13 @@ class AppDefaults { CLAppDislayOptions: 0, CLMenubarCompactMode: 1] } - } extension UserDefaults { - func wipeIfNeccesary() { if let bundleID = Bundle.main.bundleIdentifier, object(forKey: "PreferencesHaveBeenWiped") == nil { removePersistentDomain(forName: bundleID) set(true, forKey: "PreferencesHaveBeenWiped") } } - } diff --git a/Clocker/Overall App/AppKit + Additions.swift b/Clocker/Overall App/AppKit + Additions.swift index 9ca8fe6..8ac019e 100644 --- a/Clocker/Overall App/AppKit + Additions.swift +++ b/Clocker/Overall App/AppKit + Additions.swift @@ -1,7 +1,6 @@ // Copyright © 2015 Abhishek Banthia extension NSTextField { - func applyDefaultStyle() { backgroundColor = NSColor.clear isEditable = false @@ -19,24 +18,21 @@ extension NSTextField { cell?.wraps = false cell?.isScrollable = true } - } extension NSFont { - func size(_ string: String, _ width: Double, attributes: [NSAttributedString.Key: AnyObject]) -> CGSize { let size = CGSize(width: width, height: Double.greatestFiniteMagnitude) var otherAttributes: [NSAttributedString.Key: AnyObject] = [NSAttributedString.Key.font: self] - attributes.forEach { (arg) in let (key, value) = arg; otherAttributes[key] = value } + attributes.forEach { arg in let (key, value) = arg; otherAttributes[key] = value } return NSString(string: string).boundingRect(with: size, options: NSString.DrawingOptions.usesLineFragmentOrigin, attributes: attributes).size } - } class ClockerSearchField: NSSearchField { diff --git a/Clocker/Overall App/DateFormatterManager.swift b/Clocker/Overall App/DateFormatterManager.swift index edee5e2..d62b2b1 100644 --- a/Clocker/Overall App/DateFormatterManager.swift +++ b/Clocker/Overall App/DateFormatterManager.swift @@ -46,7 +46,7 @@ class DateFormatterManager: NSObject { return specializedFormatter } - @objc class func localizedFormatter(with format: String, for timezoneIdentifier: String, locale: Locale = Locale.autoupdatingCurrent) -> DateFormatter { + @objc class func localizedFormatter(with format: String, for timezoneIdentifier: String, locale _: Locale = Locale.autoupdatingCurrent) -> DateFormatter { dateFormatter.dateStyle = .none dateFormatter.timeStyle = .none dateFormatter.locale = Locale.autoupdatingCurrent diff --git a/Clocker/Overall App/Reach.swift b/Clocker/Overall App/Reach.swift index aa5da78..7fbb5bd 100644 --- a/Clocker/Overall App/Reach.swift +++ b/Clocker/Overall App/Reach.swift @@ -76,7 +76,7 @@ extension ReachabilityStatus { let connectionRequired = flags.contains(.connectionRequired) let isReachable = flags.contains(.reachable) - if !connectionRequired && isReachable { + if !connectionRequired, isReachable { self = .online(.wiFi) } else { self = .offline diff --git a/Clocker/Overall App/Themer.swift b/Clocker/Overall App/Themer.swift index f0dc3bc..aeddd7e 100644 --- a/Clocker/Overall App/Themer.swift +++ b/Clocker/Overall App/Themer.swift @@ -76,7 +76,6 @@ extension Themer { } setAppAppearance() - } @objc func respondToInterfaceStyle() { @@ -315,7 +314,6 @@ extension Themer { } func currentLocationImage() -> NSImage { - if #available(macOS 10.14, *) { switch themeIndex { case .light: @@ -365,7 +363,6 @@ extension Themer { } func privacyTabImage() -> NSImage { - if #available(macOS 10.14, *) { switch themeIndex { case .light: @@ -381,7 +378,6 @@ extension Themer { } func appearanceTabImage() -> NSImage { - if #available(macOS 10.14, *) { switch themeIndex { case .light: @@ -397,7 +393,6 @@ extension Themer { } func calendarTabImage() -> NSImage { - if #available(macOS 10.14, *) { switch themeIndex { case .light: diff --git a/Clocker/Overall App/Timer.swift b/Clocker/Overall App/Timer.swift index 4ec422e..0cbed8a 100644 --- a/Clocker/Overall App/Timer.swift +++ b/Clocker/Overall App/Timer.swift @@ -126,7 +126,7 @@ open class Repeater: Equatable { /// Current state of the timer public private(set) var state: State = .paused { didSet { - self.onStateChanged?(self, state) + onStateChanged?(self, state) } } @@ -334,7 +334,7 @@ open class Repeater: Equatable { /// Pause a running timer. If timer is paused it does nothing. @discardableResult public func pause() -> Bool { - guard state != .paused && state != .finished else { + guard state != .paused, state != .finished else { return false } diff --git a/Clocker/Overall App/UserDefaults + KVOExtensions.swift b/Clocker/Overall App/UserDefaults + KVOExtensions.swift index 8074333..a144c39 100644 --- a/Clocker/Overall App/UserDefaults + KVOExtensions.swift +++ b/Clocker/Overall App/UserDefaults + KVOExtensions.swift @@ -3,7 +3,6 @@ import Cocoa extension UserDefaults { - @objc dynamic var displayFutureSlider: Int { return integer(forKey: CLDisplayFutureSliderKey) } diff --git a/Clocker/Panel/Data Layer/TimezoneData.swift b/Clocker/Panel/Data Layer/TimezoneData.swift index 7175d42..5af56f9 100644 --- a/Clocker/Panel/Data Layer/TimezoneData.swift +++ b/Clocker/Panel/Data Layer/TimezoneData.swift @@ -12,7 +12,6 @@ struct DateFormat { // Non-class type cannot conform to NSCoding! class TimezoneData: NSObject, NSCoding { - enum SelectionType: Int { case city case timezone @@ -193,7 +192,7 @@ class TimezoneData: NSObject, NSCoding { private class func logOldModelUsage() { guard let shortVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String, let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String else { - return + return } let operatingSystem = ProcessInfo.processInfo.operatingSystemVersion @@ -202,7 +201,7 @@ class TimezoneData: NSObject, NSCoding { let feedbackInfo = [ AppFeedbackConstants.CLOperatingSystemVersion: osVersion, - AppFeedbackConstants.CLClockerVersion: versionInfo + AppFeedbackConstants.CLClockerVersion: versionInfo, ] Logger.log(object: feedbackInfo, for: "CLTimezoneData is still being used!") @@ -256,7 +255,7 @@ class TimezoneData: NSObject, NSCoding { // Do the serialization let serializedModels = newModels.map { (place) -> Data in - return NSKeyedArchiver.archivedData(withRootObject: place) + NSKeyedArchiver.archivedData(withRootObject: place) } return serializedModels @@ -361,7 +360,7 @@ class TimezoneData: NSObject, NSCoding { let errorDictionary = [ "Formatted Address": name, "Place Identifier": placeIdentifier, - "TimezoneID": timezoneIdentifier + "TimezoneID": timezoneIdentifier, ] Logger.log(object: errorDictionary, for: "Error fetching timezone() in TimezoneData") diff --git a/Clocker/Panel/Data Layer/TimezoneDataOperations.swift b/Clocker/Panel/Data Layer/TimezoneDataOperations.swift index eab3734..353e71e 100644 --- a/Clocker/Panel/Data Layer/TimezoneDataOperations.swift +++ b/Clocker/Panel/Data Layer/TimezoneDataOperations.swift @@ -33,7 +33,6 @@ extension TimezoneDataOperations { } func compactMenuHeader() -> String { - var subtitle = CLEmptyString let shouldDayBeShown = DataStore.shared().shouldShowDateInMenubar() @@ -105,7 +104,7 @@ extension TimezoneDataOperations { let sourceTimezone = TimeZone.current let destinationTimezone = TimeZone(identifier: dataObject.timezone()) - let sourceGMTOffset: Double = Double(sourceTimezone.secondsFromGMT(for: source)) + let sourceGMTOffset: Double = Double(sourceTimezone.secondsFromGMT(for: source)) let destinationGMTOffset: Double = Double(destinationTimezone?.secondsFromGMT(for: source) ?? 0) let interval = destinationGMTOffset - sourceGMTOffset @@ -120,8 +119,8 @@ extension TimezoneDataOperations { } return calendar?.date(byAdding: .minute, - value: minutesToAdd, - to: Date()) ?? Date() + value: minutesToAdd, + to: Date()) ?? Date() } func date(with sliderValue: Int, displayType: CLDateDisplayType) -> String { @@ -136,10 +135,8 @@ extension TimezoneDataOperations { } if displayType == CLDateDisplayType.panelDisplay { - // Yesterday, tomorrow, etc if relativeDayPreference.intValue == 0 { - let localFormatter = DateFormatterManager.localizedSimpleFormatter("EEEE") let local = localFormatter.date(from: localeDate(with: "EEEE")) @@ -169,9 +166,9 @@ extension TimezoneDataOperations { } let errorDictionary: [String: Any] = ["Timezone": dataObject.timezone(), - "Current Locale": Locale.autoupdatingCurrent.identifier, - "Slider Value": sliderValue, - "Today's Date": Date()] + "Current Locale": Locale.autoupdatingCurrent.identifier, + "Slider Value": sliderValue, + "Today's Date": Date()] Logger.log(object: errorDictionary, for: "Unable to get date") return "Error" @@ -207,8 +204,8 @@ extension TimezoneDataOperations { let unableToConvertDateParameters = [ "New Date": newDate, "Timezone": dataObject.timezone(), - "Locale": dateFormatter.locale.identifier - ] as [String: Any] + "Locale": dateFormatter.locale.identifier, + ] as [String: Any] Logger.log(object: unableToConvertDateParameters, for: "Date conversion failure - New Date is nil") return CLEmptyString } diff --git a/Clocker/Panel/FloatingWindowController.swift b/Clocker/Panel/FloatingWindowController.swift index 6bbc70a..1f1063d 100644 --- a/Clocker/Panel/FloatingWindowController.swift +++ b/Clocker/Panel/FloatingWindowController.swift @@ -55,7 +55,7 @@ class FloatingWindowController: ParentPanelController { target.image = Themer.shared().extraOptionsHighlightedImage() - if popover.isShown && row == previousPopoverRow { + if popover.isShown, row == previousPopoverRow { popover.close() target.image = Themer.shared().extraOptionsImage() previousPopoverRow = -1 diff --git a/Clocker/Panel/Notes Popover/NotesPopover.swift b/Clocker/Panel/Notes Popover/NotesPopover.swift index 9534e1b..59ece65 100644 --- a/Clocker/Panel/Notes Popover/NotesPopover.swift +++ b/Clocker/Panel/Notes Popover/NotesPopover.swift @@ -3,7 +3,6 @@ import Cocoa class NotesPopover: NSViewController { - private enum OverrideType { case timezoneFormat case seconds @@ -37,7 +36,7 @@ class NotesPopover: NSViewController { @IBOutlet var timeFormatControl: NSSegmentedControl! - @IBOutlet weak var secondsFormatControl: NSSegmentedControl! + @IBOutlet var secondsFormatControl: NSSegmentedControl! @IBOutlet var notesTextView: TextViewWithPlaceholder! @@ -62,7 +61,7 @@ class NotesPopover: NSViewController { "1 hour before", "2 hour before", "1 day before", - "2 days before" + "2 days before", ] alertPopupButton.removeAllItems() @@ -200,7 +199,7 @@ class NotesPopover: NSViewController { let attributesDictionary = [ NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: Themer.shared().mainTextColor(), - NSAttributedString.Key.paragraphStyle: style + NSAttributedString.Key.paragraphStyle: style, ] button.attributedTitle = NSAttributedString(string: title, @@ -448,7 +447,6 @@ class NotesPopover: NSViewController { handler.setupStatusItem() } } - } @objc extension NotesPopover { diff --git a/Clocker/Panel/Notes Popover/TextViewWithPlaceholder.swift b/Clocker/Panel/Notes Popover/TextViewWithPlaceholder.swift index 6bb3f04..fac52d0 100644 --- a/Clocker/Panel/Notes Popover/TextViewWithPlaceholder.swift +++ b/Clocker/Panel/Notes Popover/TextViewWithPlaceholder.swift @@ -18,7 +18,7 @@ class TextViewWithPlaceholder: NSTextView { if let placeHolderFont = NSFont(name: "Avenir", size: 14) { let textDict = [ NSAttributedString.Key.foregroundColor: NSColor.gray, - NSAttributedString.Key.font: placeHolderFont + NSAttributedString.Key.font: placeHolderFont, ] return NSAttributedString(string: " Add your notes here.", attributes: textDict) } @@ -32,7 +32,7 @@ class TextViewWithPlaceholder: NSTextView { override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) - if string == CLEmptyString && self != window?.firstResponder { + if string == CLEmptyString, self != window?.firstResponder { placeholder.draw(at: NSPoint(x: 0, y: 0)) } } diff --git a/Clocker/Panel/PanelController.swift b/Clocker/Panel/PanelController.swift index 88ca1b0..10577bf 100644 --- a/Clocker/Panel/PanelController.swift +++ b/Clocker/Panel/PanelController.swift @@ -3,7 +3,6 @@ import Cocoa class PanelController: ParentPanelController { - @objc dynamic var hasActivePanel: Bool = false static var sharedWindow = PanelController(windowNibName: .panel) @@ -76,7 +75,7 @@ class PanelController: ParentPanelController { setTimezoneDatasourceSlider(sliderValue: 0) - reviewView.isHidden = !(RateController.canPrompt()) + reviewView.isHidden = !RateController.canPrompt() reviewView.layer?.backgroundColor = NSColor.clear.cgColor @@ -100,7 +99,6 @@ class PanelController: ParentPanelController { // New way to set the panel's frame. // This takes into account the screen's dimensions. private func setPanelFrame() { - guard let appDelegate = NSApplication.shared.delegate as? AppDelegate else { return } @@ -114,7 +112,7 @@ class PanelController: ParentPanelController { statusView = appDelegate.statusItemForPanel().statusItem.button } - if let statusWindow = statusBackgroundWindow, + if let statusWindow = statusBackgroundWindow, let statusButton = statusView { var statusItemFrame = statusWindow.convertToScreen(statusButton.frame) var statusItemScreen = NSScreen.main @@ -176,14 +174,13 @@ class PanelController: ParentPanelController { "Show Upcoming Event View": showUpcomingEventView == "YES" ? "Yes" : "No", "Country": country, "Calendar Access Provided": EventCenter.sharedCenter().calendarAccessGranted() ? "Yes" : "No", - "Number of Timezones": preferences.count + "Number of Timezones": preferences.count, ] Logger.log(object: panelEvent, for: "openedPanel") } private func startWindowTimer() { - stopMenubarTimerIfNeccesary() if let timer = parentTimer, timer.state == .paused { @@ -195,7 +192,6 @@ class PanelController: ParentPanelController { } private func startTimer() { - print("Start timer called") parentTimer = Repeater(interval: .seconds(1), mode: .infinite) { _ in @@ -204,7 +200,6 @@ class PanelController: ParentPanelController { } } parentTimer!.start() - } private func stopMenubarTimerIfNeccesary() { @@ -278,7 +273,7 @@ class PanelController: ParentPanelController { target.image = Themer.shared().extraOptionsHighlightedImage() - if popover.isShown && row == previousPopoverRow { + if popover.isShown, row == previousPopoverRow { popover.close() target.image = Themer.shared().extraOptionsImage() previousPopoverRow = -1 diff --git a/Clocker/Panel/ParentPanelController.swift b/Clocker/Panel/ParentPanelController.swift index 21c63c6..c34ef67 100644 --- a/Clocker/Panel/ParentPanelController.swift +++ b/Clocker/Panel/ParentPanelController.swift @@ -12,7 +12,6 @@ struct PanelConstants { } class ParentPanelController: NSWindowController { - private var futureSliderObserver: NSKeyValueObservation? private var userFontSizeSelectionObserver: NSKeyValueObservation? private var futureSliderRangeObserver: NSKeyValueObservation? @@ -98,13 +97,13 @@ class ParentPanelController: NSWindowController { } private func setupObservers() { - futureSliderObserver = UserDefaults.standard.observe(\.displayFutureSlider, options: [.new]) { (_, change) in + futureSliderObserver = UserDefaults.standard.observe(\.displayFutureSlider, options: [.new]) { _, change in if let changedValue = change.newValue { self.futureSliderView.isHidden = changedValue == 1 } } - userFontSizeSelectionObserver = UserDefaults.standard.observe(\.userFontSize, options: [.new]) { (_, change) in + userFontSizeSelectionObserver = UserDefaults.standard.observe(\.userFontSize, options: [.new]) { _, change in if let newFontSize = change.newValue { Logger.log(object: ["FontSize": newFontSize], for: "User Font Size Preference") self.mainTableView.reloadData() @@ -112,7 +111,7 @@ class ParentPanelController: NSWindowController { } } - futureSliderRangeObserver = UserDefaults.standard.observe(\.sliderDayRange, options: [.new]) { (_, change) in + futureSliderRangeObserver = UserDefaults.standard.observe(\.sliderDayRange, options: [.new]) { _, change in if change.newValue != nil { self.adjustFutureSliderBasedOnPreferences() } @@ -153,7 +152,7 @@ class ParentPanelController: NSWindowController { themeChanged() - futureSliderView.isHidden = !(DataStore.shared().shouldDisplay(.futureSlider)) + futureSliderView.isHidden = !DataStore.shared().shouldDisplay(.futureSlider) sharingButton.sendAction(on: .leftMouseDown) @@ -168,16 +167,15 @@ class ParentPanelController: NSWindowController { } private func showDebugVersionViewIfNeccesary() { - if debugVersionView != nil { debugVersionView.wantsLayer = true debugVersionView.layer?.backgroundColor = NSColor.systemRed.cgColor } #if RELEASE - if debugVersionView != nil && stackView.arrangedSubviews.contains(debugVersionView) { - stackView.removeView(debugVersionView) - } + if debugVersionView != nil, stackView.arrangedSubviews.contains(debugVersionView) { + stackView.removeView(debugVersionView) + } #endif } @@ -277,7 +275,7 @@ class ParentPanelController: NSWindowController { let styleAttributes = [ NSAttributedString.Key.paragraphStyle: paragraphStyle, - NSAttributedString.Key.font: NSFont(name: "Avenir-Light", size: 13) ?? NSFont.systemFont(ofSize: 13) + NSAttributedString.Key.font: NSFont(name: "Avenir-Light", size: 13) ?? NSFont.systemFont(ofSize: 13), ] let leftButtonAttributedTitle = NSAttributedString(string: leftButton.title, attributes: styleAttributes) @@ -830,7 +828,7 @@ class ParentPanelController: NSWindowController { let styleAttributes = [ NSAttributedString.Key.paragraphStyle: paragraphStyle, - NSAttributedString.Key.font: NSFont(name: "Avenir-Light", size: 13)! + NSAttributedString.Key.font: NSFont(name: "Avenir-Light", size: 13)!, ] leftButton.attributedTitle = NSAttributedString(string: "Not Really", attributes: styleAttributes) rightButton.attributedTitle = NSAttributedString(string: "Yes!", attributes: styleAttributes) @@ -841,7 +839,7 @@ class ParentPanelController: NSWindowController { return } - NSAnimationContext.runAnimationGroup({ (context) in + NSAnimationContext.runAnimationGroup({ context in context.duration = 1 context.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) leftButton.animator().alphaValue = 0.0 @@ -849,7 +847,7 @@ class ParentPanelController: NSWindowController { }, completionHandler: { field.stringValue = title - NSAnimationContext.runAnimationGroup({ (context) in + NSAnimationContext.runAnimationGroup({ context in context.duration = 1 context.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeIn) self.runAnimationCompletionBlock(leftTitle, rightTitle) @@ -858,27 +856,27 @@ class ParentPanelController: NSWindowController { } private func runAnimationCompletionBlock(_ leftButtonTitle: String, _ rightButtonTitle: String) { - self.leftButton.animator().alphaValue = 1.0 - self.rightButton.animator().alphaValue = 1.0 + leftButton.animator().alphaValue = 1.0 + rightButton.animator().alphaValue = 1.0 let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = .center let styleAttributes = [ NSAttributedString.Key.paragraphStyle: paragraphStyle, - NSAttributedString.Key.font: NSFont(name: "Avenir-Light", size: 13)! + NSAttributedString.Key.font: NSFont(name: "Avenir-Light", size: 13)!, ] - if self.leftButton.attributedTitle.string == "Not Really" { - self.leftButton.animator().attributedTitle = NSAttributedString(string: PanelConstants.noThanksTitle, attributes: styleAttributes) + if leftButton.attributedTitle.string == "Not Really" { + leftButton.animator().attributedTitle = NSAttributedString(string: PanelConstants.noThanksTitle, attributes: styleAttributes) } - if self.rightButton.attributedTitle.string == PanelConstants.yesWithExclamation { - self.rightButton.animator().attributedTitle = NSAttributedString(string: "Yes, sure", attributes: styleAttributes) + if rightButton.attributedTitle.string == PanelConstants.yesWithExclamation { + rightButton.animator().attributedTitle = NSAttributedString(string: "Yes, sure", attributes: styleAttributes) } - self.leftButton.animator().attributedTitle = NSAttributedString(string: leftButtonTitle, attributes: styleAttributes) - self.rightButton.animator().attributedTitle = NSAttributedString(string: rightButtonTitle, attributes: styleAttributes) + leftButton.animator().attributedTitle = NSAttributedString(string: leftButtonTitle, attributes: styleAttributes) + rightButton.animator().attributedTitle = NSAttributedString(string: rightButtonTitle, attributes: styleAttributes) } // MARK: Date Picker + Slider diff --git a/Clocker/Panel/Rate Controller/RateController.swift b/Clocker/Panel/Rate Controller/RateController.swift index 6f7b02d..175033b 100644 --- a/Clocker/Panel/Rate Controller/RateController.swift +++ b/Clocker/Panel/Rate Controller/RateController.swift @@ -3,9 +3,8 @@ import Cocoa final class RateController { - private static var storage = UserDefaults.standard - private static let version: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "N/A" + private static let version: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "N/A" private static var debugging = false private enum Keys { @@ -43,12 +42,12 @@ final class RateController { // Check if the app has been installed for atleast 7 days guard let install = storage.object(forKey: Keys.install) as? Date, install.timeIntervalSinceNow < minInstall - else { return false } + else { return false } // If we have never been prompted before, go ahead and prompt guard let lastPrompt = storage.object(forKey: Keys.lastPrompt) as? Date, let lastVersion = storage.object(forKey: Keys.lastVersion) as? String - else { return true } + else { return true } // Minimum interval between two versions should be 45 let minInterval: TimeInterval = day * 45 @@ -66,5 +65,4 @@ final class RateController { NSWorkspace.shared.open(ratingsURL) prompted() } - } diff --git a/Clocker/Panel/Rate Controller/ReviewView.swift b/Clocker/Panel/Rate Controller/ReviewView.swift index a3cb862..7c0abac 100644 --- a/Clocker/Panel/Rate Controller/ReviewView.swift +++ b/Clocker/Panel/Rate Controller/ReviewView.swift @@ -7,7 +7,7 @@ class ReviewView: NSView { override func mouseEntered(with event: NSEvent) { super.mouseEntered(with: event) - let dismissalButton = subviews.filter({ $0.tag == 55 }).first + let dismissalButton = subviews.filter { $0.tag == 55 }.first if let firstMatch = dismissalButton, firstMatch.isHidden { firstMatch.isHidden = false } @@ -15,7 +15,7 @@ class ReviewView: NSView { override func mouseExited(with event: NSEvent) { super.mouseExited(with: event) - let dismissalButton = subviews.filter({ $0.tag == 55 }).first + let dismissalButton = subviews.filter { $0.tag == 55 }.first if let firstMatch = dismissalButton, !firstMatch.isHidden { firstMatch.isHidden = true } diff --git a/Clocker/Panel/UI/CustomSliderCell.swift b/Clocker/Panel/UI/CustomSliderCell.swift index fad7306..008006b 100644 --- a/Clocker/Panel/UI/CustomSliderCell.swift +++ b/Clocker/Panel/UI/CustomSliderCell.swift @@ -21,8 +21,8 @@ class CustomSliderCell: NSSliderCell { leftRect.size.width = finalWidth let background = NSBezierPath(roundedRect: rect, - xRadius: barRadius, - yRadius: barRadius) + xRadius: barRadius, + yRadius: barRadius) NSColor(calibratedRed: 67.0 / 255.0, green: 138.0 / 255.0, blue: 250.0 / 255.0, alpha: 1.0).setFill() background.fill() diff --git a/Clocker/Panel/UI/NoTimezoneView.swift b/Clocker/Panel/UI/NoTimezoneView.swift index 92c0bb4..83b1d66 100644 --- a/Clocker/Panel/UI/NoTimezoneView.swift +++ b/Clocker/Panel/UI/NoTimezoneView.swift @@ -6,9 +6,9 @@ import QuartzCore class NoTimezoneView: NSView { private lazy var emoji: NSTextField = { let emoji = NSTextField(frame: NSRect(x: frame.size.width / 2 - 50, - y: frame.size.height / 2 - 50, - width: 100, - height: 100)) + y: frame.size.height / 2 - 50, + width: 100, + height: 100)) emoji.wantsLayer = true emoji.stringValue = "🌏" emoji.isBordered = false @@ -23,9 +23,9 @@ class NoTimezoneView: NSView { private lazy var message: NSTextField = { let messageField = NSTextField(frame: NSRect(x: frame.size.width / 2 - 250, - y: frame.size.height / 2 - 275, - width: 500, - height: 200)) + y: frame.size.height / 2 - 275, + width: 500, + height: 200)) messageField.wantsLayer = true messageField.setAccessibilityIdentifier("NoTimezoneMessage") messageField.placeholderString = "No places added" diff --git a/Clocker/Panel/UI/PanelTableView.swift b/Clocker/Panel/UI/PanelTableView.swift index 52a17ec..bcaf366 100644 --- a/Clocker/Panel/UI/PanelTableView.swift +++ b/Clocker/Panel/UI/PanelTableView.swift @@ -31,7 +31,7 @@ class PanelTableView: NSTableView { let options: NSTrackingArea.Options = [ .mouseMoved, .mouseEnteredAndExited, - .activeAlways + .activeAlways, ] let clipRect = enclosingScrollView?.contentView.bounds ?? .zero diff --git a/Clocker/Panel/UI/TimezoneCellView.swift b/Clocker/Panel/UI/TimezoneCellView.swift index a0f265f..0ce0dac 100644 --- a/Clocker/Panel/UI/TimezoneCellView.swift +++ b/Clocker/Panel/UI/TimezoneCellView.swift @@ -116,7 +116,7 @@ class TimezoneCellView: NSTableCellView { var searchView = superview - while searchView != nil && searchView is PanelTableView == false { + while searchView != nil, searchView is PanelTableView == false { searchView = searchView?.superview } diff --git a/Clocker/Panel/UI/TimezoneDataSource.swift b/Clocker/Panel/UI/TimezoneDataSource.swift index d88c12d..450a06d 100644 --- a/Clocker/Panel/UI/TimezoneDataSource.swift +++ b/Clocker/Panel/UI/TimezoneDataSource.swift @@ -60,7 +60,7 @@ extension TimezoneDataSource: NSTableViewDataSource, NSTableViewDelegate { cellView.time.stringValue = operation.time(with: sliderValue) cellView.noteLabel.stringValue = currentModel.note ?? CLEmptyString cellView.noteLabel.toolTip = currentModel.note ?? CLEmptyString - cellView.currentLocationIndicator.isHidden = !(currentModel.isSystemTimezone) + cellView.currentLocationIndicator.isHidden = !currentModel.isSystemTimezone cellView.time.setAccessibilityIdentifier("ActualTime") cellView.layout(with: currentModel) @@ -177,7 +177,7 @@ extension TimezoneCellView { sunriseImage.isHidden = !shouldDisplay // If it's a timezone and not a place, we can't determine the sunrise/sunset time; hide the sunrise image - if model.selectionType == .timezone && (model.latitude == nil && model.longitude == nil) { + if model.selectionType == .timezone, model.latitude == nil, model.longitude == nil { sunriseImage.isHidden = true } diff --git a/Clocker/Preferences/About/AboutViewController.swift b/Clocker/Preferences/About/AboutViewController.swift index d7f9d17..c5868d4 100644 --- a/Clocker/Preferences/About/AboutViewController.swift +++ b/Clocker/Preferences/About/AboutViewController.swift @@ -33,7 +33,7 @@ class AboutViewController: ParentViewController { setup() - themeDidChangeNotification = NotificationCenter.default.addObserver(forName: .themeDidChangeNotification, object: nil, queue: OperationQueue.main) { (_) in + themeDidChangeNotification = NotificationCenter.default.addObserver(forName: .themeDidChangeNotification, object: nil, queue: OperationQueue.main) { _ in self.setup() } } @@ -46,16 +46,14 @@ class AboutViewController: ParentViewController { private func underlineTextForActionButton() { let rangesInOrder = [NSRange(location: 3, length: 8), - NSRange(location: 7, length: privateFeedback.attributedTitle.length - 7), - NSRange(location: 27, length: 33), - NSRange(location: 32, length: 30) - ] + NSRange(location: 7, length: privateFeedback.attributedTitle.length - 7), + NSRange(location: 27, length: 33), + NSRange(location: 32, length: 30)] let buttonsInOrder = [quickCommentAction, - privateFeedback, - supportClocker, - openSourceButton - ] + privateFeedback, + supportClocker, + openSourceButton] let localizedKeys = ["1. @n0shake on Twitter for quick comments", "2. For Private Feedback", @@ -87,10 +85,10 @@ class AboutViewController: ParentViewController { value: Themer.shared().mainTextColor(), range: NSRange(location: 0, length: underlinedButton.attributedTitle.string.count)) originalText.addAttribute(NSAttributedString.Key.font, - value: (button?.font)! , + value: (button?.font)!, range: NSRange(location: 0, length: underlinedButton.attributedTitle.string.count)) originalText.addAttribute(NSAttributedString.Key.paragraphStyle, - value: mutableParaghStyle , + value: mutableParaghStyle, range: NSRange(location: 0, length: underlinedButton.attributedTitle.string.count)) underlinedButton.attributedTitle = originalText } @@ -126,7 +124,6 @@ class AboutViewController: ParentViewController { let custom: [String: Any] = ["Country": countryCode] Logger.log(object: custom, for: "Report Issue Opened") } - } @IBAction func openGitHub(_: Any) { @@ -139,7 +136,7 @@ class AboutViewController: ParentViewController { Logger.log(object: custom, for: "Opened GitHub") } - @IBOutlet weak var feedbackLabel: NSTextField! + @IBOutlet var feedbackLabel: NSTextField! private func setup() { feedbackLabel.stringValue = "Feedback is always welcome:" diff --git a/Clocker/Preferences/App Feedback/AppFeedbackWindowController.swift b/Clocker/Preferences/App Feedback/AppFeedbackWindowController.swift index 1dd813e..d332307 100644 --- a/Clocker/Preferences/App Feedback/AppFeedbackWindowController.swift +++ b/Clocker/Preferences/App Feedback/AppFeedbackWindowController.swift @@ -155,7 +155,7 @@ class AppFeedbackWindowController: NSWindowController { AppFeedbackConstants.CLAppFeedbackEmailProperty: email, AppFeedbackConstants.CLAppFeedbackFeedbackProperty: appFeedbackProperty, AppFeedbackConstants.CLOperatingSystemVersion: osVersion, - AppFeedbackConstants.CLClockerVersion: versionInfo + AppFeedbackConstants.CLClockerVersion: versionInfo, ] return feedbackInfo diff --git a/Clocker/Preferences/Appearance/AppearanceViewController.swift b/Clocker/Preferences/Appearance/AppearanceViewController.swift index de7d5bc..f05bbda 100644 --- a/Clocker/Preferences/Appearance/AppearanceViewController.swift +++ b/Clocker/Preferences/Appearance/AppearanceViewController.swift @@ -8,10 +8,10 @@ class AppearanceViewController: ParentViewController { @IBOutlet var informationLabel: NSTextField! @IBOutlet var sliderDayRangePopup: NSPopUpButton! @IBOutlet var visualEffectView: NSVisualEffectView! - @IBOutlet weak var menubarMode: NSSegmentedControl! - @IBOutlet weak var includeDayInMenubarControl: NSSegmentedControl! - @IBOutlet weak var includeDateInMenubarControl: NSSegmentedControl! - @IBOutlet weak var includePlaceNameControl: NSSegmentedControl! + @IBOutlet var menubarMode: NSSegmentedControl! + @IBOutlet var includeDayInMenubarControl: NSSegmentedControl! + @IBOutlet var includeDateInMenubarControl: NSSegmentedControl! + @IBOutlet var includePlaceNameControl: NSSegmentedControl! private var themeDidChangeNotification: NSObjectProtocol? @@ -31,12 +31,12 @@ class AppearanceViewController: ParentViewController { "4 days", "5 days", "6 days", - "7 days" + "7 days", ]) setup() - themeDidChangeNotification = NotificationCenter.default.addObserver(forName: .themeDidChangeNotification, object: nil, queue: OperationQueue.main) { (_) in + themeDidChangeNotification = NotificationCenter.default.addObserver(forName: .themeDidChangeNotification, object: nil, queue: OperationQueue.main) { _ in self.setup() self.animateBackgroundColorChange() self.view.needsDisplay = true // Let's make the color change permanent. @@ -54,7 +54,7 @@ class AppearanceViewController: ParentViewController { colorAnimation.duration = 0.25 colorAnimation.fromValue = previousBackgroundColor.cgColor colorAnimation.toValue = Themer.shared().mainBackgroundColor().cgColor - self.view.layer?.add(colorAnimation, forKey: "backgroundColor") + view.layer?.add(colorAnimation, forKey: "backgroundColor") } override func viewWillAppear() { @@ -80,21 +80,21 @@ class AppearanceViewController: ParentViewController { updateMenubarControls(!shouldDisplayCompact) } - @IBOutlet weak var headerLabel: NSTextField! - @IBOutlet weak var timeFormatLabel: NSTextField! - @IBOutlet weak var panelTheme: NSTextField! - @IBOutlet weak var dayDisplayOptionsLabel: NSTextField! - @IBOutlet weak var showSliderLabel: NSTextField! - @IBOutlet weak var showSunriseLabel: NSTextField! - @IBOutlet weak var showSecondsLabel: NSTextField! - @IBOutlet weak var largerTextLabel: NSTextField! - @IBOutlet weak var futureSliderRangeLabel: NSTextField! - @IBOutlet weak var includeDateLabel: NSTextField! - @IBOutlet weak var includeDayLabel: NSTextField! - @IBOutlet weak var includePlaceLabel: NSTextField! - @IBOutlet weak var menubarDisplayOptionsLabel: NSTextField! - @IBOutlet weak var appDisplayLabel: NSTextField! - @IBOutlet weak var menubarModeLabel: NSTextField! + @IBOutlet var headerLabel: NSTextField! + @IBOutlet var timeFormatLabel: NSTextField! + @IBOutlet var panelTheme: NSTextField! + @IBOutlet var dayDisplayOptionsLabel: NSTextField! + @IBOutlet var showSliderLabel: NSTextField! + @IBOutlet var showSunriseLabel: NSTextField! + @IBOutlet var showSecondsLabel: NSTextField! + @IBOutlet var largerTextLabel: NSTextField! + @IBOutlet var futureSliderRangeLabel: NSTextField! + @IBOutlet var includeDateLabel: NSTextField! + @IBOutlet var includeDayLabel: NSTextField! + @IBOutlet var includePlaceLabel: NSTextField! + @IBOutlet var menubarDisplayOptionsLabel: NSTextField! + @IBOutlet var appDisplayLabel: NSTextField! + @IBOutlet var menubarModeLabel: NSTextField! private func setup() { headerLabel.stringValue = "Main Panel Options" @@ -136,7 +136,6 @@ class AppearanceViewController: ParentViewController { private var previousBackgroundColor: NSColor = NSColor.white @IBAction func themeChanged(_ sender: NSSegmentedControl) { - previousBackgroundColor = Themer.shared().mainBackgroundColor() Themer.shared().set(theme: sender.selectedSegment) @@ -208,7 +207,6 @@ class AppearanceViewController: ParentViewController { } @IBAction func changeAppDisplayOptions(_ sender: NSSegmentedControl) { - if sender.selectedSegment == 0 { Logger.log(object: ["Selection": "Menubar"], for: "Dock Mode") NSApp.setActivationPolicy(.accessory) @@ -220,7 +218,7 @@ class AppearanceViewController: ParentViewController { private func refresh(panel: Bool, floating: Bool) { OperationQueue.main.addOperation { - if panel && DataStore.shared().shouldDisplay(ViewType.showAppInForeground) == false { + if panel, DataStore.shared().shouldDisplay(ViewType.showAppInForeground) == false { guard let panelController = PanelController.panel() else { return } let futureSliderBounds = panelController.futureSlider.bounds @@ -232,7 +230,7 @@ class AppearanceViewController: ParentViewController { panelController.setupMenubarTimer() } - if floating && DataStore.shared().shouldDisplay(ViewType.showAppInForeground) { + if floating, DataStore.shared().shouldDisplay(ViewType.showAppInForeground) { if DataStore.shared().shouldDisplay(ViewType.showAppInForeground) { let floatingWindow = FloatingWindowController.shared() floatingWindow.updateTableContent() @@ -246,16 +244,16 @@ class AppearanceViewController: ParentViewController { } } - @IBAction func displayDayInMenubarAction(_ sender: Any) { + @IBAction func displayDayInMenubarAction(_: Any) { DataStore.shared().updateDayPreference() updateStatusItem() } - @IBAction func displayDateInMenubarAction(_ sender: Any) { + @IBAction func displayDateInMenubarAction(_: Any) { updateStatusItem() } - @IBAction func displayPlaceInMenubarAction(_ sender: Any) { + @IBAction func displayPlaceInMenubarAction(_: Any) { updateStatusItem() } @@ -285,7 +283,6 @@ class AppearanceViewController: ParentViewController { } else { Logger.log(object: ["Context": "In Appearance View"], for: "Switched to Standard Mode") } - } // We don't support showing day or date in the menubar for compact mode yet. diff --git a/Clocker/Preferences/Calendar/CalendarViewController.swift b/Clocker/Preferences/Calendar/CalendarViewController.swift index 93df181..cc8920f 100644 --- a/Clocker/Preferences/Calendar/CalendarViewController.swift +++ b/Clocker/Preferences/Calendar/CalendarViewController.swift @@ -4,7 +4,6 @@ import Cocoa import EventKit class ClockerTextBackgroundView: NSView { - private var themeDidChangeNotification: NSObjectProtocol? override func awakeFromNib() { @@ -13,7 +12,7 @@ class ClockerTextBackgroundView: NSView { layer?.masksToBounds = false layer?.backgroundColor = Themer.shared().textBackgroundColor().cgColor - themeDidChangeNotification = NotificationCenter.default.addObserver(forName: .themeDidChangeNotification, object: nil, queue: OperationQueue.main) { (_) in + themeDidChangeNotification = NotificationCenter.default.addObserver(forName: .themeDidChangeNotification, object: nil, queue: OperationQueue.main) { _ in self.layer?.backgroundColor = Themer.shared().textBackgroundColor().cgColor } } @@ -31,18 +30,17 @@ class ClockerTextBackgroundView: NSView { } class CalendarViewController: ParentViewController { - @IBOutlet var showSegmentedControl: NSSegmentedControl! @IBOutlet var allDaysSegmentedControl: NSSegmentedControl! @IBOutlet var truncateTextField: NSTextField! @IBOutlet var noAccessView: NSVisualEffectView! @IBOutlet var informationField: NSTextField! @IBOutlet var grantAccessButton: NSButton! - @IBOutlet weak var calendarsTableView: NSTableView! + @IBOutlet var calendarsTableView: NSTableView! - @IBOutlet weak var showNextMeetingInMenubarControl: NSSegmentedControl! - @IBOutlet weak var backgroundView: NSView! - @IBOutlet weak var nextMeetingBackgroundView: NSView! + @IBOutlet var showNextMeetingInMenubarControl: NSSegmentedControl! + @IBOutlet var backgroundView: NSView! + @IBOutlet var nextMeetingBackgroundView: NSView! private var themeDidChangeNotification: NSObjectProtocol? private lazy var calendars: [Any] = EventCenter.sharedCenter().fetchSourcesAndCalendars() @@ -57,7 +55,7 @@ class CalendarViewController: ParentViewController { name: .calendarAccessGranted, object: nil) - themeDidChangeNotification = NotificationCenter.default.addObserver(forName: .themeDidChangeNotification, object: nil, queue: OperationQueue.main) { (_) in + themeDidChangeNotification = NotificationCenter.default.addObserver(forName: .themeDidChangeNotification, object: nil, queue: OperationQueue.main) { _ in self.setup() } @@ -91,7 +89,7 @@ class CalendarViewController: ParentViewController { } // If the menubar mode is compact, we can't show meetings in the menubar. So disable toggling that option. - showNextMeetingInMenubarControl.isEnabled = !(DataStore.shared().shouldDisplay(.menubarCompactMode)) + showNextMeetingInMenubarControl.isEnabled = !DataStore.shared().shouldDisplay(.menubarCompactMode) } private func verifyCalendarAccess() { @@ -102,7 +100,7 @@ class CalendarViewController: ParentViewController { noAccessView.isHidden = hasCalendarAccess if hasNotDeterminedCalendarAccess { - informationField.stringValue = "Clocker is more useful when it can display events from your calendars." + informationField.stringValue = "Clocker is more useful when it can display events from your calendars." setGrantAccess(title: "Grant Access") } else if hasDeniedCalendarAccess { // The informationField text is taken care off in the XIB. Just set the grant button to empty because we can't do anything. @@ -121,7 +119,7 @@ class CalendarViewController: ParentViewController { let attributesDictionary: [NSAttributedString.Key: Any] = [ NSAttributedString.Key.paragraphStyle: style, NSAttributedString.Key.font: boldFont, - NSAttributedString.Key.foregroundColor: Themer.shared().mainTextColor() + NSAttributedString.Key.foregroundColor: Themer.shared().mainTextColor(), ] let attributedString = NSAttributedString(string: title, attributes: attributesDictionary) @@ -146,7 +144,6 @@ class CalendarViewController: ParentViewController { } @IBAction func showNextMeetingAction(_ sender: NSSegmentedControl) { - // We need to start the menubar timer if it hasn't been started already guard let delegate = NSApplication.shared.delegate as? AppDelegate else { assertionFailure() @@ -156,7 +153,6 @@ class CalendarViewController: ParentViewController { let statusItemHandler = delegate.statusItemForPanel() if sender.selectedSegment == 0 { - if let isValid = statusItemHandler.menubarTimer?.isValid, isValid == true { print("Timer is already in progress") updateStatusItem() @@ -164,10 +160,8 @@ class CalendarViewController: ParentViewController { } } else { - statusItemHandler.invalidateTimer(showIcon: true, isSyncing: false) } - } @IBAction func showUpcomingEventView(_ sender: NSSegmentedControl) { @@ -203,26 +197,26 @@ class CalendarViewController: ParentViewController { statusItem.performTimerWork() } - @IBOutlet weak var headerLabel: NSTextField! - @IBOutlet weak var upcomingEventView: NSTextField! - @IBOutlet weak var allDayMeetingsLabel: NSTextField! - @IBOutlet weak var showNextMeetingLabel: NSTextField! - @IBOutlet weak var nextMeetingAccessoryLabel: NSTextField! - @IBOutlet weak var truncateTextLabel: NSTextField! - @IBOutlet weak var showEventsFromLabel: NSTextField! - @IBOutlet weak var charactersField: NSTextField! - @IBOutlet weak var truncateAccessoryLabel: NSTextField! + @IBOutlet var headerLabel: NSTextField! + @IBOutlet var upcomingEventView: NSTextField! + @IBOutlet var allDayMeetingsLabel: NSTextField! + @IBOutlet var showNextMeetingLabel: NSTextField! + @IBOutlet var nextMeetingAccessoryLabel: NSTextField! + @IBOutlet var truncateTextLabel: NSTextField! + @IBOutlet var showEventsFromLabel: NSTextField! + @IBOutlet var charactersField: NSTextField! + @IBOutlet var truncateAccessoryLabel: NSTextField! private func setup() { // Grant access button's text color is taken care above. - headerLabel.stringValue = "Upcoming Event View Options" - upcomingEventView.stringValue = "Show Upcoming Event View" - allDayMeetingsLabel.stringValue = "Show All Day Meetings" + headerLabel.stringValue = "Upcoming Event View Options" + upcomingEventView.stringValue = "Show Upcoming Event View" + allDayMeetingsLabel.stringValue = "Show All Day Meetings" showNextMeetingLabel.stringValue = "Show Next Meeting Title in Menubar" - truncateTextLabel.stringValue = "Truncate menubar text longer than" - charactersField.stringValue = "characters" - showEventsFromLabel.stringValue = "Show events from" - truncateAccessoryLabel.stringValue = "If meeting title is \"Meeting with Neel\" and truncate length is set to 5, text in menubar will appear as \"Meeti...\"" + truncateTextLabel.stringValue = "Truncate menubar text longer than" + charactersField.stringValue = "characters" + showEventsFromLabel.stringValue = "Show events from" + truncateAccessoryLabel.stringValue = "If meeting title is \"Meeting with Neel\" and truncate length is set to 5, text in menubar will appear as \"Meeti...\"" [headerLabel, upcomingEventView, allDayMeetingsLabel, showNextMeetingLabel, nextMeetingAccessoryLabel, truncateTextLabel, @@ -231,21 +225,18 @@ class CalendarViewController: ParentViewController { } extension CalendarViewController: NSTableViewDataSource { - - func numberOfRows(in tableView: NSTableView) -> Int { + func numberOfRows(in _: NSTableView) -> Int { let hasCalendarAccess = EventCenter.sharedCenter().calendarAccessGranted() return hasCalendarAccess ? calendars.count : 0 } } extension CalendarViewController: NSTableViewDelegate { - - func tableView(_ tableView: NSTableView, shouldSelectRow row: Int) -> Bool { + func tableView(_: NSTableView, shouldSelectRow _: Int) -> Bool { return false } - func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat { - + func tableView(_: NSTableView, heightOfRow row: Int) -> CGFloat { guard let currentSource = calendars[row] as? String, !currentSource.isEmpty else { return 30.0 } @@ -253,8 +244,7 @@ extension CalendarViewController: NSTableViewDelegate { return 24.0 } - func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { - + func tableView(_ tableView: NSTableView, viewFor _: NSTableColumn?, row: Int) -> NSView? { if let currentSource = calendars[row] as? String, let message = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "sourceCellView"), owner: self) as? SourceTableViewCell { message.sourceName.stringValue = currentSource @@ -273,7 +263,6 @@ extension CalendarViewController: NSTableViewDelegate { } return nil - } @objc func calendarSelected(_ checkbox: NSButton) { @@ -290,7 +279,6 @@ extension CalendarViewController: NSTableViewDelegate { } private func updateSelectedCalendars(_ selection: [Any]) { - var selectedCalendars: [String] = [] for obj in selection { diff --git a/Clocker/Preferences/General/PreferencesViewController.swift b/Clocker/Preferences/General/PreferencesViewController.swift index c0d5a15..c4e92a1 100644 --- a/Clocker/Preferences/General/PreferencesViewController.swift +++ b/Clocker/Preferences/General/PreferencesViewController.swift @@ -70,7 +70,7 @@ class PreferencesViewController: ParentViewController { @IBOutlet private var headerView: NSView! @IBOutlet private var tableview: NSView! @IBOutlet private var additionalSortOptions: NSView! - @IBOutlet weak var startAtLoginLabel: NSTextField! + @IBOutlet var startAtLoginLabel: NSTextField! @IBOutlet var startupCheckbox: NSButton! @IBOutlet var headerLabel: NSTextField! @@ -198,7 +198,7 @@ class PreferencesViewController: ParentViewController { } let archivedObjects = menubarTimes.map { (timezone) -> Data in - return NSKeyedArchiver.archivedData(withRootObject: timezone) + NSKeyedArchiver.archivedData(withRootObject: timezone) } UserDefaults.standard.set(archivedObjects, forKey: CLMenubarFavorites) @@ -244,7 +244,7 @@ class PreferencesViewController: ParentViewController { [timezoneNameSortButton, labelSortButton, timezoneSortButton].forEach { $0?.attributedTitle = NSAttributedString(string: $0?.title ?? CLEmptyString, attributes: [ NSAttributedString.Key.foregroundColor: Themer.shared().mainTextColor(), - NSAttributedString.Key.font: NSFont(name: "Avenir-Light", size: 13)! + NSAttributedString.Key.font: NSFont(name: "Avenir-Light", size: 13)!, ]) } @@ -362,7 +362,7 @@ extension PreferencesViewController: NSTableViewDataSource, NSTableViewDelegate return nil } - private func handleTimezoneNameIdentifier(for row: Int, _ selectedDataSource: TimezoneData?) -> Any? { + private func handleTimezoneNameIdentifier(for _: Int, _ selectedDataSource: TimezoneData?) -> Any? { guard let model = selectedDataSource else { return nil } @@ -382,7 +382,7 @@ extension PreferencesViewController: NSTableViewDataSource, NSTableViewDelegate return dataSource?.formattedAddress } } else { - if searchField.stringValue.isEmpty == false && row < timezoneFilteredArray.count { + if searchField.stringValue.isEmpty == false, row < timezoneFilteredArray.count { return timezoneFilteredArray[row] } return timezoneArray[row] @@ -391,7 +391,7 @@ extension PreferencesViewController: NSTableViewDataSource, NSTableViewDelegate } private func handleAbbreviationColumn(for row: Int) -> Any? { - if searchField.stringValue.isEmpty == false && (row < timezoneFilteredArray.count) { + if searchField.stringValue.isEmpty == false, row < timezoneFilteredArray.count { let currentSelection = timezoneFilteredArray[row] if currentSelection == "UTC" { return "UTC" @@ -497,8 +497,8 @@ extension PreferencesViewController: NSTableViewDataSource, NSTableViewDelegate if selectedTimeZones.count > row { Logger.log(object: [ "Old Label": dataObject.customLabel ?? "Error", - "New Label": formattedValue - ], + "New Label": formattedValue, + ], for: "Custom Label Changed") dataObject.setLabel(formattedValue) @@ -510,25 +510,24 @@ extension PreferencesViewController: NSTableViewDataSource, NSTableViewDelegate Logger.log(object: [ "MethodName": "SetObjectValue", "Selected Timezone Count": selectedTimeZones.count, - "Current Row": row - ], + "Current Row": row, + ], for: "Error in selected row count") } } private func showAlertIfMoreThanOneTimezoneHasBeenAddedToTheMenubar() { - let isUITestRunning = ProcessInfo.processInfo.arguments.contains(CLUITestingLaunchArgument) // If we have seen displayed the message before, abort! let haveWeSeenThisMessageBefore = UserDefaults.standard.bool(forKey: CLLongStatusBarWarningMessage) - if haveWeSeenThisMessageBefore && !isUITestRunning { + if haveWeSeenThisMessageBefore, !isUITestRunning { return } // If the user is already using the compact mode, abort. - if DataStore.shared().shouldDisplay(.menubarCompactMode) && !isUITestRunning { + if DataStore.shared().shouldDisplay(.menubarCompactMode), !isUITestRunning { return } @@ -692,7 +691,7 @@ extension PreferencesViewController { self.dataTask = NetworkManager.task(with: self.generateSearchURL(), completionHandler: { [weak self] response, error in - guard let `self` = self else { return } + guard let self = self else { return } OperationQueue.main.addOperation { if let errorPresent = error { @@ -734,12 +733,12 @@ extension PreferencesViewController { private func presentError(_ errorMessage: String) { if errorMessage == PreferencesConstants.offlineErrorMessage { - self.placeholderLabel.placeholderString = PreferencesConstants.noInternetConnectivityError + placeholderLabel.placeholderString = PreferencesConstants.noInternetConnectivityError } else { - self.placeholderLabel.placeholderString = PreferencesConstants.tryAgainMessage + placeholderLabel.placeholderString = PreferencesConstants.tryAgainMessage } - self.isActivityInProgress = false + isActivityInProgress = false } private func appendResultsToFilteredArray(_ results: [SearchResult.Result]) { @@ -755,17 +754,17 @@ extension PreferencesViewController { CLTimezoneName: formattedAddress, CLCustomLabel: formattedAddress, CLTimezoneID: CLEmptyString, - CLPlaceIdentifier: $0.placeId - ] as [String: Any] + CLPlaceIdentifier: $0.placeId, + ] as [String: Any] self.filteredArray.append(TimezoneData(with: totalPackage)) } } private func prepareUIForPresentingResults() { - self.placeholderLabel.placeholderString = CLEmptyString - self.isActivityInProgress = false - self.availableTimezoneTableView.reloadData() + placeholderLabel.placeholderString = CLEmptyString + isActivityInProgress = false + availableTimezoneTableView.reloadData() } // Extracting this out for tests @@ -821,7 +820,7 @@ extension PreferencesViewController { NetworkManager.task(with: urlString) { [weak self] response, error in - guard let `self` = self else { return } + guard let self = self else { return } OperationQueue.main.addOperation { if self.handleEdgeCase(for: response) == true { @@ -829,7 +828,7 @@ extension PreferencesViewController { } if error == nil, let json = response, let timezone = self.decodeTimezone(from: json) { - if self.availableTimezoneTableView.selectedRow >= 0 && self.availableTimezoneTableView.selectedRow < self.filteredArray.count { + if self.availableTimezoneTableView.selectedRow >= 0, self.availableTimezoneTableView.selectedRow < self.filteredArray.count { self.installTimezone(timezone) } self.updateViewState() @@ -867,8 +866,8 @@ extension PreferencesViewController { "latitude": dataObject.latitude!, "longitude": dataObject.longitude!, "nextUpdate": CLEmptyString, - CLCustomLabel: filteredAddress - ] as [String: Any] + CLCustomLabel: filteredAddress, + ] as [String: Any] let timezoneObject = TimezoneData(with: newTimeZone) let operationsObject = TimezoneDataOperations(with: timezoneObject) @@ -1118,7 +1117,7 @@ extension PreferencesViewController { var newDefaults = selectedTimeZones let objectsToRemove = timezoneTableView.selectedRowIndexes.map { (index) -> Data in - return selectedTimeZones[index] + selectedTimeZones[index] } newDefaults = newDefaults.filter { !objectsToRemove.contains($0) } @@ -1331,8 +1330,7 @@ extension PreferencesViewController { } } -extension PreferencesViewController: SRRecorderControlDelegate { -} +extension PreferencesViewController: SRRecorderControlDelegate {} // Helpers extension PreferencesViewController { diff --git a/Clocker/Preferences/OneWindowController.swift b/Clocker/Preferences/OneWindowController.swift index 1acecb5..4ae97b6 100644 --- a/Clocker/Preferences/OneWindowController.swift +++ b/Clocker/Preferences/OneWindowController.swift @@ -3,15 +3,14 @@ import Cocoa class CenteredTabViewController: NSTabViewController { - override func toolbarDefaultItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { super.toolbarDefaultItemIdentifiers(toolbar) var toolbarItems: [NSToolbarItem.Identifier] = [NSToolbarItem.Identifier.flexibleSpace] - tabViewItems.forEach { (item) in + tabViewItems.forEach { item in if let identifier = item.identifier as? String { - toolbarItems.append(NSToolbarItem.Identifier.init(identifier)) + toolbarItems.append(NSToolbarItem.Identifier(identifier)) } } @@ -19,11 +18,9 @@ class CenteredTabViewController: NSTabViewController { return toolbarItems } - } class OneWindowController: NSWindowController { - private static var sharedWindow: OneWindowController! private var themeDidChangeNotification: NSObjectProtocol? @@ -31,13 +28,13 @@ class OneWindowController: NSWindowController { super.windowDidLoad() setup() - themeDidChangeNotification = NotificationCenter.default.addObserver(forName: .themeDidChangeNotification, object: nil, queue: OperationQueue.main) { (_) in + themeDidChangeNotification = NotificationCenter.default.addObserver(forName: .themeDidChangeNotification, object: nil, queue: OperationQueue.main) { _ in - NSAnimationContext.runAnimationGroup({ (context) in + NSAnimationContext.runAnimationGroup { context in context.duration = 1 context.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) self.window?.animator().backgroundColor = Themer.shared().mainBackgroundColor() - }) + } self.setupToolbarImages() } @@ -61,7 +58,7 @@ class OneWindowController: NSWindowController { class func shared() -> OneWindowController { if sharedWindow == nil { - let prefStoryboard = NSStoryboard.init(name: "Preferences", bundle: nil) + let prefStoryboard = NSStoryboard(name: "Preferences", bundle: nil) sharedWindow = prefStoryboard.instantiateInitialController() as? OneWindowController } return sharedWindow @@ -72,7 +69,7 @@ class OneWindowController: NSWindowController { return } - if !(window.isMainWindow) || !(window.isVisible) { + if !window.isMainWindow || !window.isVisible { showWindow(nil) } @@ -93,12 +90,11 @@ class OneWindowController: NSWindowController { "Calendar": themer.calendarTabImage(), "Permissions": themer.privacyTabImage()] - tabViewController.tabViewItems.forEach { (tabViewItem) in + tabViewController.tabViewItems.forEach { tabViewItem in let identity = (tabViewItem.identifier as? String) ?? "" if identifierTOImageMapping[identity] != nil { tabViewItem.image = identifierTOImageMapping[identity] } } } - } diff --git a/Clocker/Preferences/Permissions/PermissionsViewController.swift b/Clocker/Preferences/Permissions/PermissionsViewController.swift index bf532bc..aeb6bfb 100644 --- a/Clocker/Preferences/Permissions/PermissionsViewController.swift +++ b/Clocker/Preferences/Permissions/PermissionsViewController.swift @@ -3,7 +3,6 @@ import Cocoa class PermissionsViewController: ParentViewController { - @IBOutlet var calendarContainerView: NSView! @IBOutlet var remindersContainerView: NSView! @@ -129,7 +128,6 @@ class PermissionsViewController: ParentViewController { if granted { OperationQueue.main.addOperation { - self.view.window?.orderBack(nil) NSApp.activate(ignoringOtherApps: true) @@ -163,7 +161,6 @@ class PermissionsViewController: ParentViewController { if granted { OperationQueue.main.addOperation { - self.view.window?.orderBack(nil) NSApp.activate(ignoringOtherApps: true)