From d9d6b8beeb2fb189941f896afa1dbdeb645c8c2f Mon Sep 17 00:00:00 2001 From: Abhishek Date: Sat, 26 Mar 2022 19:24:11 -0400 Subject: [PATCH 01/16] Formatting.. --- Clocker/AppDelegate.swift | 2 +- .../ClockerUnitTests/ClockerUnitTests.swift | 40 +++++++------- Clocker/ClockerUnitTests/ThemerTests.swift | 44 ++++++--------- .../Sources/CoreModelKit/SearchResults.swift | 10 ++-- .../Sources/CoreModelKit/TimezoneData.swift | 6 +-- .../Date Additions/TimePeriodChain.swift | 6 +-- .../CalendarHandler.swift | 6 ++- .../RemindersHandler.swift | 3 +- Clocker/Menu Bar/StatusContainerView.swift | 6 ++- Clocker/Menu Bar/StatusItemHandler.swift | 5 +- .../FinalOnboardingViewController.swift | 2 +- .../OnboardingSearchController.swift | 9 ++-- Clocker/Overall App/DataStore.swift | 10 ++-- Clocker/Overall App/NetworkManager.swift | 2 +- Clocker/Overall App/Themer.swift | 54 ++++++++++--------- Clocker/Overall App/Timer.swift | 2 +- .../Overall App/VersionUpdateHandler.swift | 2 +- .../Data Layer/TimezoneDataOperations.swift | 2 +- .../Panel/Notes Popover/NotesPopover.swift | 8 +-- Clocker/Panel/PanelController.swift | 23 ++++---- .../ParentPanelController+ModernSlider.swift | 2 +- Clocker/Panel/ParentPanelController.swift | 45 +++++++++------- .../Rate Controller/ReviewController.swift | 4 +- Clocker/Panel/UI/TimezoneCellView.swift | 6 +-- Clocker/Panel/UI/TimezoneDataSource.swift | 2 +- .../UpcomingEventViewItem.swift | 3 +- .../About/AboutViewController.swift | 6 +-- .../AppFeedbackWindowController.swift | 15 +++--- .../Appearance/AppearanceViewController.swift | 3 +- .../Calendar/CalendarViewController.swift | 6 ++- .../General/PreferencesDataSource.swift | 7 +-- .../General/PreferencesViewController.swift | 37 ++++++------- .../Menu Bar/StatusContainerView.swift | 6 ++- .../Menu Bar/StatusItemHandler.swift | 13 ++--- .../UpcomingEventStatusItemView.swift | 1 + Clocker/Preferences/OneWindowController.swift | 8 +-- 36 files changed, 210 insertions(+), 196 deletions(-) diff --git a/Clocker/AppDelegate.swift b/Clocker/AppDelegate.swift index cfcac83..a2d76ec 100644 --- a/Clocker/AppDelegate.swift +++ b/Clocker/AppDelegate.swift @@ -16,7 +16,7 @@ open class AppDelegate: NSObject, NSApplicationDelegate { panelObserver?.invalidate() } - open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change _: [NSKeyValueChangeKey: Any]?, context _: UnsafeMutableRawPointer?) { + override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change _: [NSKeyValueChangeKey: Any]?, context _: UnsafeMutableRawPointer?) { if let path = keyPath, path == PreferencesConstants.hotKeyPathIdentifier { let hotKeyCenter = PTHotKeyCenter.shared() diff --git a/Clocker/ClockerUnitTests/ClockerUnitTests.swift b/Clocker/ClockerUnitTests/ClockerUnitTests.swift index 13cf265..48e8b5d 100644 --- a/Clocker/ClockerUnitTests/ClockerUnitTests.swift +++ b/Clocker/ClockerUnitTests/ClockerUnitTests.swift @@ -105,31 +105,31 @@ class ClockerUnitTests: XCTestCase { XCTAssert(newDefaults.isEmpty == false) XCTAssert(newDefaults.count == oldCount + 1) } - + func testDecoding() { let timezone1 = TimezoneData.customObject(from: nil) XCTAssertNotNil(timezone1) - + let data = Data() let timezone2 = TimezoneData.customObject(from: data) XCTAssertNil(timezone2) } - + func testDescription() { let timezoneData = TimezoneData(with: california) XCTAssertFalse(timezoneData.description.isEmpty) XCTAssertFalse(timezoneData.debugDescription.isEmpty) } - + func testHashing() { let timezoneData = TimezoneData(with: california) XCTAssert(timezoneData.hash != -1) - + timezoneData.placeID = nil timezoneData.timezoneID = nil XCTAssert(timezoneData.hash == -1) } - + func testBadInputDictionaryForInitialization() { let badInput: [String: Any] = ["customLabel": "", "latitude": "41.2565369", @@ -234,7 +234,7 @@ class ClockerUnitTests: XCTestCase { dataObject.setShouldOverrideGlobalTimeFormat(11) // 12-hour with preceding zero and seconds XCTAssertTrue(dataObject.timezoneFormat(DataStore.shared().timezoneFormat()) == "hh:mm:ss") - + // Wrong input dataObject.setShouldOverrideGlobalTimeFormat(0) // 12-hour with preceding zero and seconds XCTAssertTrue(dataObject.timezoneFormat(88) == "h:mm a") @@ -274,47 +274,47 @@ class ClockerUnitTests: XCTestCase { dataObject.setShouldOverrideGlobalTimeFormat(11) // 12-hour with preceding zero and seconds XCTAssertTrue(dataObject.timezoneFormat(DataStore.shared().timezoneFormat()) == "hh:mm:ss") - + dataObject.setShouldOverrideGlobalTimeFormat(12) // 12-hour with preceding zero and seconds XCTAssertTrue(dataObject.timezoneFormat(DataStore.shared().timezoneFormat()) == "epoch") } - + func testSecondsDisplayForOverridenTimezone() { let dataObject = TimezoneData(with: california) UserDefaults.standard.set(NSNumber(value: 1), forKey: CLSelectedTimeZoneFormatKey) // Set to 24-Hour Format // Test default behaviour - let timezoneWithSecondsKeys = [4,5,8,11] + let timezoneWithSecondsKeys = [4, 5, 8, 11] for timezoneKey in timezoneWithSecondsKeys { dataObject.setShouldOverrideGlobalTimeFormat(timezoneKey) XCTAssertTrue(dataObject.shouldShowSeconds(DataStore.shared().timezoneFormat())) } - - let timezoneWithoutSecondsKeys = [1,2,7,10] + + let timezoneWithoutSecondsKeys = [1, 2, 7, 10] for timezoneKey in timezoneWithoutSecondsKeys { dataObject.setShouldOverrideGlobalTimeFormat(timezoneKey) XCTAssertFalse(dataObject.shouldShowSeconds(DataStore.shared().timezoneFormat())) } - + // Test wrong override timezone key let wrongTimezoneKey = 88 dataObject.setShouldOverrideGlobalTimeFormat(wrongTimezoneKey) XCTAssertFalse(dataObject.shouldShowSeconds(DataStore.shared().timezoneFormat())) - + // Test wrong global preference key dataObject.setShouldOverrideGlobalTimeFormat(0) XCTAssertFalse(dataObject.shouldShowSeconds(88)) } - + func testTimezoneRetrieval() { let dataObject = TimezoneData(with: mumbai) let autoupdatingTimezone = TimeZone.autoupdatingCurrent.identifier XCTAssertEqual(dataObject.timezone(), "Asia/Calcutta") - + // Unlikely dataObject.timezoneID = nil XCTAssertEqual(dataObject.timezone(), autoupdatingTimezone) - + dataObject.isSystemTimezone = true XCTAssertEqual(dataObject.timezone(), autoupdatingTimezone) } @@ -328,15 +328,15 @@ class ClockerUnitTests: XCTestCase { dataObject.formattedAddress = nil XCTAssertTrue(dataObject.formattedTimezoneLabel() == "Asia", "Incorrect custom label returned by model \(dataObject.formattedTimezoneLabel())") - + dataObject.setLabel("Jogeshwari") XCTAssertTrue(dataObject.formattedTimezoneLabel() == "Jogeshwari", "Incorrect custom label returned by model \(dataObject.formattedTimezoneLabel())") - + // Unlikely scenario dataObject.setLabel("") dataObject.timezoneID = "GMT" XCTAssertTrue(dataObject.formattedTimezoneLabel() == "GMT", "Incorrect custom label returned by model \(dataObject.formattedTimezoneLabel())") - + // Another unlikely scenario dataObject.setLabel("") dataObject.timezoneID = nil diff --git a/Clocker/ClockerUnitTests/ThemerTests.swift b/Clocker/ClockerUnitTests/ThemerTests.swift index a269a72..cf23798 100644 --- a/Clocker/ClockerUnitTests/ThemerTests.swift +++ b/Clocker/ClockerUnitTests/ThemerTests.swift @@ -5,16 +5,15 @@ import XCTest @testable import Clocker class ThemerTests: XCTestCase { - @available(macOS 10.14, *) func testSettingTheme() { // Set to some random number should set to 0 let subject = Themer(index: 124) XCTAssertEqual(NSAppearance(named: .aqua), NSAppearance(named: .aqua)) - + // Set the same theme; this should return early subject.set(theme: 0) - + // Set the theme to dark theme subject.set(theme: 1) let expectedApperance = NSAppearance(named: .darkAqua) @@ -28,8 +27,7 @@ class ThemerTests: XCTestCase { let expectedBackgroundColor = NSColor.white let expectedTextColor = NSColor.black let expectedTextBackgroundColor = NSColor(deviceRed: 241.0 / 255.0, green: 241.0 / 255.0, blue: 241.0 / 255.0, alpha: 1.0) - - + let expectedShutdownImageName = "ellipsis.circle" let expectedPreferenceImageName = "plus" let expectedPinImageName = "macwindow.on.rectangle" @@ -54,14 +52,13 @@ class ThemerTests: XCTestCase { let expectedBackwardsImage = "gobackward.15" let expectedForwardsImage = "goforward.15" let expectedResetSliderImage = "xmark.circle.fill" - XCTAssertEqual(subject.sliderKnobColor(), expectedSliderKnobColor) XCTAssertEqual(subject.sliderRightColor(), expectedSliderRightColor) XCTAssertEqual(subject.mainBackgroundColor(), expectedBackgroundColor) XCTAssertEqual(subject.mainTextColor(), expectedTextColor) XCTAssertEqual(subject.textBackgroundColor(), expectedTextBackgroundColor) - + XCTAssertEqual(subject.shutdownImage().accessibilityDescription, expectedShutdownImageName) XCTAssertEqual(subject.preferenceImage().accessibilityDescription, expectedPreferenceImageName) XCTAssertEqual(subject.pinImage().accessibilityDescription, expectedPinImageName) @@ -74,7 +71,7 @@ class ThemerTests: XCTestCase { XCTAssertEqual(subject.sharingImage().accessibilityDescription, expectedSharingImage) XCTAssertEqual(subject.currentLocationImage().accessibilityDescription, expectedCurrentLocationImage) XCTAssertEqual(subject.popoverAppearance(), expectedPopoverApperarance) - + XCTAssertEqual(subject.addImage().accessibilityDescription, expectedAddImage) XCTAssertEqual(subject.addImageHighlighted().name(), expectedAddImageHighlighted) XCTAssertEqual(subject.privacyTabImage().accessibilityDescription, expectedPrivacyTabImage) @@ -88,7 +85,7 @@ class ThemerTests: XCTestCase { XCTAssertEqual(subject.goForwardsImage()?.accessibilityDescription, expectedForwardsImage) XCTAssertEqual(subject.resetModernSliderImage()?.accessibilityDescription, expectedResetSliderImage) } - + func testDarkTheme() throws { let subject = Themer(index: 1) // 1 is for dark theme let expectedSliderKnobColor = NSColor(deviceRed: 0.0, green: 0.0, blue: 0, alpha: 0.9) @@ -96,8 +93,7 @@ class ThemerTests: XCTestCase { let expectedBackgroundColor = NSColor(deviceRed: 42.0 / 255.0, green: 42.0 / 255.0, blue: 42.0 / 255.0, alpha: 1.0) let expectedTextColor = NSColor.white let expectedTextBackgroundColor = NSColor(deviceRed: 42.0 / 255.0, green: 55.0 / 255.0, blue: 62.0 / 255.0, alpha: 1.0) - - + let expectedShutdownImageName = "ellipsis.circle" let expectedPreferenceImageName = "plus" let expectedPinImageName = "macwindow.on.rectangle" @@ -122,7 +118,6 @@ class ThemerTests: XCTestCase { let expectedBackwardsImage = "gobackward.15" let expectedForwardsImage = "goforward.15" let expectedResetSliderImage = "xmark.circle.fill" - XCTAssertEqual(subject.sliderKnobColor(), expectedSliderKnobColor) XCTAssertEqual(subject.sliderRightColor(), expectedSliderRightColor) @@ -155,18 +150,17 @@ class ThemerTests: XCTestCase { XCTAssertEqual(subject.resetModernSliderImage()?.accessibilityDescription, expectedResetSliderImage) XCTAssertEqual(subject.description, "Current Theme is \(Themer.Theme.dark)") } - + func testSystemTheme() throws { let currentSystemTheme = - UserDefaults.standard.string(forKey: "AppleUserInterfaceStyle")?.lowercased().contains("dark") ?? false ? Themer.Theme.dark : Themer.Theme.light + UserDefaults.standard.string(forKey: "AppleUserInterfaceStyle")?.lowercased().contains("dark") ?? false ? Themer.Theme.dark : Themer.Theme.light let subject = Themer(index: 2) // 2 is for system theme let expectedSliderKnobColor = currentSystemTheme == .light ? NSColor(deviceRed: 255.0, green: 255.0, blue: 255, alpha: 0.9) : NSColor(deviceRed: 0.0, green: 0.0, blue: 0, alpha: 0.9) let expectedSliderRightColor = currentSystemTheme == .dark ? NSColor.white : NSColor.gray let expectedBackgroundColor = currentSystemTheme == .dark ? NSColor(deviceRed: 42.0 / 255.0, green: 42.0 / 255.0, blue: 42.0 / 255.0, alpha: 1.0) : NSColor.white let expectedTextColor = NSColor.textColor let expectedTextBackgroundColor = currentSystemTheme == .dark ? NSColor(deviceRed: 42.0 / 255.0, green: 55.0 / 255.0, blue: 62.0 / 255.0, alpha: 1.0) : NSColor(deviceRed: 241.0 / 255.0, green: 241.0 / 255.0, blue: 241.0 / 255.0, alpha: 1.0) - - + let expectedShutdownImageName = "ellipsis.circle" let expectedPreferenceImageName = "plus" let expectedPinImageName = "macwindow.on.rectangle" @@ -191,7 +185,6 @@ class ThemerTests: XCTestCase { let expectedBackwardsImage = "gobackward.15" let expectedForwardsImage = "goforward.15" let expectedResetSliderImage = "xmark.circle.fill" - XCTAssertEqual(subject.sliderKnobColor(), expectedSliderKnobColor) XCTAssertEqual(subject.sliderRightColor(), expectedSliderRightColor) @@ -224,7 +217,7 @@ class ThemerTests: XCTestCase { XCTAssertEqual(subject.resetModernSliderImage()?.accessibilityDescription, expectedResetSliderImage) XCTAssertEqual(subject.description, "System Theme is \(currentSystemTheme == .dark ? Themer.Theme.dark : Themer.Theme.light)") } - + func testSolarizedLightTheme() throws { let subject = Themer(index: 3) // 3 is for solarized light theme let expectedSliderKnobColor = NSColor(deviceRed: 0.0, green: 0.0, blue: 0, alpha: 0.9) @@ -232,8 +225,7 @@ class ThemerTests: XCTestCase { let expectedBackgroundColor = NSColor(deviceRed: 253.0 / 255.0, green: 246.0 / 255.0, blue: 227.0 / 255.0, alpha: 1.0) let expectedTextColor = NSColor.black let expectedTextBackgroundColor = NSColor(deviceRed: 238.0 / 255.0, green: 232.0 / 255.0, blue: 213.0 / 255.0, alpha: 1.0) - - + let expectedShutdownImageName = "ellipsis.circle" let expectedPreferenceImageName = "plus" let expectedPinImageName = "macwindow.on.rectangle" @@ -258,14 +250,13 @@ class ThemerTests: XCTestCase { let expectedBackwardsImage = "gobackward.15" let expectedForwardsImage = "goforward.15" let expectedResetSliderImage = "xmark.circle.fill" - XCTAssertEqual(subject.sliderKnobColor(), expectedSliderKnobColor) XCTAssertEqual(subject.sliderRightColor(), expectedSliderRightColor) XCTAssertEqual(subject.mainBackgroundColor(), expectedBackgroundColor) XCTAssertEqual(subject.mainTextColor(), expectedTextColor) XCTAssertEqual(subject.textBackgroundColor(), expectedTextBackgroundColor) - + XCTAssertEqual(subject.shutdownImage().accessibilityDescription, expectedShutdownImageName) XCTAssertEqual(subject.preferenceImage().accessibilityDescription, expectedPreferenceImageName) XCTAssertEqual(subject.pinImage().accessibilityDescription, expectedPinImageName) @@ -278,7 +269,7 @@ class ThemerTests: XCTestCase { XCTAssertEqual(subject.sharingImage().accessibilityDescription, expectedSharingImage) XCTAssertEqual(subject.currentLocationImage().accessibilityDescription, expectedCurrentLocationImage) XCTAssertEqual(subject.popoverAppearance(), expectedPopoverApperarance) - + XCTAssertEqual(subject.addImage().accessibilityDescription, expectedAddImage) XCTAssertEqual(subject.addImageHighlighted().name(), expectedAddImageHighlighted) XCTAssertEqual(subject.privacyTabImage().accessibilityDescription, expectedPrivacyTabImage) @@ -292,7 +283,7 @@ class ThemerTests: XCTestCase { XCTAssertEqual(subject.goForwardsImage()?.accessibilityDescription, expectedForwardsImage) XCTAssertEqual(subject.resetModernSliderImage()?.accessibilityDescription, expectedResetSliderImage) } - + func testSolarizedDarkTheme() throws { let subject = Themer(index: 4) // 4 is for solarized dark theme let expectedSliderKnobColor = NSColor(deviceRed: 0.0, green: 0.0, blue: 0, alpha: 0.9) @@ -300,8 +291,7 @@ class ThemerTests: XCTestCase { let expectedBackgroundColor = NSColor(deviceRed: 7.0 / 255.0, green: 54.0 / 255.0, blue: 66.0 / 255.0, alpha: 1.0) let expectedTextColor = NSColor.white let expectedTextBackgroundColor = NSColor(deviceRed: 88.0 / 255.0, green: 110.0 / 255.0, blue: 117.0 / 255.0, alpha: 1.0) - - + let expectedShutdownImageName = "ellipsis.circle" let expectedPreferenceImageName = "plus" let expectedPinImageName = "macwindow.on.rectangle" @@ -326,7 +316,6 @@ class ThemerTests: XCTestCase { let expectedBackwardsImage = "gobackward.15" let expectedForwardsImage = "goforward.15" let expectedResetSliderImage = "xmark.circle.fill" - XCTAssertEqual(subject.sliderKnobColor(), expectedSliderKnobColor) XCTAssertEqual(subject.sliderRightColor(), expectedSliderRightColor) @@ -358,5 +347,4 @@ class ThemerTests: XCTestCase { XCTAssertEqual(subject.goForwardsImage()?.accessibilityDescription, expectedForwardsImage) XCTAssertEqual(subject.resetModernSliderImage()?.accessibilityDescription, expectedResetSliderImage) } - } diff --git a/Clocker/CoreModelKit/Sources/CoreModelKit/SearchResults.swift b/Clocker/CoreModelKit/Sources/CoreModelKit/SearchResults.swift index 64341d1..84f8719 100644 --- a/Clocker/CoreModelKit/Sources/CoreModelKit/SearchResults.swift +++ b/Clocker/CoreModelKit/Sources/CoreModelKit/SearchResults.swift @@ -2,7 +2,7 @@ import Cocoa -public struct ResultStatus { +public enum ResultStatus { public static let okay = "OK" public static let zeroResults = "ZERO_RESULTS" public static let requestDenied = "REQUEST_DENIED" @@ -12,7 +12,7 @@ public struct SearchResult: Codable { public let results: [Result] public let status: String public let errorMessage: String? - + public struct Result: Codable { public let addressComponents: [AddressComponent] public let formattedAddress: String @@ -55,10 +55,10 @@ public struct SearchResult: Codable { case types } } - + private enum CodingKeys: String, CodingKey { - case results = "results" - case status = "status" + case results + case status case errorMessage = "error_message" } } diff --git a/Clocker/CoreModelKit/Sources/CoreModelKit/TimezoneData.swift b/Clocker/CoreModelKit/Sources/CoreModelKit/TimezoneData.swift index 0c0d6bf..ec66b4c 100644 --- a/Clocker/CoreModelKit/Sources/CoreModelKit/TimezoneData.swift +++ b/Clocker/CoreModelKit/Sources/CoreModelKit/TimezoneData.swift @@ -85,7 +85,7 @@ public class TimezoneData: NSObject, NSCoding { public var isSystemTimezone = false public var overrideFormat: TimezoneOverride = .globalFormat - public override init() { + override public init() { selectionType = .timezone isFavourite = 0 note = ModelConstants.emptyString @@ -268,7 +268,7 @@ public class TimezoneData: NSObject, NSCoding { return formatInString.contains("ss") } - public override var hash: Int { + override public var hash: Int { guard let placeIdentifier = placeID, let timezone = timezoneID else { return -1 } @@ -276,7 +276,7 @@ public class TimezoneData: NSObject, NSCoding { return placeIdentifier.hashValue ^ timezone.hashValue } - public override func isEqual(_ object: Any?) -> Bool { + override public func isEqual(_ object: Any?) -> Bool { guard let compared = object as? TimezoneData else { return false } diff --git a/Clocker/Dependencies/Date Additions/TimePeriodChain.swift b/Clocker/Dependencies/Date Additions/TimePeriodChain.swift index f0c691c..52a8be8 100755 --- a/Clocker/Dependencies/Date Additions/TimePeriodChain.swift +++ b/Clocker/Dependencies/Date Additions/TimePeriodChain.swift @@ -138,15 +138,15 @@ open class TimePeriodChain: TimePeriodGroup { _end = _end?.addingTimeInterval(duration) } - public override func map(_ transform: (TimePeriodProtocol) throws -> T) rethrows -> [T] { + override public func map(_ transform: (TimePeriodProtocol) throws -> T) rethrows -> [T] { return try periods.map(transform) } - public override func filter(_ isIncluded: (TimePeriodProtocol) throws -> Bool) rethrows -> [TimePeriodProtocol] { + override public func filter(_ isIncluded: (TimePeriodProtocol) throws -> Bool) rethrows -> [TimePeriodProtocol] { return try periods.filter(isIncluded) } - internal override func reduce(_ initialResult: Result, _ nextPartialResult: (Result, TimePeriodProtocol) throws -> Result) rethrows -> Result { + override internal func reduce(_ initialResult: Result, _ nextPartialResult: (Result, TimePeriodProtocol) throws -> Result) rethrows -> Result { return try periods.reduce(initialResult, nextPartialResult) } diff --git a/Clocker/Events and Reminders/CalendarHandler.swift b/Clocker/Events and Reminders/CalendarHandler.swift index 7620eb1..ec789b2 100644 --- a/Clocker/Events and Reminders/CalendarHandler.swift +++ b/Clocker/Events and Reminders/CalendarHandler.swift @@ -391,7 +391,8 @@ extension EventCenter { // Check for Zoom links if actualLink.contains("zoom.us/j/") || actualLink.contains("zoom.us/s/") - || actualLink.contains("zoom.us/w/") { + || actualLink.contains("zoom.us/w/") + { // Create a Zoom App link let workspace = NSWorkspace.shared if workspace.urlForApplication(toOpen: URL(string: "zoommtg://")!) != nil { @@ -417,7 +418,8 @@ extension EventCenter { || actualLink.contains("public.senfcall.de") || actualLink.contains("youcanbook.me/zoom/") || actualLink.contains("workplace.com/groupcall") - || actualLink.contains("bluejeans.com/") { + || actualLink.contains("bluejeans.com/") + { if let meetingLink = result.url { return meetingLink } diff --git a/Clocker/Events and Reminders/RemindersHandler.swift b/Clocker/Events and Reminders/RemindersHandler.swift index 7546c81..9b93518 100644 --- a/Clocker/Events and Reminders/RemindersHandler.swift +++ b/Clocker/Events and Reminders/RemindersHandler.swift @@ -51,7 +51,8 @@ extension EventCenter { timezone: String, alertIndex: Int, reminderDate: Date, - additionalNotes: String?) -> Bool { + additionalNotes: String?) -> Bool + { initializeStoreIfNeccesary() if reminderAccessNotDetermined() || reminderAccessDenied() { diff --git a/Clocker/Menu Bar/StatusContainerView.swift b/Clocker/Menu Bar/StatusContainerView.swift index 536707c..c266f5f 100644 --- a/Clocker/Menu Bar/StatusContainerView.swift +++ b/Clocker/Menu Bar/StatusContainerView.swift @@ -31,10 +31,12 @@ func compactWidth(for timezone: TimezoneData) -> Int { if timeFormat == DateFormat.twelveHour || timeFormat == DateFormat.twelveHourWithSeconds || timeFormat == DateFormat.twelveHourWithZero - || timeFormat == DateFormat.twelveHourWithSeconds { + || timeFormat == DateFormat.twelveHourWithSeconds + { totalWidth += 20 } else if timeFormat == DateFormat.twentyFourHour - || timeFormat == DateFormat.twentyFourHourWithSeconds { + || timeFormat == DateFormat.twentyFourHourWithSeconds + { totalWidth += 0 } diff --git a/Clocker/Menu Bar/StatusItemHandler.swift b/Clocker/Menu Bar/StatusItemHandler.swift index fb719d4..669a664 100644 --- a/Clocker/Menu Bar/StatusItemHandler.swift +++ b/Clocker/Menu Bar/StatusItemHandler.swift @@ -112,7 +112,8 @@ class StatusItemHandler: NSObject { userNotificationsDidChangeNotif = center.addObserver(forName: UserDefaults.didChangeNotification, object: self, - queue: mainQueue) { _ in + queue: mainQueue) + { _ in self.setupStatusItem() } } @@ -185,7 +186,7 @@ class StatusItemHandler: NSObject { if let strongSelf = self { strongSelf.performTimerWork() } - }) + }) // Tolerance, even a small amount, has a positive imapct on the power usage. As a rule, we set it to 10% of the interval menubarTimer?.tolerance = shouldDisplaySeconds ? 0.5 : 20 diff --git a/Clocker/Onboarding/FinalOnboardingViewController.swift b/Clocker/Onboarding/FinalOnboardingViewController.swift index 6ef7c1a..db81236 100644 --- a/Clocker/Onboarding/FinalOnboardingViewController.swift +++ b/Clocker/Onboarding/FinalOnboardingViewController.swift @@ -53,7 +53,7 @@ class FinalOnboardingViewController: NSViewController { @IBAction func localizationAction(_: Any) { guard let localizationURL = URL(string: AboutUsConstants.TwitterFollowIntentLink), - let languageCode = Locale.preferredLanguages.first else { return } + let languageCode = Locale.preferredLanguages.first else { return } NSWorkspace.shared.open(localizationURL) diff --git a/Clocker/Onboarding/OnboardingSearchController.swift b/Clocker/Onboarding/OnboardingSearchController.swift index 6ea7a72..2c2607a 100644 --- a/Clocker/Onboarding/OnboardingSearchController.swift +++ b/Clocker/Onboarding/OnboardingSearchController.swift @@ -27,8 +27,8 @@ class OnboardingSearchController: NSViewController { private var geocodingKey: String = { guard let path = Bundle.main.path(forResource: "Keys", ofType: "plist"), - let dictionary = NSDictionary(contentsOfFile: path), - let apiKey = dictionary["GeocodingKey"] as? String + let dictionary = NSDictionary(contentsOfFile: path), + let apiKey = dictionary["GeocodingKey"] as? String else { assertionFailure("Unable to find the API key") return "" @@ -135,7 +135,8 @@ class OnboardingSearchController: NSViewController { private func setupLabelHidingTimer() { Timer.scheduledTimer(withTimeInterval: 5, - repeats: false) { _ in + repeats: false) + { _ in OperationQueue.main.addOperation { self.setInfoLabel(CLEmptyString) } @@ -375,7 +376,7 @@ class OnboardingSearchController: NSViewController { self.findLocalSearchResultsForTimezones() self.prepareUIForPresentingResults() } - }) + }) } private func presentErrorMessage(_ errorMessage: String) { diff --git a/Clocker/Overall App/DataStore.swift b/Clocker/Overall App/DataStore.swift index 7faa663..d9f1f5f 100644 --- a/Clocker/Overall App/DataStore.swift +++ b/Clocker/Overall App/DataStore.swift @@ -50,14 +50,14 @@ class DataStore: NSObject { if let cloudPreferences = ubiquitousStore.object(forKey: CLDefaultPreferenceKey) as? [Data] { return cloudPreferences } - + guard let preferences = userDefaults.object(forKey: CLDefaultPreferenceKey) as? [Data] else { return [] } return preferences } - + func setTimezones(_ timezones: [Data]?) { userDefaults.set(timezones, forKey: CLDefaultPreferenceKey) // iCloud sync @@ -164,9 +164,9 @@ class DataStore: NSObject { return value == 0 } } - - //MARK: Private - + + // MARK: Private + private func shouldDisplayHelper(_ key: String) -> Bool { guard let value = retrieve(key: key) as? NSNumber else { return false diff --git a/Clocker/Overall App/NetworkManager.swift b/Clocker/Overall App/NetworkManager.swift index 08974f0..fcfe866 100644 --- a/Clocker/Overall App/NetworkManager.swift +++ b/Clocker/Overall App/NetworkManager.swift @@ -41,7 +41,7 @@ extension NetworkManager { let session = URLSession(configuration: configuration) guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), - let url = URL(string: encodedPath) + let url = URL(string: encodedPath) else { completionHandler(nil, unableToGenerateURL) return nil diff --git a/Clocker/Overall App/Themer.swift b/Clocker/Overall App/Themer.swift index a985c9f..7d53e3b 100644 --- a/Clocker/Overall App/Themer.swift +++ b/Clocker/Overall App/Themer.swift @@ -15,6 +15,7 @@ class Themer: NSObject { case solarizedLight case solarizedDark } + private static var sharedInstance = Themer(index: UserDefaults.standard.integer(forKey: CLThemeKey)) private var effectiveApperanceObserver: NSKeyValueObservation? private var themeIndex: Theme { @@ -47,9 +48,9 @@ class Themer: NSObject { selector: #selector(respondToInterfaceStyle), name: .interfaceStyleDidChange, object: nil) - + if #available(macOS 10.14, *) { - effectiveApperanceObserver = NSApp.observe(\.effectiveAppearance) { [weak self] (app, _) in + effectiveApperanceObserver = NSApp.observe(\.effectiveAppearance) { [weak self] _, _ in if let sSelf = self { sSelf.setAppAppearance() NotificationCenter.default.post(name: .themeDidChangeNotification, object: nil) @@ -92,12 +93,13 @@ extension Themer { self.setAppAppearance() } } - - //MARK: Color + + // MARK: Color + func sliderKnobColor() -> NSColor { switch themeIndex { case .light: - return NSColor(deviceRed: 255.0, green: 255.0, blue: 255, alpha: 0.9) + return NSColor(deviceRed: 255.0, green: 255.0, blue: 255, alpha: 0.9) case .system: return retrieveCurrentSystem() == .light ? NSColor(deviceRed: 255.0, green: 255.0, blue: 255, alpha: 0.9) : NSColor(deviceRed: 0.0, green: 0.0, blue: 0, alpha: 0.9) default: @@ -108,7 +110,7 @@ extension Themer { func sliderRightColor() -> NSColor { switch themeIndex { case .dark: - return NSColor.white + return NSColor.white default: return NSColor.gray } @@ -132,7 +134,7 @@ extension Themer { return themeIndex == .light ? NSColor.white : NSColor(deviceRed: 55.0 / 255.0, green: 71.0 / 255.0, blue: 79.0 / 255.0, alpha: 1.0) } - + func textBackgroundColor() -> NSColor { if #available(macOS 10.14, *) { switch themeIndex { @@ -172,8 +174,9 @@ extension Themer { return themeIndex == .light ? NSColor.black : NSColor.white } - - //MARK: Images + + // MARK: Images + func shutdownImage() -> NSImage { if let symbolImageForShutdown = symbolImage(for: "ellipsis.circle") { return symbolImageForShutdown @@ -190,7 +193,7 @@ extension Themer { if let symbolImageForPreference = symbolImage(for: "plus") { return symbolImageForPreference } - + return fallbackImageProvider(NSImage(named: NSImage.Name("Settings"))!, NSImage(named: NSImage.Name("Settings-White"))!, NSImage(named: NSImage.actionTemplateName)!, @@ -202,7 +205,7 @@ extension Themer { if let pinImage = symbolImage(for: "macwindow.on.rectangle") { return pinImage } - + return fallbackImageProvider(NSImage(named: NSImage.Name("Float"))!, NSImage(named: NSImage.Name("Float-White"))!, NSImage(named: NSImage.Name("Pin"))!, @@ -225,7 +228,7 @@ extension Themer { if let symbolImage = symbolImage(for: "sunset.fill") { return symbolImage } - + return fallbackImageProvider(NSImage(named: NSImage.Name("Sunset"))!, NSImage(named: NSImage.Name("WhiteSunset"))!, NSImage(named: NSImage.Name("Sunset Dynamic"))!, @@ -237,7 +240,7 @@ extension Themer { if let symbolImage = symbolImage(for: "xmark") { return symbolImage } - + return fallbackImageProvider(NSImage(named: NSImage.Name("Remove"))!, NSImage(named: NSImage.Name("WhiteRemove"))!, NSImage(named: NSImage.Name("Remove Dynamic"))!, @@ -317,7 +320,7 @@ extension Themer { if let symbolImageForPreference = symbolImage(for: "plus") { return symbolImageForPreference } - + return fallbackImageProvider(NSImage(named: NSImage.Name("Add Icon"))!, NSImage(named: NSImage.Name("Add White"))!, NSImage(named: .addDynamicIcon)!, @@ -402,21 +405,21 @@ extension Themer { return removeImage() } - - //MARK: Debug Description - + + // MARK: Debug Description + override var debugDescription: String { if themeIndex == .system { return "System Theme is \(retrieveCurrentSystem())" } return "Current Theme is \(themeIndex)" } - + override var description: String { return debugDescription } - - //MARK: Private + + // MARK: Private private func symbolImage(for name: String) -> NSImage? { assert(name.isEmpty == false) @@ -428,7 +431,7 @@ extension Themer { return nil } - + private func retrieveCurrentSystem() -> Theme { if #available(OSX 10.14, *) { if let appleInterfaceStyle = UserDefaults.standard.object(forKey: "AppleInterfaceStyle") as? String { @@ -439,7 +442,7 @@ extension Themer { } return .light } - + private func setAppAppearance() { if #available(OSX 10.14, *) { var appAppearance = NSAppearance(named: .aqua) @@ -452,12 +455,13 @@ extension Themer { NSApp.appearance = appAppearance } } - + private func fallbackImageProvider(_ lightImage: NSImage, _ darkImage: NSImage, _ systemImage: NSImage, _ solarizedLightImage: NSImage, - _ solarizedDarkImage: NSImage) -> NSImage { + _ solarizedDarkImage: NSImage) -> NSImage + { if #available(macOS 10.14, *) { switch themeIndex { case .light: @@ -474,7 +478,5 @@ extension Themer { } return themeIndex == .light ? lightImage : darkImage - } - } diff --git a/Clocker/Overall App/Timer.swift b/Clocker/Overall App/Timer.swift index 0cbed8a..3201cac 100644 --- a/Clocker/Overall App/Timer.swift +++ b/Clocker/Overall App/Timer.swift @@ -118,7 +118,7 @@ open class Repeater: Equatable { } /// Handler typealias - public typealias Observer = ((Repeater) -> Void) + public typealias Observer = (Repeater) -> Void /// Token assigned to the observer public typealias ObserverToken = UInt64 diff --git a/Clocker/Overall App/VersionUpdateHandler.swift b/Clocker/Overall App/VersionUpdateHandler.swift index 88a4600..4d562f0 100644 --- a/Clocker/Overall App/VersionUpdateHandler.swift +++ b/Clocker/Overall App/VersionUpdateHandler.swift @@ -172,7 +172,7 @@ class VersionUpdateHandler: NSObject { lastVersionCopy = "0" } var newVersionFound = false - var details: String = "" + var details = "" let versions = dict.keys.sorted() diff --git a/Clocker/Panel/Data Layer/TimezoneDataOperations.swift b/Clocker/Panel/Data Layer/TimezoneDataOperations.swift index f3d6c5f..9be80f8 100644 --- a/Clocker/Panel/Data Layer/TimezoneDataOperations.swift +++ b/Clocker/Panel/Data Layer/TimezoneDataOperations.swift @@ -368,7 +368,7 @@ extension TimezoneDataOperations { to: Date()) guard let lat = dataObject.latitude, - let long = dataObject.longitude + let long = dataObject.longitude else { assertionFailure("Data was unexpectedly nil.") return diff --git a/Clocker/Panel/Notes Popover/NotesPopover.swift b/Clocker/Panel/Notes Popover/NotesPopover.swift index d26e44e..f140883 100644 --- a/Clocker/Panel/Notes Popover/NotesPopover.swift +++ b/Clocker/Panel/Notes Popover/NotesPopover.swift @@ -224,7 +224,7 @@ class NotesPopover: NSViewController { } completionHandler(completedDate) - }) + }) } catch { assertionFailure("Failed to successfully initialize DataDetector") completionHandler(nil) @@ -322,7 +322,8 @@ class NotesPopover: NSViewController { } private func updateTimezoneInDefaultPreferences(with override: Int, - _: OverrideType) { + _: OverrideType) + { let timezones = DataStore.shared().timezones() var timezoneObjects: [TimezoneData] = [] @@ -391,7 +392,8 @@ class NotesPopover: NSViewController { timezone: model.timezone(), alertIndex: alertIndex, reminderDate: reminderPicker.dateValue, - additionalNotes: model.note) { + additionalNotes: model.note) + { showSuccessMessage() } } diff --git a/Clocker/Panel/PanelController.swift b/Clocker/Panel/PanelController.swift index af798f7..310ee03 100644 --- a/Clocker/Panel/PanelController.swift +++ b/Clocker/Panel/PanelController.swift @@ -154,7 +154,8 @@ class PanelController: ParentPanelController { } if let statusWindow = statusBackgroundWindow, - let statusButton = statusView { + let statusButton = statusView + { var statusItemFrame = statusWindow.convertToScreen(statusButton.frame) var statusItemScreen = NSScreen.main var testPoint = statusItemFrame.origin @@ -186,16 +187,16 @@ class PanelController: ParentPanelController { let preferences = DataStore.shared().timezones() guard let theme = DataStore.shared().retrieve(key: CLThemeKey) as? NSNumber, - let displayFutureSliderKey = DataStore.shared().retrieve(key: CLThemeKey) as? NSNumber, - let showAppInForeground = DataStore.shared().retrieve(key: CLShowAppInForeground) as? NSNumber, - let relativeDateKey = DataStore.shared().retrieve(key: CLRelativeDateKey) as? NSNumber, - let fontSize = DataStore.shared().retrieve(key: CLUserFontSizePreference) as? NSNumber, - let sunriseTime = DataStore.shared().retrieve(key: CLSunriseSunsetTime) as? NSNumber, - let showDayInMenu = DataStore.shared().retrieve(key: CLShowDayInMenu) as? NSNumber, - let showDateInMenu = DataStore.shared().retrieve(key: CLShowDateInMenu) as? NSNumber, - let showPlaceInMenu = DataStore.shared().retrieve(key: CLShowPlaceInMenu) as? NSNumber, - let showUpcomingEventView = DataStore.shared().retrieve(key: CLShowUpcomingEventView) as? String, - let country = Locale.autoupdatingCurrent.regionCode + let displayFutureSliderKey = DataStore.shared().retrieve(key: CLThemeKey) as? NSNumber, + let showAppInForeground = DataStore.shared().retrieve(key: CLShowAppInForeground) as? NSNumber, + let relativeDateKey = DataStore.shared().retrieve(key: CLRelativeDateKey) as? NSNumber, + let fontSize = DataStore.shared().retrieve(key: CLUserFontSizePreference) as? NSNumber, + let sunriseTime = DataStore.shared().retrieve(key: CLSunriseSunsetTime) as? NSNumber, + let showDayInMenu = DataStore.shared().retrieve(key: CLShowDayInMenu) as? NSNumber, + let showDateInMenu = DataStore.shared().retrieve(key: CLShowDateInMenu) as? NSNumber, + let showPlaceInMenu = DataStore.shared().retrieve(key: CLShowPlaceInMenu) as? NSNumber, + let showUpcomingEventView = DataStore.shared().retrieve(key: CLShowUpcomingEventView) as? String, + let country = Locale.autoupdatingCurrent.regionCode else { return } diff --git a/Clocker/Panel/ParentPanelController+ModernSlider.swift b/Clocker/Panel/ParentPanelController+ModernSlider.swift index 7d2d75e..d3f799c 100644 --- a/Clocker/Panel/ParentPanelController+ModernSlider.swift +++ b/Clocker/Panel/ParentPanelController+ModernSlider.swift @@ -127,7 +127,7 @@ extension ParentPanelController { } public func setDefaultDateLabel(_ index: Int) -> Int { - let futureSliderDayPreference = DataStore.shared().retrieve(key: CLFutureSliderRange) as? NSNumber ?? 5 + let futureSliderDayPreference = DataStore.shared().retrieve(key: CLFutureSliderRange) as? NSNumber ?? 5 let futureSliderDayRange = (futureSliderDayPreference.intValue + 1) let totalCount = (PanelConstants.modernSliderPointsInADay * futureSliderDayRange * 2) + 1 let centerPoint = Int(ceil(Double(totalCount / 2))) diff --git a/Clocker/Panel/ParentPanelController.swift b/Clocker/Panel/ParentPanelController.swift index 2583d4c..aa24974 100644 --- a/Clocker/Panel/ParentPanelController.swift +++ b/Clocker/Panel/ParentPanelController.swift @@ -188,7 +188,8 @@ class ParentPanelController: NSWindowController { object: nil) NotificationCenter.default.addObserver(forName: NSUbiquitousKeyValueStore.didChangeExternallyNotification, object: self, - queue: OperationQueue.main) { [weak self] _ in + queue: OperationQueue.main) + { [weak self] _ in if let sSelf = self { sSelf.mainTableView.reloadData() sSelf.setScrollViewConstraint() @@ -250,7 +251,7 @@ class ParentPanelController: NSWindowController { coordinates: nil) } } - + private func updateHomeObject(with customLabel: String, coordinates: CLLocationCoordinate2D?) { let timezones = DataStore.shared().timezones() @@ -415,8 +416,9 @@ class ParentPanelController: NSWindowController { if let note = object?.note, note.isEmpty == false { newHeight += 20 } else if DataStore.shared().shouldDisplay(.dstTransitionInfo), - let obj = object, - TimezoneDataOperations(with: obj).nextDaylightSavingsTransitionIfAvailable(with: futureSliderValue) != nil { + let obj = object, + TimezoneDataOperations(with: obj).nextDaylightSavingsTransitionIfAvailable(with: futureSliderValue) != nil + { newHeight += 20 } } @@ -603,8 +605,9 @@ class ParentPanelController: NSWindowController { let current = preferences[$0] if $0 < mainTableView.numberOfRows, - let cellView = mainTableView.view(atColumn: 0, row: $0, makeIfNecessary: false) as? TimezoneCellView, - let model = TimezoneData.customObject(from: current) { + let cellView = mainTableView.view(atColumn: 0, row: $0, makeIfNecessary: false) as? TimezoneCellView, + let model = TimezoneData.customObject(from: current) + { if let futureSliderCell = futureSlider.cell as? CustomSliderCell, futureSliderCell.tracking == true { return } @@ -624,7 +627,8 @@ class ParentPanelController: NSWindowController { if let note = model.note, !note.isEmpty { cellView.noteLabel.stringValue = note } else if DataStore.shared().shouldDisplay(.dstTransitionInfo), - let value = TimezoneDataOperations(with: model).nextDaylightSavingsTransitionIfAvailable(with: futureSliderValue) { + let value = TimezoneDataOperations(with: model).nextDaylightSavingsTransitionIfAvailable(with: futureSliderValue) + { cellView.noteLabel.stringValue = value } else { cellView.noteLabel.stringValue = CLEmptyString @@ -724,7 +728,8 @@ class ParentPanelController: NSWindowController { @IBAction func calendarButtonAction(_ sender: NSButton) { if sender.title == NSLocalizedString("Click here to start.", - comment: "Button Title for no Calendar access") { + comment: "Button Title for no Calendar access") + { showPermissionsWindow() } else { retrieveCalendarEvents() @@ -815,7 +820,8 @@ class ParentPanelController: NSWindowController { if let events = eventCenter.eventsForDate[NSCalendar.autoupdatingCurrent.startOfDay(for: now)], events.isEmpty == false { OperationQueue.main.addOperation { if self.upcomingEventCollectionView != nil, - let upcomingEvents = eventCenter.upcomingEventsForDay(events) { + let upcomingEvents = eventCenter.upcomingEventsForDay(events) + { self.upcomingEventsDataSource.updateEventsDataSource(upcomingEvents) self.upcomingEventCollectionView.reloadData() return @@ -982,7 +988,7 @@ class ParentPanelController: NSWindowController { @objc func openCrowdin() { guard let localizationURL = URL(string: AboutUsConstants.CrowdInLocalizationLink), - let languageCode = Locale.preferredLanguages.first else { return } + let languageCode = Locale.preferredLanguages.first else { return } NSWorkspace.shared.open(localizationURL) @@ -996,7 +1002,7 @@ class ParentPanelController: NSWindowController { NSWorkspace.shared.open(sourceURL) } - + @objc func openFAQs() { guard let sourceURL = URL(string: AboutUsConstants.FAQsLink) else { return } @@ -1077,19 +1083,19 @@ extension ParentPanelController: NSSharingServicePickerDelegate { /// London - 01:17:01 private func retrieveAllTimes() -> String { var clipboardCopy = String() - + // Get all timezones let timezones = DataStore.shared().timezones() - + if timezones.isEmpty { return clipboardCopy } - + // Sort them in ascending order let sortedByTime = timezones.sorted { obj1, obj2 -> Bool in let system = NSTimeZone.system guard let object1 = TimezoneData.customObject(from: obj1), - let object2 = TimezoneData.customObject(from: obj2) + let object2 = TimezoneData.customObject(from: obj2) else { assertionFailure("Data was unexpectedly nil") return false @@ -1103,19 +1109,20 @@ extension ParentPanelController: NSSharingServicePickerDelegate { return difference1 > difference2 } - + // Grab date in first place and store it as local variable guard let earliestTimezone = TimezoneData.customObject(from: sortedByTime.first) else { return clipboardCopy } - + let timezoneOperations = TimezoneDataOperations(with: earliestTimezone) var sectionTitle = timezoneOperations.todaysDate(with: 0) // TODO: Take slider value into consideration clipboardCopy.append("\(sectionTitle)\n") - + stride(from: 0, to: sortedByTime.count, by: 1).forEach { if $0 < sortedByTime.count, - let dataModel = TimezoneData.customObject(from: sortedByTime[$0]) { + let dataModel = TimezoneData.customObject(from: sortedByTime[$0]) + { let dataOperations = TimezoneDataOperations(with: dataModel) let date = dataOperations.todaysDate(with: 0) let time = dataOperations.time(with: 0) diff --git a/Clocker/Panel/Rate Controller/ReviewController.swift b/Clocker/Panel/Rate Controller/ReviewController.swift index b72d20d..fdfa2d4 100644 --- a/Clocker/Panel/Rate Controller/ReviewController.swift +++ b/Clocker/Panel/Rate Controller/ReviewController.swift @@ -42,12 +42,12 @@ final class ReviewController { // Check if the app has been installed for atleast 7 days guard let install = storage.object(forKey: Keys.install) as? Date, - install.timeIntervalSinceNow < minInstall + install.timeIntervalSinceNow < minInstall 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 + let lastVersion = storage.object(forKey: Keys.lastVersion) as? String else { return true } // Minimum interval between two versions should be 3 months diff --git a/Clocker/Panel/UI/TimezoneCellView.swift b/Clocker/Panel/UI/TimezoneCellView.swift index b5977a7..7e042ea 100644 --- a/Clocker/Panel/UI/TimezoneCellView.swift +++ b/Clocker/Panel/UI/TimezoneCellView.swift @@ -39,7 +39,7 @@ class TimezoneCellView: NSTableCellView { func setupLayout() { guard let relativeFont = relativeDate.font, - let sunriseFont = sunriseSetTime.font + let sunriseFont = sunriseSetTime.font else { assertionFailure("Unable to convert to NSString") return @@ -128,7 +128,7 @@ class TimezoneCellView: NSTableCellView { } guard let customFont = customName.font, - let timeFont = time.font + let timeFont = time.font else { assertionFailure("User Font Size is in unexpectedly nil") return @@ -165,7 +165,7 @@ class TimezoneCellView: NSTableCellView { } guard let panelTableView = searchView as? PanelTableView, - let enclosingScroller = panelTableView.enclosingScrollView + let enclosingScroller = panelTableView.enclosingScrollView else { // We might be coming from the preview tableview! return diff --git a/Clocker/Panel/UI/TimezoneDataSource.swift b/Clocker/Panel/UI/TimezoneDataSource.swift index 76de67c..6e0aebb 100644 --- a/Clocker/Panel/UI/TimezoneDataSource.swift +++ b/Clocker/Panel/UI/TimezoneDataSource.swift @@ -144,7 +144,7 @@ extension TimezoneDataSource: NSTableViewDataSource, NSTableViewDelegate { panelController.deleteTimezone(at: row) } - }) + }) if #available(OSX 11.0, *) { swipeToDelete.image = Themer.shared().filledTrashImage() diff --git a/Clocker/Panel/Upcoming Events/UpcomingEventViewItem.swift b/Clocker/Panel/Upcoming Events/UpcomingEventViewItem.swift index effe786..19810f6 100644 --- a/Clocker/Panel/Upcoming Events/UpcomingEventViewItem.swift +++ b/Clocker/Panel/Upcoming Events/UpcomingEventViewItem.swift @@ -40,7 +40,8 @@ class UpcomingEventViewItem: NSCollectionViewItem { _ color: NSColor, _ link: URL?, _ delegate: UpcomingEventPanelDelegate?, - _ isCancelled: Bool) { + _ isCancelled: Bool) + { if leadingConstraint.constant != UpcomingEventViewItem.EventLeadingConstraint / 2 { leadingConstraint.animator().constant = UpcomingEventViewItem.EventLeadingConstraint / 2 } diff --git a/Clocker/Preferences/About/AboutViewController.swift b/Clocker/Preferences/About/AboutViewController.swift index 81be4ed..1d6f696 100644 --- a/Clocker/Preferences/About/AboutViewController.swift +++ b/Clocker/Preferences/About/AboutViewController.swift @@ -99,7 +99,7 @@ class AboutViewController: ParentViewController { @IBAction func openMyTwitter(_: Any) { guard let twitterURL = URL(string: AboutUsConstants.TwitterLink), - let countryCode = Locale.autoupdatingCurrent.regionCode else { return } + let countryCode = Locale.autoupdatingCurrent.regionCode else { return } NSWorkspace.shared.open(twitterURL) @@ -110,7 +110,7 @@ class AboutViewController: ParentViewController { @IBAction func viewSource(_: Any) { guard let sourceURL = URL(string: AboutUsConstants.AppStoreLink), - let countryCode = Locale.autoupdatingCurrent.regionCode else { return } + let countryCode = Locale.autoupdatingCurrent.regionCode else { return } NSWorkspace.shared.open(sourceURL) @@ -132,7 +132,7 @@ class AboutViewController: ParentViewController { @IBAction func openGitHub(_: Any) { guard let localizationURL = URL(string: AboutUsConstants.CrowdInLocalizationLink), - let languageCode = Locale.preferredLanguages.first else { return } + let languageCode = Locale.preferredLanguages.first else { return } NSWorkspace.shared.open(localizationURL) diff --git a/Clocker/Preferences/App Feedback/AppFeedbackWindowController.swift b/Clocker/Preferences/App Feedback/AppFeedbackWindowController.swift index ea12d94..0cce1b5 100644 --- a/Clocker/Preferences/App Feedback/AppFeedbackWindowController.swift +++ b/Clocker/Preferences/App Feedback/AppFeedbackWindowController.swift @@ -80,7 +80,8 @@ class AppFeedbackWindowController: NSWindowController { themeDidChangeNotification = NotificationCenter.default.addObserver(forName: .themeDidChangeNotification, object: nil, - queue: OperationQueue.main) { _ in + queue: OperationQueue.main) + { _ in self.window?.backgroundColor = Themer.shared().mainBackgroundColor() self.setup() } @@ -139,9 +140,9 @@ class AppFeedbackWindowController: NSWindowController { let preferences = DataStore.shared().timezones() guard let theme = DataStore.shared().retrieve(key: CLThemeKey) as? NSNumber, - let displayFutureSliderKey = DataStore.shared().retrieve(key: CLThemeKey) as? NSNumber, - let relativeDateKey = DataStore.shared().retrieve(key: CLRelativeDateKey) as? NSNumber, - let country = Locale.autoupdatingCurrent.regionCode + let displayFutureSliderKey = DataStore.shared().retrieve(key: CLThemeKey) as? NSNumber, + let relativeDateKey = DataStore.shared().retrieve(key: CLRelativeDateKey) as? NSNumber, + let country = Locale.autoupdatingCurrent.regionCode else { return "Error" } @@ -182,7 +183,7 @@ class AppFeedbackWindowController: NSWindowController { private func retrieveDataForSending() -> [String: String] { guard let shortVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String, - let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String + let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String else { return [:] } @@ -285,7 +286,7 @@ class AppFeedbackWindowController: NSWindowController { @IBAction func navigateToSupportTwitter(_: Any) { guard let twitterURL = URL(string: AboutUsConstants.TwitterLink), - let countryCode = Locale.autoupdatingCurrent.regionCode else { return } + let countryCode = Locale.autoupdatingCurrent.regionCode else { return } NSWorkspace.shared.open(twitterURL) @@ -311,7 +312,7 @@ extension AppFeedbackWindowController: NSWindowDelegate { func bringPreferencesWindowToFront() { let windows = NSApplication.shared.windows let prefWindow = windows.first(where: { window in - return window.identifier == NSUserInterfaceItemIdentifier("Preferences") + window.identifier == NSUserInterfaceItemIdentifier("Preferences") }) if let prefW = prefWindow { prefW.makeKeyAndOrderFront(self) diff --git a/Clocker/Preferences/Appearance/AppearanceViewController.swift b/Clocker/Preferences/Appearance/AppearanceViewController.swift index 8294fe1..79558af 100644 --- a/Clocker/Preferences/Appearance/AppearanceViewController.swift +++ b/Clocker/Preferences/Appearance/AppearanceViewController.swift @@ -188,7 +188,8 @@ class AppearanceViewController: ParentViewController { refresh(panel: true, floating: true) if let selectedFormat = sender.selectedItem?.title, - selectedFormat.contains("ss") { + selectedFormat.contains("ss") + { Logger.info("Selected format contains timezone format") guard let panelController = PanelController.panel() else { return } panelController.pauseTimer() diff --git a/Clocker/Preferences/Calendar/CalendarViewController.swift b/Clocker/Preferences/Calendar/CalendarViewController.swift index d817478..fd17568 100644 --- a/Clocker/Preferences/Calendar/CalendarViewController.swift +++ b/Clocker/Preferences/Calendar/CalendarViewController.swift @@ -243,13 +243,15 @@ extension CalendarViewController: NSTableViewDelegate { 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 { + let message = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "sourceCellView"), owner: self) as? SourceTableViewCell + { message.sourceName.stringValue = currentSource return message } if let currentSource = calendars[row] as? CalendarInfo, - let calendarCell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "calendarCellView"), owner: self) as? CalendarTableViewCell { + let calendarCell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "calendarCellView"), owner: self) as? CalendarTableViewCell + { calendarCell.calendarName.stringValue = currentSource.calendar.title calendarCell.calendarSelected.state = currentSource.selected ? NSControl.StateValue.on : NSControl.StateValue.off calendarCell.calendarSelected.target = self diff --git a/Clocker/Preferences/General/PreferencesDataSource.swift b/Clocker/Preferences/General/PreferencesDataSource.swift index 27527ba..63d464d 100644 --- a/Clocker/Preferences/General/PreferencesDataSource.swift +++ b/Clocker/Preferences/General/PreferencesDataSource.swift @@ -104,7 +104,8 @@ extension PreferencesDataSource: NSTableViewDataSource { var selectedDataSource: TimezoneData? if selectedTimezones.count > row, - let model = TimezoneData.customObject(from: selectedTimezones[row]) { + let model = TimezoneData.customObject(from: selectedTimezones[row]) + { selectedDataSource = model } @@ -163,7 +164,7 @@ extension PreferencesDataSource: NSTableViewDataSource { "Old Label": dataObject.customLabel ?? "Error", "New Label": formattedValue, ], - for: "Custom Label Changed") + for: "Custom Label Changed") dataObject.setLabel(formattedValue) @@ -176,7 +177,7 @@ extension PreferencesDataSource: NSTableViewDataSource { "Selected Timezone Count": selectedTimezones.count, "Current Row": row, ], - for: "Error in selected row count") + for: "Error in selected row count") } } diff --git a/Clocker/Preferences/General/PreferencesViewController.swift b/Clocker/Preferences/General/PreferencesViewController.swift index e2a30a0..df14bfe 100644 --- a/Clocker/Preferences/General/PreferencesViewController.swift +++ b/Clocker/Preferences/General/PreferencesViewController.swift @@ -19,7 +19,6 @@ struct PreferencesConstants { } class PreferencesViewController: ParentViewController { - @IBOutlet private var placeholderLabel: NSTextField! @IBOutlet private var timezoneTableView: NSTableView! @IBOutlet private var availableTimezoneTableView: NSTableView! @@ -43,14 +42,14 @@ class PreferencesViewController: ParentViewController { @IBOutlet var startAtLoginLabel: NSTextField! @IBOutlet var startupCheckbox: NSButton! - + // Sorting private var arePlacesSortedInAscendingOrder = false private var arePlacesSortedInAscendingTimezoneOrder = false private var isTimezoneSortOptionSelected = false private var isTimezoneNameSortOptionSelected = false private var isLabelOptionSelected = false - + private var isActivityInProgress = false { didSet { OperationQueue.main.addOperation { @@ -73,14 +72,12 @@ class PreferencesViewController: ParentViewController { private lazy var startupManager = StartupManager() private var dataTask: URLSessionDataTask? = .none - private lazy var notimezoneView: NoTimezoneView? = { - NoTimezoneView(frame: tableview.frame) - }() + private lazy var notimezoneView: NoTimezoneView? = NoTimezoneView(frame: tableview.frame) private var geocodingKey: String = { guard let path = Bundle.main.path(forResource: "Keys", ofType: "plist"), - let dictionary = NSDictionary(contentsOfFile: path), - let apiKey = dictionary["GeocodingKey"] as? String + let dictionary = NSDictionary(contentsOfFile: path), + let apiKey = dictionary["GeocodingKey"] as? String else { assertionFailure("Unable to find the API key") return "" @@ -88,8 +85,6 @@ class PreferencesViewController: ParentViewController { return apiKey }() - - override func viewDidLoad() { super.viewDidLoad() @@ -97,10 +92,11 @@ class PreferencesViewController: ParentViewController { selector: #selector(refreshTimezoneTableView), name: NSNotification.Name.customLabelChanged, object: nil) - + NotificationCenter.default.addObserver(forName: NSUbiquitousKeyValueStore.didChangeExternallyNotification, object: self, - queue: OperationQueue.main) { [weak self] _ in + queue: OperationQueue.main) + { [weak self] _ in if let sSelf = self { sSelf.refreshTimezoneTableView() } @@ -347,9 +343,10 @@ extension PreferencesViewController: NSTableViewDataSource, NSTableViewDelegate for: "favouriteRemoved") if let appDelegate = NSApplication.shared.delegate as? AppDelegate, - let menubarFavourites = DataStore.shared().menubarTimezones(), - menubarFavourites.isEmpty, - DataStore.shared().shouldDisplay(.showMeetingInMenubar) == false { + let menubarFavourites = DataStore.shared().menubarTimezones(), + menubarFavourites.isEmpty, + DataStore.shared().shouldDisplay(.showMeetingInMenubar) == false + { appDelegate.invalidateMenubarTimer(true) } @@ -475,7 +472,7 @@ extension PreferencesViewController { self.prepareUIForPresentingResults() } - }) + }) } } @@ -893,7 +890,7 @@ extension PreferencesViewController { let system = NSTimeZone.system guard let object1 = TimezoneData.customObject(from: obj1), - let object2 = TimezoneData.customObject(from: obj2) + let object2 = TimezoneData.customObject(from: obj2) else { assertionFailure("Data was unexpectedly nil") return false @@ -921,7 +918,7 @@ extension PreferencesViewController { let sortedLabels = selectedTimeZones.sorted { obj1, obj2 -> Bool in guard let object1 = TimezoneData.customObject(from: obj1), - let object2 = TimezoneData.customObject(from: obj2) + let object2 = TimezoneData.customObject(from: obj2) else { assertionFailure("Data was unexpectedly nil") return false @@ -945,7 +942,7 @@ extension PreferencesViewController { let sortedByAddress = selectedTimeZones.sorted { obj1, obj2 -> Bool in guard let object1 = TimezoneData.customObject(from: obj1), - let object2 = TimezoneData.customObject(from: obj2) + let object2 = TimezoneData.customObject(from: obj2) else { assertionFailure("Data was unexpectedly nil") return false @@ -1012,7 +1009,7 @@ extension PreferencesViewController: PreferenceSelectionUpdates { let sortedTimezones = selectedTimeZones.sorted { obj1, obj2 -> Bool in guard let object1 = TimezoneData.customObject(from: obj1), - let object2 = TimezoneData.customObject(from: obj2) + let object2 = TimezoneData.customObject(from: obj2) else { assertionFailure("Data was unexpectedly nil") return false diff --git a/Clocker/Preferences/Menu Bar/StatusContainerView.swift b/Clocker/Preferences/Menu Bar/StatusContainerView.swift index 66808f0..282d598 100644 --- a/Clocker/Preferences/Menu Bar/StatusContainerView.swift +++ b/Clocker/Preferences/Menu Bar/StatusContainerView.swift @@ -33,10 +33,12 @@ func compactWidth(for timezone: TimezoneData) -> Int { if timeFormat == DateFormat.twelveHour || timeFormat == DateFormat.twelveHourWithSeconds || timeFormat == DateFormat.twelveHourWithZero - || timeFormat == DateFormat.twelveHourWithSeconds { + || timeFormat == DateFormat.twelveHourWithSeconds + { totalWidth += 20 } else if timeFormat == DateFormat.twentyFourHour - || timeFormat == DateFormat.twentyFourHourWithSeconds { + || timeFormat == DateFormat.twentyFourHourWithSeconds + { totalWidth += 0 } diff --git a/Clocker/Preferences/Menu Bar/StatusItemHandler.swift b/Clocker/Preferences/Menu Bar/StatusItemHandler.swift index dcdcc70..f5b3a79 100644 --- a/Clocker/Preferences/Menu Bar/StatusItemHandler.swift +++ b/Clocker/Preferences/Menu Bar/StatusItemHandler.swift @@ -115,15 +115,16 @@ class StatusItemHandler: NSObject { userNotificationsDidChangeNotif = center.addObserver(forName: UserDefaults.didChangeNotification, object: self, - queue: mainQueue) { _ in + queue: mainQueue) + { _ in self.setupStatusItem() } - - NSWorkspace.shared.notificationCenter.addObserver(forName: NSWorkspace.willSleepNotification, object: nil, queue: OperationQueue.main) { notification in + + NSWorkspace.shared.notificationCenter.addObserver(forName: NSWorkspace.willSleepNotification, object: nil, queue: OperationQueue.main) { _ in self.menubarTimer?.invalidate() } - - NSWorkspace.shared.notificationCenter.addObserver(forName: NSWorkspace.didWakeNotification, object: nil, queue: OperationQueue.main) { notification in + + NSWorkspace.shared.notificationCenter.addObserver(forName: NSWorkspace.didWakeNotification, object: nil, queue: OperationQueue.main) { _ in self.setupStatusItem() } } @@ -183,7 +184,7 @@ class StatusItemHandler: NSObject { if let strongSelf = self { strongSelf.refresh() } - }) + }) // Tolerance, even a small amount, has a positive imapct on the power usage. As a rule, we set it to 10% of the interval menubarTimer?.tolerance = shouldDisplaySeconds ? 0.5 : 20 diff --git a/Clocker/Preferences/Menu Bar/UpcomingEventStatusItemView.swift b/Clocker/Preferences/Menu Bar/UpcomingEventStatusItemView.swift index ea1b014..6f6818b 100644 --- a/Clocker/Preferences/Menu Bar/UpcomingEventStatusItemView.swift +++ b/Clocker/Preferences/Menu Bar/UpcomingEventStatusItemView.swift @@ -65,6 +65,7 @@ class UpcomingEventStatusItemView: NSView { ]) } + @available(*, unavailable) required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } diff --git a/Clocker/Preferences/OneWindowController.swift b/Clocker/Preferences/OneWindowController.swift index ebc08c5..87a2abe 100644 --- a/Clocker/Preferences/OneWindowController.swift +++ b/Clocker/Preferences/OneWindowController.swift @@ -50,7 +50,7 @@ class OneWindowController: NSWindowController { window?.backgroundColor = Themer.shared().mainBackgroundColor() window?.identifier = NSUserInterfaceItemIdentifier("Preferences") } - + private func setupToolbarImages() { guard let tabViewController = contentViewController as? CenteredTabViewController else { return @@ -78,18 +78,18 @@ class OneWindowController: NSWindowController { } // MARK: Public - + func openPermissionsPane() { openPreferenceTab(at: 3) NSApp.activate(ignoringOtherApps: true) } - + // Action mapped to the + button in the PanelController. We should always open the General Pane when the + button is clicked. func openGeneralPane() { openPreferenceTab(at: 0) NSApp.activate(ignoringOtherApps: true) } - + private func openPreferenceTab(at index: Int) { guard let window = window else { return From 127a1eb8cbcda23486b232a5c6fb7fe43d11bab0 Mon Sep 17 00:00:00 2001 From: Abhishek Date: Sat, 26 Mar 2022 19:34:40 -0400 Subject: [PATCH 02/16] Minor renaming. --- Clocker/Clocker.xcodeproj/project.pbxproj | 8 ++++---- .../ClockerUnitTests/StandardMenubarHandlerTests.swift | 4 ++-- Clocker/Panel/ParentPanelController.swift | 2 +- .../Preferences/General/PreferencesViewController.swift | 2 +- .../{MenubarHandler.swift => MenubarTitleProvider.swift} | 2 +- Clocker/Preferences/Menu Bar/StatusItemHandler.swift | 2 +- 6 files changed, 10 insertions(+), 10 deletions(-) rename Clocker/Preferences/Menu Bar/{MenubarHandler.swift => MenubarTitleProvider.swift} (98%) diff --git a/Clocker/Clocker.xcodeproj/project.pbxproj b/Clocker/Clocker.xcodeproj/project.pbxproj index 9282700..c5f3d17 100755 --- a/Clocker/Clocker.xcodeproj/project.pbxproj +++ b/Clocker/Clocker.xcodeproj/project.pbxproj @@ -7,7 +7,7 @@ objects = { /* Begin PBXBuildFile section */ - 3508CC942599FFEC000E3530 /* MenubarHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3508CC932599FFEC000E3530 /* MenubarHandler.swift */; }; + 3508CC942599FFEC000E3530 /* MenubarTitleProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3508CC932599FFEC000E3530 /* MenubarTitleProvider.swift */; }; 3508CC9A259A0001000E3530 /* StatusItemView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3508CC99259A0001000E3530 /* StatusItemView.swift */; }; 3508CC9F259A000E000E3530 /* StatusItemHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3508CC9E259A000E000E3530 /* StatusItemHandler.swift */; }; 3508CCAA259A0027000E3530 /* StatusContainerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3508CCA9259A0027000E3530 /* StatusContainerView.swift */; }; @@ -255,7 +255,7 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ - 3508CC932599FFEC000E3530 /* MenubarHandler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MenubarHandler.swift; sourceTree = ""; }; + 3508CC932599FFEC000E3530 /* MenubarTitleProvider.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MenubarTitleProvider.swift; sourceTree = ""; }; 3508CC99259A0001000E3530 /* StatusItemView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatusItemView.swift; sourceTree = ""; }; 3508CC9E259A000E000E3530 /* StatusItemHandler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatusItemHandler.swift; sourceTree = ""; }; 3508CCA9259A0027000E3530 /* StatusContainerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatusContainerView.swift; sourceTree = ""; }; @@ -568,7 +568,7 @@ 35C36EDF22595D9C002FA5C6 /* Menu Bar */ = { isa = PBXGroup; children = ( - 3508CC932599FFEC000E3530 /* MenubarHandler.swift */, + 3508CC932599FFEC000E3530 /* MenubarTitleProvider.swift */, 3508CC99259A0001000E3530 /* StatusItemView.swift */, 3508CC9E259A000E000E3530 /* StatusItemHandler.swift */, 3508CCA9259A0027000E3530 /* StatusContainerView.swift */, @@ -1317,7 +1317,7 @@ 35C36F4F2259D981002FA5C6 /* AppDefaults.swift in Sources */, 35C36F5D2259DD96002FA5C6 /* TimezoneDataOperations.swift in Sources */, 3548C45D26BEEF4C00AFB533 /* ParentPanelController+UpcomingEvents.swift in Sources */, - 3508CC942599FFEC000E3530 /* MenubarHandler.swift in Sources */, + 3508CC942599FFEC000E3530 /* MenubarTitleProvider.swift in Sources */, 35C36F14225961DA002FA5C6 /* Integer+DateTools.swift in Sources */, 35C36FA22259ED6D002FA5C6 /* RemindersHandler.swift in Sources */, 35C36F622259DE67002FA5C6 /* NotesPopover.swift in Sources */, diff --git a/Clocker/ClockerUnitTests/StandardMenubarHandlerTests.swift b/Clocker/ClockerUnitTests/StandardMenubarHandlerTests.swift index f93625e..29d5fe7 100644 --- a/Clocker/ClockerUnitTests/StandardMenubarHandlerTests.swift +++ b/Clocker/ClockerUnitTests/StandardMenubarHandlerTests.swift @@ -30,7 +30,7 @@ class StandardMenubarHandlerTests: XCTestCase { // Set standard menubar in Prefs UserDefaults.standard.set(1, forKey: CLMenubarCompactMode) - let menubarHandler = MenubarHandler() + let menubarHandler = MenubarTitleProvider() let menubarString = menubarHandler.titleForMenubar() ?? "" // Test menubar string is present @@ -58,7 +58,7 @@ class StandardMenubarHandlerTests: XCTestCase { func testUnfavouritedTimezone_returnNilMenubarString() { // Wipe all timezones from UserDefaults DataStore.shared().setTimezones(nil) - let menubarHandler = MenubarHandler() + let menubarHandler = MenubarTitleProvider() let emptyMenubarString = menubarHandler.titleForMenubar() // Returns early because DataStore.menubarTimezones is nil XCTAssertNil(emptyMenubarString) diff --git a/Clocker/Panel/ParentPanelController.swift b/Clocker/Panel/ParentPanelController.swift index aa24974..7f0de6c 100644 --- a/Clocker/Panel/ParentPanelController.swift +++ b/Clocker/Panel/ParentPanelController.swift @@ -575,7 +575,7 @@ class ParentPanelController: NSWindowController { Logger.log(object: nil, for: "Deleted Timezone Through Swipe") } - private lazy var menubarTitleHandler = MenubarHandler() + private lazy var menubarTitleHandler = MenubarTitleProvider() @objc func updateTime() { let store = DataStore.shared() diff --git a/Clocker/Preferences/General/PreferencesViewController.swift b/Clocker/Preferences/General/PreferencesViewController.swift index df14bfe..f59decb 100644 --- a/Clocker/Preferences/General/PreferencesViewController.swift +++ b/Clocker/Preferences/General/PreferencesViewController.swift @@ -79,7 +79,7 @@ class PreferencesViewController: ParentViewController { let dictionary = NSDictionary(contentsOfFile: path), let apiKey = dictionary["GeocodingKey"] as? String else { - assertionFailure("Unable to find the API key") +// assertionFailure("Unable to find the API key") return "" } return apiKey diff --git a/Clocker/Preferences/Menu Bar/MenubarHandler.swift b/Clocker/Preferences/Menu Bar/MenubarTitleProvider.swift similarity index 98% rename from Clocker/Preferences/Menu Bar/MenubarHandler.swift rename to Clocker/Preferences/Menu Bar/MenubarTitleProvider.swift index dba732b..69ea823 100644 --- a/Clocker/Preferences/Menu Bar/MenubarHandler.swift +++ b/Clocker/Preferences/Menu Bar/MenubarTitleProvider.swift @@ -5,7 +5,7 @@ import CoreLoggerKit import CoreModelKit import EventKit -class MenubarHandler: NSObject { +class MenubarTitleProvider: NSObject { func titleForMenubar() -> String? { if let nextEvent = checkForUpcomingEvents() { return nextEvent diff --git a/Clocker/Preferences/Menu Bar/StatusItemHandler.swift b/Clocker/Preferences/Menu Bar/StatusItemHandler.swift index f5b3a79..d055680 100644 --- a/Clocker/Preferences/Menu Bar/StatusItemHandler.swift +++ b/Clocker/Preferences/Menu Bar/StatusItemHandler.swift @@ -22,7 +22,7 @@ class StatusItemHandler: NSObject { return statusItem }() - private var menubarTitleHandler = MenubarHandler() + private var menubarTitleHandler = MenubarTitleProvider() private var parentView: StatusContainerView? From 7bf7f49aba39410c6cad0c233e4f61fef2e12e06 Mon Sep 17 00:00:00 2001 From: Abhishek Date: Sat, 26 Mar 2022 19:45:01 -0400 Subject: [PATCH 03/16] Unused. --- .../Data Layer/TimezoneDataOperations.swift | 26 ------------------- 1 file changed, 26 deletions(-) diff --git a/Clocker/Panel/Data Layer/TimezoneDataOperations.swift b/Clocker/Panel/Data Layer/TimezoneDataOperations.swift index 9be80f8..0db1170 100644 --- a/Clocker/Panel/Data Layer/TimezoneDataOperations.swift +++ b/Clocker/Panel/Data Layer/TimezoneDataOperations.swift @@ -77,32 +77,6 @@ extension TimezoneDataOperations { return "Heads up! DST transition will occur in \(numberOfDays) \(suffix)." } - private func checkForUpcomingEvents() -> (String, 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 { - return nil - } - - for event in events { - if event.event.startDate.timeIntervalSinceNow > 0, !event.isAllDay { - let timeForEventToStart = event.event.startDate.timeIntervalSinceNow / 60 - - if timeForEventToStart > 30 { - Logger.info("Our next event: \(event.event.title ?? "Error") starts in \(timeForEventToStart) mins") - - continue - } - - return EventCenter.sharedCenter().separateFormat(event: event.event) - } - } - } - - return nil - } - func compactMenuTitle() -> String { var subtitle = CLEmptyString From b3c1e3c90fbe5367d2bd51eb8465333cb3ae0616 Mon Sep 17 00:00:00 2001 From: Abhishek Date: Sat, 26 Mar 2022 20:50:29 -0400 Subject: [PATCH 04/16] Typo. --- Clocker/Events and Reminders/CalendarHandler.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Clocker/Events and Reminders/CalendarHandler.swift b/Clocker/Events and Reminders/CalendarHandler.swift index ec789b2..817e73d 100644 --- a/Clocker/Events and Reminders/CalendarHandler.swift +++ b/Clocker/Events and Reminders/CalendarHandler.swift @@ -163,7 +163,7 @@ extension EventCenter { if filteredEvents.count == 1 { return filteredEvents.first } - // If there are multipl events coming up, prefer the ones the currentUser has accepted + // If there are multiple events coming up, prefer the ones the currentUser has accepted let acceptedEvents = filteredEvents.filter { $0.attendeStatus == .accepted } From 34aba40bc7e299641d93f81024781e2ea36fc73e Mon Sep 17 00:00:00 2001 From: Abhishek Date: Sat, 26 Mar 2022 21:03:46 -0400 Subject: [PATCH 05/16] Conform UpcomingEventStatusItemView to StatusItemViewConforming. --- .../UpcomingEventStatusItemView.swift | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/Clocker/Preferences/Menu Bar/UpcomingEventStatusItemView.swift b/Clocker/Preferences/Menu Bar/UpcomingEventStatusItemView.swift index 6f6818b..331a96a 100644 --- a/Clocker/Preferences/Menu Bar/UpcomingEventStatusItemView.swift +++ b/Clocker/Preferences/Menu Bar/UpcomingEventStatusItemView.swift @@ -71,9 +71,15 @@ class UpcomingEventStatusItemView: NSView { } private func initialSetup() { - nextEventField.attributedStringValue = NSAttributedString(string: "Next Event", attributes: textFontAttributes) + nextEventField.attributedStringValue = NSAttributedString(string: dataObject.event.title, attributes: textFontAttributes) etaField.attributedStringValue = NSAttributedString(string: dataObject.metadataForMeeting(), attributes: timeAttributes) } + + @available(OSX 10.14, *) + override func viewDidChangeEffectiveAppearance() { + super.viewDidChangeEffectiveAppearance() + statusItemViewSetNeedsDisplay() + } func updateWithNextEventInfo(_ metadata: String) { nextEventField.attributedStringValue = NSAttributedString(string: "Next Event", attributes: textFontAttributes) @@ -89,3 +95,16 @@ class UpcomingEventStatusItemView: NSView { mainDelegate.togglePanel(event) } } + +extension UpcomingEventStatusItemView: StatusItemViewConforming { + + func statusItemViewSetNeedsDisplay() { + nextEventField.attributedStringValue = NSAttributedString(string: dataObject.event.title, attributes: textFontAttributes) + etaField.attributedStringValue = NSAttributedString(string: dataObject.metadataForMeeting(), attributes: timeAttributes) + } + + func statusItemViewIdentifier() -> String { + return "upcoming_event_view" + } + +} From 244cef4fba29e8805b740299668b66de08c6cdb8 Mon Sep 17 00:00:00 2001 From: Abhishek Date: Sat, 26 Mar 2022 21:04:21 -0400 Subject: [PATCH 06/16] Minor. --- .../Preferences/Menu Bar/StatusItemView.swift | 20 +++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/Clocker/Preferences/Menu Bar/StatusItemView.swift b/Clocker/Preferences/Menu Bar/StatusItemView.swift index 2765da3..af55985 100644 --- a/Clocker/Preferences/Menu Bar/StatusItemView.swift +++ b/Clocker/Preferences/Menu Bar/StatusItemView.swift @@ -105,12 +105,7 @@ class StatusItemView: NSView { @available(OSX 10.14, *) override func viewDidChangeEffectiveAppearance() { super.viewDidChangeEffectiveAppearance() - updateTimeInMenubar() - } - - func updateTimeInMenubar() { - locationView.attributedStringValue = NSAttributedString(string: operationsObject.compactMenuTitle(), attributes: textFontAttributes) - timeView.attributedStringValue = NSAttributedString(string: operationsObject.compactMenuSubtitle(), attributes: timeAttributes) + statusItemViewSetNeedsDisplay() } private func initialSetup() { @@ -132,3 +127,16 @@ class StatusItemView: NSView { mainDelegate.togglePanel(event) } } + +extension StatusItemView: StatusItemViewConforming { + + func statusItemViewSetNeedsDisplay() { + locationView.attributedStringValue = NSAttributedString(string: operationsObject.compactMenuTitle(), attributes: textFontAttributes) + timeView.attributedStringValue = NSAttributedString(string: operationsObject.compactMenuSubtitle(), attributes: timeAttributes) + } + + func statusItemViewIdentifier() -> String { + return "location_view" + } + +} From ad09ddac3f7908b1b00a9c6e342f8d88839e77d4 Mon Sep 17 00:00:00 2001 From: Abhishek Date: Sat, 26 Mar 2022 21:05:02 -0400 Subject: [PATCH 07/16] Formatting. --- Clocker/Preferences/Menu Bar/StatusItemView.swift | 4 +--- .../Preferences/Menu Bar/UpcomingEventStatusItemView.swift | 6 ++---- 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/Clocker/Preferences/Menu Bar/StatusItemView.swift b/Clocker/Preferences/Menu Bar/StatusItemView.swift index af55985..a2b871b 100644 --- a/Clocker/Preferences/Menu Bar/StatusItemView.swift +++ b/Clocker/Preferences/Menu Bar/StatusItemView.swift @@ -129,14 +129,12 @@ class StatusItemView: NSView { } extension StatusItemView: StatusItemViewConforming { - func statusItemViewSetNeedsDisplay() { locationView.attributedStringValue = NSAttributedString(string: operationsObject.compactMenuTitle(), attributes: textFontAttributes) timeView.attributedStringValue = NSAttributedString(string: operationsObject.compactMenuSubtitle(), attributes: timeAttributes) } - + func statusItemViewIdentifier() -> String { return "location_view" } - } diff --git a/Clocker/Preferences/Menu Bar/UpcomingEventStatusItemView.swift b/Clocker/Preferences/Menu Bar/UpcomingEventStatusItemView.swift index 331a96a..52196ac 100644 --- a/Clocker/Preferences/Menu Bar/UpcomingEventStatusItemView.swift +++ b/Clocker/Preferences/Menu Bar/UpcomingEventStatusItemView.swift @@ -74,7 +74,7 @@ class UpcomingEventStatusItemView: NSView { nextEventField.attributedStringValue = NSAttributedString(string: dataObject.event.title, attributes: textFontAttributes) etaField.attributedStringValue = NSAttributedString(string: dataObject.metadataForMeeting(), attributes: timeAttributes) } - + @available(OSX 10.14, *) override func viewDidChangeEffectiveAppearance() { super.viewDidChangeEffectiveAppearance() @@ -97,14 +97,12 @@ class UpcomingEventStatusItemView: NSView { } extension UpcomingEventStatusItemView: StatusItemViewConforming { - func statusItemViewSetNeedsDisplay() { nextEventField.attributedStringValue = NSAttributedString(string: dataObject.event.title, attributes: textFontAttributes) etaField.attributedStringValue = NSAttributedString(string: dataObject.metadataForMeeting(), attributes: timeAttributes) } - + func statusItemViewIdentifier() -> String { return "upcoming_event_view" } - } From fdfc08eb6a91d4c236eddd8a146b4f8c86fdc987 Mon Sep 17 00:00:00 2001 From: Abhishek Date: Sat, 26 Mar 2022 21:11:03 -0400 Subject: [PATCH 08/16] Swiftlint. --- .../OnboardingSearchController.swift | 9 +++---- Clocker/Overall App/ConfigExport.swift | 4 +-- Clocker/Overall App/Themer.swift | 3 +-- .../Overall App/VersionUpdateHandler.swift | 8 +++--- .../Data Layer/TimezoneDataOperations.swift | 2 +- .../Panel/Notes Popover/NotesPopover.swift | 10 +++---- .../TextViewWithPlaceholder.swift | 2 +- Clocker/Panel/PanelController.swift | 5 ++-- Clocker/Panel/ParentPanelController.swift | 27 +++++++------------ Clocker/Panel/UI/PanelTableView.swift | 2 +- .../UpcomingEventViewItem.swift | 3 +-- .../AppFeedbackWindowController.swift | 5 ++-- .../Appearance/AppearanceViewController.swift | 5 ++-- .../Calendar/CalendarViewController.swift | 8 +++--- .../General/PreferencesDataSource.swift | 7 +++-- .../General/PreferencesViewController.swift | 12 ++++----- .../Menu Bar/StatusContainerView.swift | 10 +++---- .../Menu Bar/StatusItemHandler.swift | 3 +-- .../Preferences/Menu Bar/StatusItemView.swift | 8 +++--- .../UpcomingEventStatusItemView.swift | 8 +++--- Clocker/StartupKit/Package.swift | 6 ++--- 21 files changed, 62 insertions(+), 85 deletions(-) diff --git a/Clocker/Onboarding/OnboardingSearchController.swift b/Clocker/Onboarding/OnboardingSearchController.swift index 2c2607a..d08eb1e 100644 --- a/Clocker/Onboarding/OnboardingSearchController.swift +++ b/Clocker/Onboarding/OnboardingSearchController.swift @@ -135,8 +135,7 @@ class OnboardingSearchController: NSViewController { private func setupLabelHidingTimer() { Timer.scheduledTimer(withTimeInterval: 5, - repeats: false) - { _ in + repeats: false) { _ in OperationQueue.main.addOperation { self.setInfoLabel(CLEmptyString) } @@ -228,7 +227,7 @@ class OnboardingSearchController: NSViewController { "latitude": latitude, "longitude": longitude, "nextUpdate": CLEmptyString, - CLCustomLabel: filteredAddress, + CLCustomLabel: filteredAddress ] as [String: Any] DataStore.shared().addTimezone(TimezoneData(with: newTimeZone)) @@ -413,7 +412,7 @@ class OnboardingSearchController: NSViewController { CLTimezoneName: formattedAddress, CLCustomLabel: formattedAddress, CLTimezoneID: CLEmptyString, - CLPlaceIdentifier: result.placeId, + CLPlaceIdentifier: result.placeId ] as [String: Any] return TimezoneData(with: totalPackage) @@ -484,7 +483,7 @@ class ResultSectionHeaderTableViewCell: NSTableCellView { class OnboardingSelectionTableRowView: NSTableRowView { override func drawSelection(in _: NSRect) { if selectionHighlightStyle != .none { - let selectionRect = NSInsetRect(bounds, 1, 1) + let selectionRect = bounds.insetBy(dx: 1, dy: 1) NSColor(calibratedWhite: 0.4, alpha: 1).setStroke() NSColor(calibratedWhite: 0.4, alpha: 1).setFill() let selectionPath = NSBezierPath(roundedRect: selectionRect, xRadius: 6, yRadius: 6) diff --git a/Clocker/Overall App/ConfigExport.swift b/Clocker/Overall App/ConfigExport.swift index 97ba117..c01bf2c 100644 --- a/Clocker/Overall App/ConfigExport.swift +++ b/Clocker/Overall App/ConfigExport.swift @@ -29,7 +29,7 @@ struct ConfigExport { CLDefaultMenubarMode, CLInstallHomeIndicatorObject, CLSwitchToCompactModeAlert, - CLDisplayDSTTransitionInfo, + CLDisplayDSTTransitionInfo ]) let dictionaryRep = UserDefaults.standard.dictionaryRepresentation() var clockerPrefs: [String: Any] = [:] @@ -53,7 +53,7 @@ struct ConfigExport { "Latitude": customObject.latitude ?? 0.0, "Longitude": customObject.longitude ?? 0.0, "Place Identifier": customObject.placeID ?? "0.0", - "Selection Type": "\(customObject.selectionType)", + "Selection Type": "\(customObject.selectionType)" ] return timezoneDictionary } diff --git a/Clocker/Overall App/Themer.swift b/Clocker/Overall App/Themer.swift index 7d53e3b..8dd347e 100644 --- a/Clocker/Overall App/Themer.swift +++ b/Clocker/Overall App/Themer.swift @@ -460,8 +460,7 @@ extension Themer { _ darkImage: NSImage, _ systemImage: NSImage, _ solarizedLightImage: NSImage, - _ solarizedDarkImage: NSImage) -> NSImage - { + _ solarizedDarkImage: NSImage) -> NSImage { if #available(macOS 10.14, *) { switch themeIndex { case .light: diff --git a/Clocker/Overall App/VersionUpdateHandler.swift b/Clocker/Overall App/VersionUpdateHandler.swift index 4d562f0..1b8d2c0 100644 --- a/Clocker/Overall App/VersionUpdateHandler.swift +++ b/Clocker/Overall App/VersionUpdateHandler.swift @@ -242,20 +242,20 @@ class VersionUpdateHandler: NSObject { y: 0.0, width: contentSize.width, height: contentSize.height)) - textView.minSize = NSMakeSize(0.0, contentSize.height) - textView.maxSize = NSMakeSize(floatMax, floatMax) + textView.minSize = NSSize(width: 0.0, height: contentSize.height) + textView.maxSize = NSSize(width: floatMax, height: floatMax) textView.isVerticallyResizable = true textView.isHorizontallyResizable = false textView.isEditable = false textView.autoresizingMask = .width - textView.textContainer?.containerSize = NSMakeSize(contentSize.width, floatMax) + textView.textContainer?.containerSize = NSSize(width: contentSize.width, height: floatMax) textView.textContainer?.widthTracksTextView = true textView.string = details scrollView.documentView = textView textView.sizeToFit() let height = min(200.0, scrollView.documentView?.frame.size.height ?? 200.0) + 3.0 - scrollView.frame = NSMakeRect(0.0, 0.0, scrollView.frame.size.width, height) + scrollView.frame = NSRect(x: 0.0, y: 0.0, width: scrollView.frame.size.width, height: height) alert.accessoryView = scrollView if ignoreButton.isEmpty == false { diff --git a/Clocker/Panel/Data Layer/TimezoneDataOperations.swift b/Clocker/Panel/Data Layer/TimezoneDataOperations.swift index 0db1170..749f6e1 100644 --- a/Clocker/Panel/Data Layer/TimezoneDataOperations.swift +++ b/Clocker/Panel/Data Layer/TimezoneDataOperations.swift @@ -283,7 +283,7 @@ extension TimezoneDataOperations { let unableToConvertDateParameters = [ "New Date": newDate, "Timezone": dataObject.timezone(), - "Locale": dateFormatter.locale.identifier, + "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/Notes Popover/NotesPopover.swift b/Clocker/Panel/Notes Popover/NotesPopover.swift index f140883..81dd3a2 100644 --- a/Clocker/Panel/Notes Popover/NotesPopover.swift +++ b/Clocker/Panel/Notes Popover/NotesPopover.swift @@ -73,7 +73,7 @@ class NotesPopover: NSViewController { "1 hour before", "2 hour before", "1 day before", - "2 days before", + "2 days before" ] alertPopupButton.removeAllItems() @@ -240,7 +240,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, @@ -322,8 +322,7 @@ class NotesPopover: NSViewController { } private func updateTimezoneInDefaultPreferences(with override: Int, - _: OverrideType) - { + _: OverrideType) { let timezones = DataStore.shared().timezones() var timezoneObjects: [TimezoneData] = [] @@ -392,8 +391,7 @@ class NotesPopover: NSViewController { timezone: model.timezone(), alertIndex: alertIndex, reminderDate: reminderPicker.dateValue, - additionalNotes: model.note) - { + additionalNotes: model.note) { showSuccessMessage() } } diff --git a/Clocker/Panel/Notes Popover/TextViewWithPlaceholder.swift b/Clocker/Panel/Notes Popover/TextViewWithPlaceholder.swift index fac52d0..7485d90 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) } diff --git a/Clocker/Panel/PanelController.swift b/Clocker/Panel/PanelController.swift index 310ee03..a52a3d0 100644 --- a/Clocker/Panel/PanelController.swift +++ b/Clocker/Panel/PanelController.swift @@ -154,8 +154,7 @@ class PanelController: ParentPanelController { } if let statusWindow = statusBackgroundWindow, - let statusButton = statusView - { + let statusButton = statusView { var statusItemFrame = statusWindow.convertToScreen(statusButton.frame) var statusItemScreen = NSScreen.main var testPoint = statusItemFrame.origin @@ -222,7 +221,7 @@ 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") diff --git a/Clocker/Panel/ParentPanelController.swift b/Clocker/Panel/ParentPanelController.swift index 7f0de6c..503dcdb 100644 --- a/Clocker/Panel/ParentPanelController.swift +++ b/Clocker/Panel/ParentPanelController.swift @@ -188,8 +188,7 @@ class ParentPanelController: NSWindowController { object: nil) NotificationCenter.default.addObserver(forName: NSUbiquitousKeyValueStore.didChangeExternallyNotification, object: self, - queue: OperationQueue.main) - { [weak self] _ in + queue: OperationQueue.main) { [weak self] _ in if let sSelf = self { sSelf.mainTableView.reloadData() sSelf.setScrollViewConstraint() @@ -341,7 +340,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) @@ -417,8 +416,7 @@ class ParentPanelController: NSWindowController { newHeight += 20 } else if DataStore.shared().shouldDisplay(.dstTransitionInfo), let obj = object, - TimezoneDataOperations(with: obj).nextDaylightSavingsTransitionIfAvailable(with: futureSliderValue) != nil - { + TimezoneDataOperations(with: obj).nextDaylightSavingsTransitionIfAvailable(with: futureSliderValue) != nil { newHeight += 20 } } @@ -606,8 +604,7 @@ class ParentPanelController: NSWindowController { if $0 < mainTableView.numberOfRows, let cellView = mainTableView.view(atColumn: 0, row: $0, makeIfNecessary: false) as? TimezoneCellView, - let model = TimezoneData.customObject(from: current) - { + let model = TimezoneData.customObject(from: current) { if let futureSliderCell = futureSlider.cell as? CustomSliderCell, futureSliderCell.tracking == true { return } @@ -627,8 +624,7 @@ class ParentPanelController: NSWindowController { if let note = model.note, !note.isEmpty { cellView.noteLabel.stringValue = note } else if DataStore.shared().shouldDisplay(.dstTransitionInfo), - let value = TimezoneDataOperations(with: model).nextDaylightSavingsTransitionIfAvailable(with: futureSliderValue) - { + let value = TimezoneDataOperations(with: model).nextDaylightSavingsTransitionIfAvailable(with: futureSliderValue) { cellView.noteLabel.stringValue = value } else { cellView.noteLabel.stringValue = CLEmptyString @@ -728,8 +724,7 @@ class ParentPanelController: NSWindowController { @IBAction func calendarButtonAction(_ sender: NSButton) { if sender.title == NSLocalizedString("Click here to start.", - comment: "Button Title for no Calendar access") - { + comment: "Button Title for no Calendar access") { showPermissionsWindow() } else { retrieveCalendarEvents() @@ -820,8 +815,7 @@ class ParentPanelController: NSWindowController { if let events = eventCenter.eventsForDate[NSCalendar.autoupdatingCurrent.startOfDay(for: now)], events.isEmpty == false { OperationQueue.main.addOperation { if self.upcomingEventCollectionView != nil, - let upcomingEvents = eventCenter.upcomingEventsForDay(events) - { + let upcomingEvents = eventCenter.upcomingEventsForDay(events) { self.upcomingEventsDataSource.updateEventsDataSource(upcomingEvents) self.upcomingEventCollectionView.reloadData() return @@ -901,7 +895,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) @@ -937,7 +931,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)! ] if leftButton.attributedTitle.string == "Not Really" { @@ -1121,8 +1115,7 @@ extension ParentPanelController: NSSharingServicePickerDelegate { stride(from: 0, to: sortedByTime.count, by: 1).forEach { if $0 < sortedByTime.count, - let dataModel = TimezoneData.customObject(from: sortedByTime[$0]) - { + let dataModel = TimezoneData.customObject(from: sortedByTime[$0]) { let dataOperations = TimezoneDataOperations(with: dataModel) let date = dataOperations.todaysDate(with: 0) let time = dataOperations.time(with: 0) diff --git a/Clocker/Panel/UI/PanelTableView.swift b/Clocker/Panel/UI/PanelTableView.swift index 8f6bdce..c0dcf45 100644 --- a/Clocker/Panel/UI/PanelTableView.swift +++ b/Clocker/Panel/UI/PanelTableView.swift @@ -32,7 +32,7 @@ class PanelTableView: NSTableView { let options: NSTrackingArea.Options = [ .mouseMoved, .mouseEnteredAndExited, - .activeAlways, + .activeAlways ] let clipRect = enclosingScrollView?.contentView.bounds ?? .zero diff --git a/Clocker/Panel/Upcoming Events/UpcomingEventViewItem.swift b/Clocker/Panel/Upcoming Events/UpcomingEventViewItem.swift index 19810f6..effe786 100644 --- a/Clocker/Panel/Upcoming Events/UpcomingEventViewItem.swift +++ b/Clocker/Panel/Upcoming Events/UpcomingEventViewItem.swift @@ -40,8 +40,7 @@ class UpcomingEventViewItem: NSCollectionViewItem { _ color: NSColor, _ link: URL?, _ delegate: UpcomingEventPanelDelegate?, - _ isCancelled: Bool) - { + _ isCancelled: Bool) { if leadingConstraint.constant != UpcomingEventViewItem.EventLeadingConstraint / 2 { leadingConstraint.animator().constant = UpcomingEventViewItem.EventLeadingConstraint / 2 } diff --git a/Clocker/Preferences/App Feedback/AppFeedbackWindowController.swift b/Clocker/Preferences/App Feedback/AppFeedbackWindowController.swift index 0cce1b5..05fb914 100644 --- a/Clocker/Preferences/App Feedback/AppFeedbackWindowController.swift +++ b/Clocker/Preferences/App Feedback/AppFeedbackWindowController.swift @@ -80,8 +80,7 @@ class AppFeedbackWindowController: NSWindowController { themeDidChangeNotification = NotificationCenter.default.addObserver(forName: .themeDidChangeNotification, object: nil, - queue: OperationQueue.main) - { _ in + queue: OperationQueue.main) { _ in self.window?.backgroundColor = Themer.shared().mainBackgroundColor() self.setup() } @@ -202,7 +201,7 @@ class AppFeedbackWindowController: NSWindowController { AppFeedbackConstants.CLOperatingSystemVersion: osVersion, AppFeedbackConstants.CLClockerVersion: versionInfo, AppFeedbackConstants.CLAppFeedbackDateProperty: todaysDate(), - AppFeedbackConstants.CLAppFeedbackUserPreferences: generateUserPreferences(), + AppFeedbackConstants.CLAppFeedbackUserPreferences: generateUserPreferences() ] } diff --git a/Clocker/Preferences/Appearance/AppearanceViewController.swift b/Clocker/Preferences/Appearance/AppearanceViewController.swift index 79558af..9c41148 100644 --- a/Clocker/Preferences/Appearance/AppearanceViewController.swift +++ b/Clocker/Preferences/Appearance/AppearanceViewController.swift @@ -60,7 +60,7 @@ class AppearanceViewController: ParentViewController { "4 days", "5 days", "6 days", - "7 days", + "7 days" ]) if #available(macOS 11.0, *) {} else { @@ -188,8 +188,7 @@ class AppearanceViewController: ParentViewController { refresh(panel: true, floating: true) if let selectedFormat = sender.selectedItem?.title, - selectedFormat.contains("ss") - { + selectedFormat.contains("ss") { Logger.info("Selected format contains timezone format") guard let panelController = PanelController.panel() else { return } panelController.pauseTimer() diff --git a/Clocker/Preferences/Calendar/CalendarViewController.swift b/Clocker/Preferences/Calendar/CalendarViewController.swift index fd17568..6e77ab4 100644 --- a/Clocker/Preferences/Calendar/CalendarViewController.swift +++ b/Clocker/Preferences/Calendar/CalendarViewController.swift @@ -114,7 +114,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) @@ -243,15 +243,13 @@ extension CalendarViewController: NSTableViewDelegate { 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 - { + let message = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "sourceCellView"), owner: self) as? SourceTableViewCell { message.sourceName.stringValue = currentSource return message } if let currentSource = calendars[row] as? CalendarInfo, - let calendarCell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "calendarCellView"), owner: self) as? CalendarTableViewCell - { + let calendarCell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "calendarCellView"), owner: self) as? CalendarTableViewCell { calendarCell.calendarName.stringValue = currentSource.calendar.title calendarCell.calendarSelected.state = currentSource.selected ? NSControl.StateValue.on : NSControl.StateValue.off calendarCell.calendarSelected.target = self diff --git a/Clocker/Preferences/General/PreferencesDataSource.swift b/Clocker/Preferences/General/PreferencesDataSource.swift index 63d464d..770f83d 100644 --- a/Clocker/Preferences/General/PreferencesDataSource.swift +++ b/Clocker/Preferences/General/PreferencesDataSource.swift @@ -104,8 +104,7 @@ extension PreferencesDataSource: NSTableViewDataSource { var selectedDataSource: TimezoneData? if selectedTimezones.count > row, - let model = TimezoneData.customObject(from: selectedTimezones[row]) - { + let model = TimezoneData.customObject(from: selectedTimezones[row]) { selectedDataSource = model } @@ -162,7 +161,7 @@ extension PreferencesDataSource: NSTableViewDataSource { if selectedTimezones.count > row { Logger.log(object: [ "Old Label": dataObject.customLabel ?? "Error", - "New Label": formattedValue, + "New Label": formattedValue ], for: "Custom Label Changed") @@ -175,7 +174,7 @@ extension PreferencesDataSource: NSTableViewDataSource { Logger.log(object: [ "MethodName": "SetObjectValue", "Selected Timezone Count": selectedTimezones.count, - "Current Row": row, + "Current Row": row ], for: "Error in selected row count") } diff --git a/Clocker/Preferences/General/PreferencesViewController.swift b/Clocker/Preferences/General/PreferencesViewController.swift index f59decb..4184a56 100644 --- a/Clocker/Preferences/General/PreferencesViewController.swift +++ b/Clocker/Preferences/General/PreferencesViewController.swift @@ -95,8 +95,7 @@ class PreferencesViewController: ParentViewController { NotificationCenter.default.addObserver(forName: NSUbiquitousKeyValueStore.didChangeExternallyNotification, object: self, - queue: OperationQueue.main) - { [weak self] _ in + queue: OperationQueue.main) { [weak self] _ in if let sSelf = self { sSelf.refreshTimezoneTableView() } @@ -249,7 +248,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)! ]) } @@ -345,8 +344,7 @@ extension PreferencesViewController: NSTableViewDataSource, NSTableViewDelegate if let appDelegate = NSApplication.shared.delegate as? AppDelegate, let menubarFavourites = DataStore.shared().menubarTimezones(), menubarFavourites.isEmpty, - DataStore.shared().shouldDisplay(.showMeetingInMenubar) == false - { + DataStore.shared().shouldDisplay(.showMeetingInMenubar) == false { appDelegate.invalidateMenubarTimer(true) } @@ -510,7 +508,7 @@ extension PreferencesViewController { CLTimezoneName: formattedAddress, CLCustomLabel: formattedAddress, CLTimezoneID: CLEmptyString, - CLPlaceIdentifier: $0.placeId, + CLPlaceIdentifier: $0.placeId ] as [String: Any] finalResults.append(TimezoneData(with: totalPackage)) @@ -602,7 +600,7 @@ extension PreferencesViewController { "latitude": dataObject.latitude!, "longitude": dataObject.longitude!, "nextUpdate": CLEmptyString, - CLCustomLabel: filteredAddress, + CLCustomLabel: filteredAddress ] as [String: Any] // Mark if the timezone is same as local timezone diff --git a/Clocker/Preferences/Menu Bar/StatusContainerView.swift b/Clocker/Preferences/Menu Bar/StatusContainerView.swift index 282d598..2e95f92 100644 --- a/Clocker/Preferences/Menu Bar/StatusContainerView.swift +++ b/Clocker/Preferences/Menu Bar/StatusContainerView.swift @@ -33,12 +33,10 @@ func compactWidth(for timezone: TimezoneData) -> Int { if timeFormat == DateFormat.twelveHour || timeFormat == DateFormat.twelveHourWithSeconds || timeFormat == DateFormat.twelveHourWithZero - || timeFormat == DateFormat.twelveHourWithSeconds - { + || timeFormat == DateFormat.twelveHourWithSeconds { totalWidth += 20 } else if timeFormat == DateFormat.twentyFourHour - || timeFormat == DateFormat.twentyFourHourWithSeconds - { + || timeFormat == DateFormat.twentyFourHourWithSeconds { totalWidth += 0 } @@ -78,7 +76,7 @@ class StatusContainerView: NSView { let timeBasedAttributes = [ NSAttributedString.Key.font: compactModeTimeFont, NSAttributedString.Key.backgroundColor: NSColor.clear, - NSAttributedString.Key.paragraphStyle: defaultParagraphStyle, + NSAttributedString.Key.paragraphStyle: defaultParagraphStyle ] func containerWidth(for timezones: [Data]) -> CGFloat { @@ -137,7 +135,7 @@ class StatusContainerView: NSView { NSAttributedString.Key.font: compactModeTimeFont, NSAttributedString.Key.foregroundColor: textColor, NSAttributedString.Key.backgroundColor: NSColor.clear, - NSAttributedString.Key.paragraphStyle: defaultParagraphStyle, + NSAttributedString.Key.paragraphStyle: defaultParagraphStyle ] let operation = TimezoneDataOperations(with: timezone) diff --git a/Clocker/Preferences/Menu Bar/StatusItemHandler.swift b/Clocker/Preferences/Menu Bar/StatusItemHandler.swift index d055680..4b3c568 100644 --- a/Clocker/Preferences/Menu Bar/StatusItemHandler.swift +++ b/Clocker/Preferences/Menu Bar/StatusItemHandler.swift @@ -115,8 +115,7 @@ class StatusItemHandler: NSObject { userNotificationsDidChangeNotif = center.addObserver(forName: UserDefaults.didChangeNotification, object: self, - queue: mainQueue) - { _ in + queue: mainQueue) { _ in self.setupStatusItem() } diff --git a/Clocker/Preferences/Menu Bar/StatusItemView.swift b/Clocker/Preferences/Menu Bar/StatusItemView.swift index a2b871b..597d740 100644 --- a/Clocker/Preferences/Menu Bar/StatusItemView.swift +++ b/Clocker/Preferences/Menu Bar/StatusItemView.swift @@ -50,7 +50,7 @@ class StatusItemView: NSView { NSAttributedString.Key.font: compactModeTimeFont, NSAttributedString.Key.foregroundColor: textColor, NSAttributedString.Key.backgroundColor: NSColor.clear, - NSAttributedString.Key.paragraphStyle: defaultParagraphStyle, + NSAttributedString.Key.paragraphStyle: defaultParagraphStyle ] return attributes } @@ -62,7 +62,7 @@ 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 } @@ -91,14 +91,14 @@ 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) ]) } diff --git a/Clocker/Preferences/Menu Bar/UpcomingEventStatusItemView.swift b/Clocker/Preferences/Menu Bar/UpcomingEventStatusItemView.swift index 52196ac..640e03a 100644 --- a/Clocker/Preferences/Menu Bar/UpcomingEventStatusItemView.swift +++ b/Clocker/Preferences/Menu Bar/UpcomingEventStatusItemView.swift @@ -21,7 +21,7 @@ class UpcomingEventStatusItemView: NSView { NSAttributedString.Key.font: compactModeTimeFont, NSAttributedString.Key.foregroundColor: textColor, NSAttributedString.Key.backgroundColor: NSColor.clear, - NSAttributedString.Key.paragraphStyle: defaultParagraphStyle, + NSAttributedString.Key.paragraphStyle: defaultParagraphStyle ] return attributes } @@ -33,7 +33,7 @@ class UpcomingEventStatusItemView: 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 } @@ -54,14 +54,14 @@ class UpcomingEventStatusItemView: NSView { nextEventField.leadingAnchor.constraint(equalTo: leadingAnchor), nextEventField.trailingAnchor.constraint(equalTo: trailingAnchor), nextEventField.topAnchor.constraint(equalTo: topAnchor, constant: 7), - nextEventField.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 0.35), + nextEventField.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 0.35) ]) NSLayoutConstraint.activate([ etaField.leadingAnchor.constraint(equalTo: leadingAnchor), etaField.trailingAnchor.constraint(equalTo: trailingAnchor, constant: 0), etaField.topAnchor.constraint(equalTo: nextEventField.bottomAnchor), - etaField.bottomAnchor.constraint(equalTo: bottomAnchor), + etaField.bottomAnchor.constraint(equalTo: bottomAnchor) ]) } diff --git a/Clocker/StartupKit/Package.swift b/Clocker/StartupKit/Package.swift index 968a353..20e83a3 100644 --- a/Clocker/StartupKit/Package.swift +++ b/Clocker/StartupKit/Package.swift @@ -6,13 +6,13 @@ import PackageDescription let package = Package( name: "StartupKit", platforms: [ - .macOS(.v10_12), + .macOS(.v10_12) ], products: [ .library( name: "StartupKit", targets: ["StartupKit"] - ), + ) ], dependencies: [ // Dependencies declare other packages that this package depends on. @@ -22,6 +22,6 @@ let package = Package( .target( name: "StartupKit", dependencies: [] - ), + ) ] ) From add37287c3ec8dd44c11daa49742c833daf703d5 Mon Sep 17 00:00:00 2001 From: Abhishek Date: Sat, 26 Mar 2022 21:11:29 -0400 Subject: [PATCH 09/16] Swiftformat. --- Clocker/CoreLoggerKit/Package.swift | 6 +++--- .../Tests/CoreLoggerKitTests/CoreLoggerKitTests.swift | 2 +- .../Tests/CoreLoggerKitTests/XCTestManifests.swift | 2 +- Clocker/CoreModelKit/Package.swift | 8 ++++---- .../Sources/CoreModelKit/TimezoneData.swift | 2 +- .../Tests/CoreModelKitTests/XCTestManifests.swift | 2 +- Clocker/Events and Reminders/CalendarHandler.swift | 8 +++----- Clocker/Events and Reminders/RemindersHandler.swift | 3 +-- Clocker/Menu Bar/StatusContainerView.swift | 10 ++++------ Clocker/Menu Bar/StatusItemHandler.swift | 3 +-- Clocker/Menu Bar/StatusItemView.swift | 8 ++++---- 11 files changed, 24 insertions(+), 30 deletions(-) diff --git a/Clocker/CoreLoggerKit/Package.swift b/Clocker/CoreLoggerKit/Package.swift index 12cf1cc..581f3de 100644 --- a/Clocker/CoreLoggerKit/Package.swift +++ b/Clocker/CoreLoggerKit/Package.swift @@ -6,13 +6,13 @@ import PackageDescription let package = Package( name: "CoreLoggerKit", platforms: [ - .macOS(.v10_12), + .macOS(.v10_12) ], products: [ .library( name: "CoreLoggerKit", targets: ["CoreLoggerKit"] - ), + ) ], dependencies: [], targets: [ @@ -23,6 +23,6 @@ let package = Package( .testTarget( name: "CoreLoggerKitTests", dependencies: ["CoreLoggerKit"] - ), + ) ] ) diff --git a/Clocker/CoreLoggerKit/Tests/CoreLoggerKitTests/CoreLoggerKitTests.swift b/Clocker/CoreLoggerKit/Tests/CoreLoggerKitTests/CoreLoggerKitTests.swift index 297d241..bc6b72a 100644 --- a/Clocker/CoreLoggerKit/Tests/CoreLoggerKitTests/CoreLoggerKitTests.swift +++ b/Clocker/CoreLoggerKit/Tests/CoreLoggerKitTests/CoreLoggerKitTests.swift @@ -3,6 +3,6 @@ import XCTest final class CoreLoggerKitTests: XCTestCase { static var allTests = [ - ("testExample", testExample), + ("testExample", testExample) ] } diff --git a/Clocker/CoreLoggerKit/Tests/CoreLoggerKitTests/XCTestManifests.swift b/Clocker/CoreLoggerKit/Tests/CoreLoggerKitTests/XCTestManifests.swift index d128ae8..f90333e 100644 --- a/Clocker/CoreLoggerKit/Tests/CoreLoggerKitTests/XCTestManifests.swift +++ b/Clocker/CoreLoggerKit/Tests/CoreLoggerKitTests/XCTestManifests.swift @@ -3,7 +3,7 @@ import XCTest #if !canImport(ObjectiveC) public func allTests() -> [XCTestCaseEntry] { return [ - testCase(CoreLoggerKitTests.allTests), + testCase(CoreLoggerKitTests.allTests) ] } #endif diff --git a/Clocker/CoreModelKit/Package.swift b/Clocker/CoreModelKit/Package.swift index fe1bb6d..0c0ef9e 100644 --- a/Clocker/CoreModelKit/Package.swift +++ b/Clocker/CoreModelKit/Package.swift @@ -6,19 +6,19 @@ import PackageDescription let package = Package( name: "CoreModelKit", platforms: [ - .macOS(.v10_12), + .macOS(.v10_12) ], products: [ // Products define the executables and libraries a package produces, and make them visible to other packages. .library( name: "CoreModelKit", targets: ["CoreModelKit"] - ), + ) ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), - .package(path: "../CoreLoggerKit/"), + .package(path: "../CoreLoggerKit/") ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. @@ -30,6 +30,6 @@ let package = Package( .testTarget( name: "CoreModelKitTests", dependencies: ["CoreModelKit", "CoreLoggerKit"] - ), + ) ] ) diff --git a/Clocker/CoreModelKit/Sources/CoreModelKit/TimezoneData.swift b/Clocker/CoreModelKit/Sources/CoreModelKit/TimezoneData.swift index ec66b4c..9f4e54a 100644 --- a/Clocker/CoreModelKit/Sources/CoreModelKit/TimezoneData.swift +++ b/Clocker/CoreModelKit/Sources/CoreModelKit/TimezoneData.swift @@ -66,7 +66,7 @@ public class TimezoneData: NSObject, NSCoding { // Suffix NSNumber(integerLiteral: 9): DateFormat.twelveHourWithoutSuffix, NSNumber(integerLiteral: 10): DateFormat.twelveHourWithoutSuffixAndSeconds, - NSNumber(integerLiteral: 11): DateFormat.epochTime, + NSNumber(integerLiteral: 11): DateFormat.epochTime ] public var customLabel: String? diff --git a/Clocker/CoreModelKit/Tests/CoreModelKitTests/XCTestManifests.swift b/Clocker/CoreModelKit/Tests/CoreModelKitTests/XCTestManifests.swift index 0f55ba6..5bee46f 100644 --- a/Clocker/CoreModelKit/Tests/CoreModelKitTests/XCTestManifests.swift +++ b/Clocker/CoreModelKit/Tests/CoreModelKitTests/XCTestManifests.swift @@ -3,7 +3,7 @@ import XCTest #if !canImport(ObjectiveC) public func allTests() -> [XCTestCaseEntry] { return [ - testCase(CoreModelKitTests.allTests), + testCase(CoreModelKitTests.allTests) ] } #endif diff --git a/Clocker/Events and Reminders/CalendarHandler.swift b/Clocker/Events and Reminders/CalendarHandler.swift index 817e73d..190002e 100644 --- a/Clocker/Events and Reminders/CalendarHandler.swift +++ b/Clocker/Events and Reminders/CalendarHandler.swift @@ -383,7 +383,7 @@ extension EventCenter { // Borrowing logic from Ityscal @discardableResult private func findAppropriateURLs(_ description: String) -> URL? { - guard let results = EventCenter.dataDetector?.matches(in: description, options: .reportCompletion, range: NSMakeRange(0, description.count)) else { + guard let results = EventCenter.dataDetector?.matches(in: description, options: .reportCompletion, range: NSRange(location: 0, length: description.count)) else { return nil } for result in results { @@ -391,8 +391,7 @@ extension EventCenter { // Check for Zoom links if actualLink.contains("zoom.us/j/") || actualLink.contains("zoom.us/s/") - || actualLink.contains("zoom.us/w/") - { + || actualLink.contains("zoom.us/w/") { // Create a Zoom App link let workspace = NSWorkspace.shared if workspace.urlForApplication(toOpen: URL(string: "zoommtg://")!) != nil { @@ -418,8 +417,7 @@ extension EventCenter { || actualLink.contains("public.senfcall.de") || actualLink.contains("youcanbook.me/zoom/") || actualLink.contains("workplace.com/groupcall") - || actualLink.contains("bluejeans.com/") - { + || actualLink.contains("bluejeans.com/") { if let meetingLink = result.url { return meetingLink } diff --git a/Clocker/Events and Reminders/RemindersHandler.swift b/Clocker/Events and Reminders/RemindersHandler.swift index 9b93518..7546c81 100644 --- a/Clocker/Events and Reminders/RemindersHandler.swift +++ b/Clocker/Events and Reminders/RemindersHandler.swift @@ -51,8 +51,7 @@ extension EventCenter { timezone: String, alertIndex: Int, reminderDate: Date, - additionalNotes: String?) -> Bool - { + additionalNotes: String?) -> Bool { initializeStoreIfNeccesary() if reminderAccessNotDetermined() || reminderAccessDenied() { diff --git a/Clocker/Menu Bar/StatusContainerView.swift b/Clocker/Menu Bar/StatusContainerView.swift index c266f5f..3e9c4ab 100644 --- a/Clocker/Menu Bar/StatusContainerView.swift +++ b/Clocker/Menu Bar/StatusContainerView.swift @@ -31,12 +31,10 @@ func compactWidth(for timezone: TimezoneData) -> Int { if timeFormat == DateFormat.twelveHour || timeFormat == DateFormat.twelveHourWithSeconds || timeFormat == DateFormat.twelveHourWithZero - || timeFormat == DateFormat.twelveHourWithSeconds - { + || timeFormat == DateFormat.twelveHourWithSeconds { totalWidth += 20 } else if timeFormat == DateFormat.twentyFourHour - || timeFormat == DateFormat.twentyFourHourWithSeconds - { + || timeFormat == DateFormat.twentyFourHourWithSeconds { totalWidth += 0 } @@ -77,7 +75,7 @@ class StatusContainerView: NSView { let timeBasedAttributes = [ NSAttributedString.Key.font: compactModeTimeFont, NSAttributedString.Key.backgroundColor: NSColor.clear, - NSAttributedString.Key.paragraphStyle: defaultParagraphStyle, + NSAttributedString.Key.paragraphStyle: defaultParagraphStyle ] func containerWidth(for timezones: [Data]) -> CGFloat { @@ -136,7 +134,7 @@ class StatusContainerView: NSView { NSAttributedString.Key.font: compactModeTimeFont, NSAttributedString.Key.foregroundColor: textColor, NSAttributedString.Key.backgroundColor: NSColor.clear, - NSAttributedString.Key.paragraphStyle: defaultParagraphStyle, + NSAttributedString.Key.paragraphStyle: defaultParagraphStyle ] let operation = TimezoneDataOperations(with: timezone) diff --git a/Clocker/Menu Bar/StatusItemHandler.swift b/Clocker/Menu Bar/StatusItemHandler.swift index 669a664..cc941d7 100644 --- a/Clocker/Menu Bar/StatusItemHandler.swift +++ b/Clocker/Menu Bar/StatusItemHandler.swift @@ -112,8 +112,7 @@ class StatusItemHandler: NSObject { userNotificationsDidChangeNotif = center.addObserver(forName: UserDefaults.didChangeNotification, object: self, - queue: mainQueue) - { _ in + queue: mainQueue) { _ in self.setupStatusItem() } } diff --git a/Clocker/Menu Bar/StatusItemView.swift b/Clocker/Menu Bar/StatusItemView.swift index fff2da2..ef9d594 100644 --- a/Clocker/Menu Bar/StatusItemView.swift +++ b/Clocker/Menu Bar/StatusItemView.swift @@ -49,7 +49,7 @@ class StatusItemView: NSView { NSAttributedString.Key.font: compactModeTimeFont, NSAttributedString.Key.foregroundColor: textColor, NSAttributedString.Key.backgroundColor: NSColor.clear, - NSAttributedString.Key.paragraphStyle: defaultParagraphStyle, + NSAttributedString.Key.paragraphStyle: defaultParagraphStyle ] return attributes } @@ -61,7 +61,7 @@ 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 } @@ -90,14 +90,14 @@ 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) ]) } From d45834a2ad5c29ea7c80bc444a93aeb5b3affb72 Mon Sep 17 00:00:00 2001 From: Abhishek Banthia <8280282+n0shake@users.noreply.github.com> Date: Sun, 27 Mar 2022 11:10:34 -0400 Subject: [PATCH 10/16] Unit tests for DateFormatterManager Cleaning up unused methods.. --- Clocker/Clocker.xcodeproj/project.pbxproj | 4 +++ .../ClockerUnitTests/ClockerUnitTests.swift | 11 ++++++ .../DateFormatterManagerTests.swift | 36 +++++++++++++++++++ .../Overall App/DateFormatterManager.swift | 25 ------------- 4 files changed, 51 insertions(+), 25 deletions(-) create mode 100644 Clocker/ClockerUnitTests/DateFormatterManagerTests.swift diff --git a/Clocker/Clocker.xcodeproj/project.pbxproj b/Clocker/Clocker.xcodeproj/project.pbxproj index c5f3d17..62049eb 100755 --- a/Clocker/Clocker.xcodeproj/project.pbxproj +++ b/Clocker/Clocker.xcodeproj/project.pbxproj @@ -51,6 +51,7 @@ 3548C45F26BEEFB400AFB533 /* UpcomingEventsDataSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3548C45E26BEEFB400AFB533 /* UpcomingEventsDataSource.swift */; }; 3548C46126BEEFE400AFB533 /* UpcomingEventViewItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3548C46026BEEFE400AFB533 /* UpcomingEventViewItem.swift */; }; 35584D1427EF8EB5006E3EAD /* ThemerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 35584D1327EF8EB5006E3EAD /* ThemerTests.swift */; }; + 35584D1827F0B019006E3EAD /* DateFormatterManagerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 35584D1727F0B019006E3EAD /* DateFormatterManagerTests.swift */; }; 357391872507277500D30819 /* TimeMarkerViewItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 357391852507277500D30819 /* TimeMarkerViewItem.swift */; }; 357391882507277500D30819 /* HourMarkerViewItem.xib in Resources */ = {isa = PBXBuildFile; fileRef = 357391862507277500D30819 /* HourMarkerViewItem.xib */; }; 3579765E2680208C009DDA6E /* ParentPanelController+ModernSlider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3579765D2680208C009DDA6E /* ParentPanelController+ModernSlider.swift */; }; @@ -286,6 +287,7 @@ 3552066427AF6488000EF08F /* pl */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = pl; path = pl.lproj/InfoPlist.strings; sourceTree = ""; }; 3552066527AF6489000EF08F /* pl */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = pl; path = pl.lproj/Localizable.strings; sourceTree = ""; }; 35584D1327EF8EB5006E3EAD /* ThemerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ThemerTests.swift; sourceTree = ""; }; + 35584D1727F0B019006E3EAD /* DateFormatterManagerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DateFormatterManagerTests.swift; sourceTree = ""; }; 3569A44E25441F320087E254 /* pt-BR */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = "pt-BR"; path = "pt-BR.lproj/Localizable.strings"; sourceTree = ""; }; 357391852507277500D30819 /* TimeMarkerViewItem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TimeMarkerViewItem.swift; sourceTree = ""; }; 357391862507277500D30819 /* HourMarkerViewItem.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = HourMarkerViewItem.xib; sourceTree = ""; }; @@ -881,6 +883,7 @@ C20839CB21515C1F00C86589 /* Info.plist */, 9A0385BA269E3434003B5E72 /* StandardMenubarHandlerTests.swift */, 35584D1327EF8EB5006E3EAD /* ThemerTests.swift */, + 35584D1727F0B019006E3EAD /* DateFormatterManagerTests.swift */, ); path = ClockerUnitTests; sourceTree = ""; @@ -1268,6 +1271,7 @@ files = ( 35584D1427EF8EB5006E3EAD /* ThemerTests.swift in Sources */, 9A0385BB269E3434003B5E72 /* StandardMenubarHandlerTests.swift in Sources */, + 35584D1827F0B019006E3EAD /* DateFormatterManagerTests.swift in Sources */, C20839CA21515C1E00C86589 /* ClockerUnitTests.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; diff --git a/Clocker/ClockerUnitTests/ClockerUnitTests.swift b/Clocker/ClockerUnitTests/ClockerUnitTests.swift index 48e8b5d..994ff35 100644 --- a/Clocker/ClockerUnitTests/ClockerUnitTests.swift +++ b/Clocker/ClockerUnitTests/ClockerUnitTests.swift @@ -392,4 +392,15 @@ class ClockerUnitTests: XCTestCase { XCTAssertNotNil(convertedDate) } } + + func testStringFiltering() { + let stringWithComma = "Mumbai, Maharashtra" + let stringWithoutComma = "Mumbai" + let emptyString = "" + + XCTAssertEqual(stringWithComma.filteredName(), "Mumbai") + XCTAssertEqual(stringWithoutComma.filteredName(), "Mumbai") + XCTAssertEqual(emptyString.filteredName(), "") + + } } diff --git a/Clocker/ClockerUnitTests/DateFormatterManagerTests.swift b/Clocker/ClockerUnitTests/DateFormatterManagerTests.swift new file mode 100644 index 0000000..0ae9e05 --- /dev/null +++ b/Clocker/ClockerUnitTests/DateFormatterManagerTests.swift @@ -0,0 +1,36 @@ +// Copyright © 2015 Abhishek Banthia + +import XCTest + +@testable import Clocker; + +class DateFormatterManagerTests: XCTestCase { + + func testRegularDateFormatter() throws { + let subject = DateFormatterManager.dateFormatter(with: .medium, for: "UTC") + XCTAssertEqual(subject.dateStyle, .medium) + XCTAssertEqual(subject.timeStyle, .medium) + XCTAssertEqual(subject.locale.identifier, "en_US") + XCTAssertEqual(subject.timeZone.identifier, "GMT") + } + + func testDateFormatterWithFormat() throws { + let subject = DateFormatterManager.dateFormatterWithFormat(with: .none, format: "hh:mm a", timezoneIdentifier: "Asia/Calcutta") + XCTAssertEqual(subject.dateStyle, .none) + XCTAssertEqual(subject.timeStyle, .none) + XCTAssertEqual(subject.locale.identifier, "en_US") + XCTAssertEqual(subject.timeZone.identifier, "Asia/Calcutta") + XCTAssertEqual(subject.locale.identifier, "en_US") + XCTAssertEqual(subject.dateFormat, "hh:mm a") + } + + func testLocalizedDateFormatter() throws { + let subject = DateFormatterManager.localizedFormatter(with: "hh:mm:ss", for: "America/Los_Angeles") + XCTAssertEqual(subject.dateStyle, .none) + XCTAssertEqual(subject.timeStyle, .none) + XCTAssertEqual(subject.locale.identifier, Locale.autoupdatingCurrent.identifier) + XCTAssertEqual(subject.timeZone.identifier, "America/Los_Angeles") + XCTAssertEqual(subject.dateFormat, "hh:mm:ss") + } + +} diff --git a/Clocker/Overall App/DateFormatterManager.swift b/Clocker/Overall App/DateFormatterManager.swift index db70d94..2a11b0f 100644 --- a/Clocker/Overall App/DateFormatterManager.swift +++ b/Clocker/Overall App/DateFormatterManager.swift @@ -3,7 +3,6 @@ import Cocoa class DateFormatterManager: NSObject { - public static let sharedInstance = DateFormatterManager() private static var dateFormatter = DateFormatter() private static var calendarDateFormatter = DateFormatter() @@ -22,21 +21,6 @@ class DateFormatterManager: NSObject { return dateFormatter } - class func dateFormatterWithCalendar(with style: DateFormatter.Style) -> DateFormatter { - calendarDateFormatter.dateStyle = style - calendarDateFormatter.timeStyle = style - calendarDateFormatter.locale = USLocale - calendarDateFormatter.calendar = gregorianCalendar - return calendarDateFormatter - } - - class func simpleFormatter(with style: DateFormatter.Style) -> DateFormatter { - simpleFormatter.dateStyle = style - simpleFormatter.timeStyle = style - simpleFormatter.locale = USLocale - return simpleFormatter - } - class func dateFormatterWithFormat(with style: DateFormatter.Style, format: String, timezoneIdentifier: String, locale: Locale = Locale(identifier: "en_US")) -> DateFormatter { specializedFormatter.dateStyle = style specializedFormatter.timeStyle = style @@ -55,15 +39,6 @@ class DateFormatterManager: NSObject { return dateFormatter } - class func localizedCalendaricalDateFormatter(with format: String) -> DateFormatter { - calendarDateFormatter.dateStyle = .none - calendarDateFormatter.timeStyle = .none - calendarDateFormatter.locale = Locale.autoupdatingCurrent - calendarDateFormatter.dateFormat = format - calendarDateFormatter.calendar = gregorianCalendar - return calendarDateFormatter - } - class func localizedSimpleFormatter(_ format: String) -> DateFormatter { localizedSimpleFormatter.dateStyle = .none localizedSimpleFormatter.timeStyle = .none From dad91c836da2eb4d88c4b8022dae06855b50e960 Mon Sep 17 00:00:00 2001 From: Abhishek Banthia <8280282+n0shake@users.noreply.github.com> Date: Sun, 27 Mar 2022 12:03:08 -0400 Subject: [PATCH 11/16] Cleanup uncalled method. --- Clocker/AppDelegate.swift | 4 ---- Clocker/Panel/ParentPanelController.swift | 2 +- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/Clocker/AppDelegate.swift b/Clocker/AppDelegate.swift index a2d76ec..e49ba70 100644 --- a/Clocker/AppDelegate.swift +++ b/Clocker/AppDelegate.swift @@ -262,10 +262,6 @@ open class AppDelegate: NSObject, NSApplicationDelegate { return statusBarHandler } - open func setPanelDefaults() { - panelController.updateDefaultPreferences() - } - open func setupMenubarTimer() { statusBarHandler.setupStatusItem() } diff --git a/Clocker/Panel/ParentPanelController.swift b/Clocker/Panel/ParentPanelController.swift index 7f0de6c..4d16a3f 100644 --- a/Clocker/Panel/ParentPanelController.swift +++ b/Clocker/Panel/ParentPanelController.swift @@ -790,7 +790,7 @@ class ParentPanelController: NSWindowController { sharedDelegate.setupFloatingWindow(false) } else { sharedDelegate.setupFloatingWindow(true) - sharedDelegate.setPanelDefaults() + updateDefaultPreferences() } let mode = inverseSelection.isEqual(to: NSNumber(value: 1)) ? "Floating Mode" : "Menubar Mode" From d67ab4671fd10b50a9c7df58e4fe581d14036157 Mon Sep 17 00:00:00 2001 From: Abhishek Banthia <8280282+n0shake@users.noreply.github.com> Date: Sun, 27 Mar 2022 12:18:57 -0400 Subject: [PATCH 12/16] Tests for App Delegate behaviour. --- Clocker/Clocker.xcodeproj/project.pbxproj | 4 + .../ClockerUnitTests/AppDelegateTests.swift | 73 +++++++++++++++++++ .../DateFormatterManagerTests.swift | 2 +- 3 files changed, 78 insertions(+), 1 deletion(-) create mode 100644 Clocker/ClockerUnitTests/AppDelegateTests.swift diff --git a/Clocker/Clocker.xcodeproj/project.pbxproj b/Clocker/Clocker.xcodeproj/project.pbxproj index 62049eb..9205298 100755 --- a/Clocker/Clocker.xcodeproj/project.pbxproj +++ b/Clocker/Clocker.xcodeproj/project.pbxproj @@ -52,6 +52,7 @@ 3548C46126BEEFE400AFB533 /* UpcomingEventViewItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3548C46026BEEFE400AFB533 /* UpcomingEventViewItem.swift */; }; 35584D1427EF8EB5006E3EAD /* ThemerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 35584D1327EF8EB5006E3EAD /* ThemerTests.swift */; }; 35584D1827F0B019006E3EAD /* DateFormatterManagerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 35584D1727F0B019006E3EAD /* DateFormatterManagerTests.swift */; }; + 35584D1A27F0B64E006E3EAD /* AppDelegateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 35584D1927F0B64E006E3EAD /* AppDelegateTests.swift */; }; 357391872507277500D30819 /* TimeMarkerViewItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 357391852507277500D30819 /* TimeMarkerViewItem.swift */; }; 357391882507277500D30819 /* HourMarkerViewItem.xib in Resources */ = {isa = PBXBuildFile; fileRef = 357391862507277500D30819 /* HourMarkerViewItem.xib */; }; 3579765E2680208C009DDA6E /* ParentPanelController+ModernSlider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3579765D2680208C009DDA6E /* ParentPanelController+ModernSlider.swift */; }; @@ -288,6 +289,7 @@ 3552066527AF6489000EF08F /* pl */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = pl; path = pl.lproj/Localizable.strings; sourceTree = ""; }; 35584D1327EF8EB5006E3EAD /* ThemerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ThemerTests.swift; sourceTree = ""; }; 35584D1727F0B019006E3EAD /* DateFormatterManagerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DateFormatterManagerTests.swift; sourceTree = ""; }; + 35584D1927F0B64E006E3EAD /* AppDelegateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegateTests.swift; sourceTree = ""; }; 3569A44E25441F320087E254 /* pt-BR */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = "pt-BR"; path = "pt-BR.lproj/Localizable.strings"; sourceTree = ""; }; 357391852507277500D30819 /* TimeMarkerViewItem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TimeMarkerViewItem.swift; sourceTree = ""; }; 357391862507277500D30819 /* HourMarkerViewItem.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = HourMarkerViewItem.xib; sourceTree = ""; }; @@ -884,6 +886,7 @@ 9A0385BA269E3434003B5E72 /* StandardMenubarHandlerTests.swift */, 35584D1327EF8EB5006E3EAD /* ThemerTests.swift */, 35584D1727F0B019006E3EAD /* DateFormatterManagerTests.swift */, + 35584D1927F0B64E006E3EAD /* AppDelegateTests.swift */, ); path = ClockerUnitTests; sourceTree = ""; @@ -1270,6 +1273,7 @@ buildActionMask = 2147483647; files = ( 35584D1427EF8EB5006E3EAD /* ThemerTests.swift in Sources */, + 35584D1A27F0B64E006E3EAD /* AppDelegateTests.swift in Sources */, 9A0385BB269E3434003B5E72 /* StandardMenubarHandlerTests.swift in Sources */, 35584D1827F0B019006E3EAD /* DateFormatterManagerTests.swift in Sources */, C20839CA21515C1E00C86589 /* ClockerUnitTests.swift in Sources */, diff --git a/Clocker/ClockerUnitTests/AppDelegateTests.swift b/Clocker/ClockerUnitTests/AppDelegateTests.swift new file mode 100644 index 0000000..91250af --- /dev/null +++ b/Clocker/ClockerUnitTests/AppDelegateTests.swift @@ -0,0 +1,73 @@ +// Copyright © 2015 Abhishek Banthia + +import XCTest + +@testable import Clocker + +class AppDelegateTests: XCTestCase { + + func testStatusItemIsInitialized() throws { + let subject = NSApplication.shared.delegate as? AppDelegate + let statusHandler = subject?.statusItemForPanel() + XCTAssertNotNil(EventCenter.sharedCenter) + XCTAssertNotNil(statusHandler) + } + + func testDockMenu() throws { + let subject = NSApplication.shared.delegate as? AppDelegate + let dockMenu = subject?.applicationDockMenu(NSApplication.shared) + let items = dockMenu?.items ?? [] + + XCTAssertEqual(dockMenu?.title, "Quick Access") + XCTAssertEqual(items.first?.title, "Toggle Panel") + XCTAssertEqual(items[1].title, "Preferences") + XCTAssertEqual(items[1].keyEquivalent, ",") + XCTAssertEqual(items[2].title, "Hide from Dock") + + // Test selections + XCTAssertEqual(items.first?.action, #selector(AppDelegate.togglePanel(_:))) + XCTAssertEqual(items[2].action, #selector(AppDelegate.hideFromDock)) + + items.forEach { menuItem in + XCTAssertTrue(menuItem.isEnabled) + } + } + + func testSetupMenubarTimer() { + let subject = NSApplication.shared.delegate as? AppDelegate + + let statusItemHandler = subject?.statusItemForPanel() + XCTAssertEqual(statusItemHandler?.statusItem.autosaveName, NSStatusItem.AutosaveName("ClockerStatusItem")) + } + + func testFloatingWindow() { + let subject = NSApplication.shared.delegate as? AppDelegate + let previousWindows = NSApplication.shared.windows + XCTAssertEqual(previousWindows.count, 1) // Only the status bar window should be present + + subject?.setupFloatingWindow(true) + + let floatingWindow = NSApplication.shared.windows.first { window in + if ((window.windowController as? FloatingWindowController) != nil) { + return true + } + return false + } + + XCTAssertNotNil(floatingWindow) + XCTAssertEqual(floatingWindow?.windowController?.windowFrameAutosaveName, NSWindow.FrameAutosaveName("FloatingWindowAutoSave")) + + subject?.setupFloatingWindow(false) + + let closedFloatingWindow = NSApplication.shared.windows.first { window in + if ((window.windowController as? FloatingWindowController) != nil) { + return true + } + return false + } + + XCTAssertNotNil(closedFloatingWindow) + } + + +} diff --git a/Clocker/ClockerUnitTests/DateFormatterManagerTests.swift b/Clocker/ClockerUnitTests/DateFormatterManagerTests.swift index 0ae9e05..ed4bcd8 100644 --- a/Clocker/ClockerUnitTests/DateFormatterManagerTests.swift +++ b/Clocker/ClockerUnitTests/DateFormatterManagerTests.swift @@ -2,7 +2,7 @@ import XCTest -@testable import Clocker; +@testable import Clocker class DateFormatterManagerTests: XCTestCase { From 6583efdf1dcc81af42ef1c5a5df33c135213c5a3 Mon Sep 17 00:00:00 2001 From: Abhishek Date: Sun, 27 Mar 2022 13:44:21 -0400 Subject: [PATCH 13/16] Remove condition causing infinite looping in unit tests --- Clocker/Overall App/Themer.swift | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/Clocker/Overall App/Themer.swift b/Clocker/Overall App/Themer.swift index 8dd347e..a0f90dc 100644 --- a/Clocker/Overall App/Themer.swift +++ b/Clocker/Overall App/Themer.swift @@ -50,11 +50,8 @@ class Themer: NSObject { object: nil) if #available(macOS 10.14, *) { - effectiveApperanceObserver = NSApp.observe(\.effectiveAppearance) { [weak self] _, _ in - if let sSelf = self { - sSelf.setAppAppearance() - NotificationCenter.default.post(name: .themeDidChangeNotification, object: nil) - } + effectiveApperanceObserver = NSApp.observe(\.effectiveAppearance) { _, _ in + NotificationCenter.default.post(name: .themeDidChangeNotification, object: nil) } } } @@ -452,7 +449,9 @@ extension Themer { } else if themeIndex == .system { appAppearance = retrieveCurrentSystem() == .dark ? NSAppearance(named: .darkAqua) : NSAppearance(named: .aqua) } - NSApp.appearance = appAppearance + if NSApp.appearance != appAppearance { + NSApp.appearance = appAppearance + } } } From d5cbd51a2b69742578f37f859cca1a046248f3d0 Mon Sep 17 00:00:00 2001 From: Abhishek Date: Sun, 27 Mar 2022 13:44:27 -0400 Subject: [PATCH 14/16] Update DataStore.swift --- Clocker/Overall App/DataStore.swift | 4 ---- 1 file changed, 4 deletions(-) diff --git a/Clocker/Overall App/DataStore.swift b/Clocker/Overall App/DataStore.swift index d9f1f5f..8be2c92 100644 --- a/Clocker/Overall App/DataStore.swift +++ b/Clocker/Overall App/DataStore.swift @@ -47,10 +47,6 @@ class DataStore: NSObject { } func timezones() -> [Data] { - if let cloudPreferences = ubiquitousStore.object(forKey: CLDefaultPreferenceKey) as? [Data] { - return cloudPreferences - } - guard let preferences = userDefaults.object(forKey: CLDefaultPreferenceKey) as? [Data] else { return [] } From 8c3e4fa4c1e38966a2f54b9361cfd02d1fcf3ec3 Mon Sep 17 00:00:00 2001 From: Abhishek Date: Sun, 27 Mar 2022 14:21:09 -0400 Subject: [PATCH 15/16] Color to indicate we're using a debug build. --- Clocker/Panel/ParentPanelController.swift | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Clocker/Panel/ParentPanelController.swift b/Clocker/Panel/ParentPanelController.swift index 50efeef..7dc76e7 100644 --- a/Clocker/Panel/ParentPanelController.swift +++ b/Clocker/Panel/ParentPanelController.swift @@ -172,6 +172,15 @@ class ParentPanelController: NSWindowController { setupObservers() updateReviewViewFontColor() + + // Set the background color of the bottom buttons view to something different to indicate we're not in a release candidate + #if DEBUG + stackView.arrangedSubviews.last?.layer?.backgroundColor = NSColor(deviceRed: 255.0/255.0, + green: 150.0/255.0, + blue: 122.0/255.0, + alpha: 0.5).cgColor + stackView.arrangedSubviews.last?.toolTip = "Clocker is running in Debug Mode" + #endif // Setup layers futureSliderView.wantsLayer = true From a44f0f7291ed82495ea39652c44b51eea97bd34a Mon Sep 17 00:00:00 2001 From: Abhishek Date: Sun, 27 Mar 2022 14:26:27 -0400 Subject: [PATCH 16/16] Initial attempt at showing next meeting event in compact menubar mode. --- .../Calendar/CalendarViewController.swift | 1 - .../Menu Bar/MenubarTitleProvider.swift | 3 +- .../Menu Bar/StatusContainerView.swift | 64 +++++++++++++++++-- .../Menu Bar/StatusItemHandler.swift | 40 +++++++++--- 4 files changed, 93 insertions(+), 15 deletions(-) diff --git a/Clocker/Preferences/Calendar/CalendarViewController.swift b/Clocker/Preferences/Calendar/CalendarViewController.swift index 6e77ab4..9166746 100644 --- a/Clocker/Preferences/Calendar/CalendarViewController.swift +++ b/Clocker/Preferences/Calendar/CalendarViewController.swift @@ -84,7 +84,6 @@ class CalendarViewController: ParentViewController { verifyCalendarAccess() showSegmentedControl.selectedSegment = DataStore.shared().shouldDisplay(ViewType.upcomingEventView) ? 0 : 1 - showNextMeetingInMenubarControl.isEnabled = DataStore.shared().shouldDisplay(.menubarCompactMode) ? false : true } private func verifyCalendarAccess() { diff --git a/Clocker/Preferences/Menu Bar/MenubarTitleProvider.swift b/Clocker/Preferences/Menu Bar/MenubarTitleProvider.swift index 69ea823..84aee9f 100644 --- a/Clocker/Preferences/Menu Bar/MenubarTitleProvider.swift +++ b/Clocker/Preferences/Menu Bar/MenubarTitleProvider.swift @@ -34,7 +34,7 @@ class MenubarTitleProvider: NSObject { return nil } - private func checkForUpcomingEvents() -> String? { + func checkForUpcomingEvents() -> String? { if DataStore.shared().shouldDisplay(.showMeetingInMenubar) { let filteredDates = EventCenter.sharedCenter().eventsForDate let autoupdatingCal = EventCenter.sharedCenter().autoupdatingCalendar @@ -48,7 +48,6 @@ class MenubarTitleProvider: NSObject { if timeForEventToStart > 30 { Logger.info("Our next event: \(event.event.title ?? "Error") starts in \(timeForEventToStart) mins") - continue } diff --git a/Clocker/Preferences/Menu Bar/StatusContainerView.swift b/Clocker/Preferences/Menu Bar/StatusContainerView.swift index 2e95f92..94d2bf0 100644 --- a/Clocker/Preferences/Menu Bar/StatusContainerView.swift +++ b/Clocker/Preferences/Menu Bar/StatusContainerView.swift @@ -18,6 +18,10 @@ func bufferCalculatedWidth() -> Int { if DataStore.shared().shouldShowDateInMenubar() { totalWidth += 20 } + + if DataStore.shared().shouldDisplay(.showMeetingInMenubar) { + totalWidth += 100 + } return totalWidth } @@ -55,6 +59,14 @@ func compactWidth(for timezone: TimezoneData) -> Int { // Test with Sat 12:46 AM let bufferWidth: CGFloat = 9.5 +protocol StatusItemViewConforming { + /// Mark that we need to refresh the text we're showing in the menubar + func statusItemViewSetNeedsDisplay() + + /// Status Item Views can be used to represent different information (like time in location, or an upcoming meeting). Distinguish between different status items view through this identifier + func statusItemViewIdentifier() -> String +} + class StatusContainerView: NSView { private var previousX: Int = 0 @@ -64,8 +76,20 @@ class StatusContainerView: NSView { layer?.backgroundColor = NSColor.clear.cgColor } - init(with timezones: [Data]) { + init(with timezones: [Data], showUpcomingEventView: Bool) { func addSubviews() { + if showUpcomingEventView, + let events = EventCenter.sharedCenter().eventsForDate[NSCalendar.autoupdatingCurrent.startOfDay(for: Date())], + events.isEmpty == false, + let upcomingEvent = EventCenter.sharedCenter().nextOccuring(events) { + let calculatedWidth = bestWidth(for: upcomingEvent) + let frame = NSRect(x: previousX, y: 0, width: calculatedWidth, height: 30) + let calendarItemView = UpcomingEventStatusItemView(frame: frame) + calendarItemView.dataObject = upcomingEvent + addSubview(calendarItemView) + previousX += calculatedWidth + } + timezones.forEach { if let timezoneObject = TimezoneData.customObject(from: $0) { addTimezone(timezoneObject) @@ -80,7 +104,7 @@ class StatusContainerView: NSView { ] func containerWidth(for timezones: [Data]) -> CGFloat { - let compressedWidth = timezones.reduce(0.0) { result, timezone -> CGFloat in + var compressedWidth = timezones.reduce(0.0) { result, timezone -> CGFloat in if let timezoneObject = TimezoneData.customObject(from: timezone) { let precalculatedWidth = Double(compactWidth(for: timezoneObject)) @@ -95,6 +119,10 @@ class StatusContainerView: NSView { return result + CGFloat(bufferCalculatedWidth()) } + if showUpcomingEventView { + compressedWidth += 70 + } + let calculatedWidth = min(compressedWidth, CGFloat(timezones.count * bufferCalculatedWidth())) return calculatedWidth @@ -145,11 +173,41 @@ class StatusContainerView: NSView { return Int(max(bestSize.width, bestTitleSize.width) + bufferWidth) } + + private func bestWidth(for eventInfo: EventInfo) -> Int { + var textColor = hasDarkAppearance ? NSColor.white : NSColor.black + + if #available(OSX 11.0, *) { + textColor = NSColor.white + } + + let timeBasedAttributes = [ + NSAttributedString.Key.font: compactModeTimeFont, + NSAttributedString.Key.foregroundColor: textColor, + NSAttributedString.Key.backgroundColor: NSColor.clear, + NSAttributedString.Key.paragraphStyle: defaultParagraphStyle + ] + + let bestSize = compactModeTimeFont.size(eventInfo.metadataForMeeting(), + 55, // Default for a location based status view + attributes: timeBasedAttributes) + let bestTitleSize = compactModeTimeFont.size(eventInfo.event.title, + 70, // Little more buffer since meeting titles tend to be longer + attributes: timeBasedAttributes) + + return Int(max(bestSize.width, bestTitleSize.width) + bufferWidth) + } func updateTime() { if subviews.isEmpty { assertionFailure("Subviews count should > 0") } + + for view in subviews { + if let conformingView = view as? StatusItemViewConforming { + conformingView.statusItemViewSetNeedsDisplay() + } + } // See if frame's width needs any adjustment adjustWidthIfNeccessary() @@ -170,8 +228,6 @@ class StatusContainerView: NSView { y: statusItem.frame.origin.y, width: newBestWidth, height: statusItem.frame.size.height) - - statusItem.updateTimeInMenubar() } } diff --git a/Clocker/Preferences/Menu Bar/StatusItemHandler.swift b/Clocker/Preferences/Menu Bar/StatusItemHandler.swift index 4b3c568..596898c 100644 --- a/Clocker/Preferences/Menu Bar/StatusItemHandler.swift +++ b/Clocker/Preferences/Menu Bar/StatusItemHandler.swift @@ -24,7 +24,7 @@ class StatusItemHandler: NSObject { private var menubarTitleHandler = MenubarTitleProvider() - private var parentView: StatusContainerView? + private var statusContainerView: StatusContainerView? private var nsCalendar = Calendar.autoupdatingCurrent @@ -42,7 +42,7 @@ class StatusItemHandler: NSObject { switch oldValue { case .compactText: statusItem.view = nil - parentView = nil + statusContainerView = nil case .standardText: statusItem.button?.title = CLEmptyString case .icon: @@ -134,8 +134,8 @@ class StatusItemHandler: NSObject { } } - private func constructCompactView() { - parentView = nil + private func constructCompactView(with upcomingEventView: Bool = false) { + statusContainerView = nil let menubarTimezones = DataStore.shared().menubarTimezones() ?? [] if menubarTimezones.isEmpty { @@ -143,8 +143,9 @@ class StatusItemHandler: NSObject { return } - parentView = StatusContainerView(with: menubarTimezones) - statusItem.view = parentView + statusContainerView = StatusContainerView(with: menubarTimezones, + showUpcomingEventView: upcomingEventView) + statusItem.view = statusContainerView statusItem.view?.window?.backgroundColor = NSColor.clear } @@ -241,7 +242,20 @@ class StatusItemHandler: NSObject { } func updateCompactMenubar() { - parentView?.updateTime() + if let upcomingEvent = menubarTitleHandler.checkForUpcomingEvents() { + print("Need to construct upcoming event view \(upcomingEvent)") + // Iterate and see if we're showing the calendar item view + let upcomingEventView = retrieveUpcomingEventStatusView() + // If not, reconstruct Status Container View with another view + if upcomingEventView == nil { + constructCompactView(with: true) + } + } else { + let upcomingEventView = retrieveUpcomingEventStatusView() + upcomingEventView?.removeFromSuperview() + } + // This will internally call `statusItemViewSetNeedsDisplay` on all subviews ensuring all text in the menubar is up-to-date. + statusContainerView?.updateTime() } func refresh() { @@ -347,7 +361,17 @@ class StatusItemHandler: NSObject { menubarTimer?.invalidate() menubarTimer = nil - constructCompactView() + constructCompactView(with: menubarTitleHandler.checkForUpcomingEvents() != nil) updateMenubar() } + + private func retrieveUpcomingEventStatusView() -> NSView? { + let upcomingEventView = statusContainerView?.subviews.first(where: { statusItemView in + if let upcomingEventView = statusItemView as? StatusItemViewConforming { + return upcomingEventView.statusItemViewIdentifier() == "upcoming_event_view" + } + return false + }) + return upcomingEventView + } }