diff --git a/.swiftlint.yml b/.swiftlint.yml new file mode 100644 index 00000000..f1b7748d --- /dev/null +++ b/.swiftlint.yml @@ -0,0 +1,44 @@ +disabled_rules: + - force_cast # todo + - type_name # todo + - cyclomatic_complexity # todo + - trailing_whitespace + - opening_brace + - implicit_getter + - redundant_optional_initialization + +opt_in_rules: + - control_statement + - empty_count + - trailing_newline + - colon + - comma + +identifier_name: + min_length: 1 + excluded: + - AppUpdateIntervals + - TemperatureUnits + - SpeedBase + - SensorsWidgetMode + - SpeedPictogram + - BatteryAdditionals + - ShortLong + - ReaderUpdateIntervals + - NumbersOfProcesses + - NetworkReaders + - SensorsList + +line_length: 200 + +function_body_length: + - 60 + - 80 + +type_body_length: + - 300 + - 400 + +file_length: + - 500 + - 800 \ No newline at end of file diff --git a/ModuleKit/Widgets/BarChart.swift b/ModuleKit/Widgets/BarChart.swift index e99908e8..c7862d57 100644 --- a/ModuleKit/Widgets/BarChart.swift +++ b/ModuleKit/Widgets/BarChart.swift @@ -77,7 +77,7 @@ public class BarChart: WidgetWrapper { } if preview { - if self.value.count == 0 { + if self.value.isEmpty { self.value = [0.72, 0.38] } self.setFrameSize(NSSize(width: 36, height: self.frame.size.height)) @@ -89,6 +89,7 @@ public class BarChart: WidgetWrapper { fatalError("init(coder:) has not been implemented") } + // swiftlint:disable function_body_length public override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) @@ -100,28 +101,20 @@ public class BarChart: WidgetWrapper { switch self.value.count { case 0, 1: width += 10 + (offset*2) - break case 2: width += 22 - break case 3...4: // 3,4 width += 30 - break case 5...8: // 5,6,7,8 width += 40 - break case 9...12: // 9..12 width += 50 - break case 13...16: // 13..16 width += 76 - break case 17...32: // 17..32 width += 84 - break default: // > 32 width += 118 - break } if self.labelState { @@ -144,7 +137,7 @@ public class BarChart: WidgetWrapper { yMargin += letterHeight } - width = width + letterWidth + Constants.Widget.spacing + width += letterWidth + Constants.Widget.spacing x = letterWidth + Constants.Widget.spacing } @@ -248,32 +241,32 @@ public class BarChart: WidgetWrapper { height: height )) - view.addSubview(ToggleTitleRow( + view.addSubview(toggleTitleRow( frame: NSRect(x: 0, y: (rowHeight + Constants.Settings.margin) * 3, width: view.frame.width, height: rowHeight), - title: LocalizedString("Label"), + title: localizedString("Label"), action: #selector(toggleLabel), state: self.labelState )) - self.boxSettingsView = ToggleTitleRow( + self.boxSettingsView = toggleTitleRow( frame: NSRect(x: 0, y: (rowHeight + Constants.Settings.margin) * 2, width: view.frame.width, height: rowHeight), - title: LocalizedString("Box"), + title: localizedString("Box"), action: #selector(toggleBox), state: self.boxState ) view.addSubview(self.boxSettingsView!) - self.frameSettingsView = ToggleTitleRow( + self.frameSettingsView = toggleTitleRow( frame: NSRect(x: 0, y: (rowHeight + Constants.Settings.margin) * 1, width: view.frame.width, height: rowHeight), - title: LocalizedString("Frame"), + title: localizedString("Frame"), action: #selector(toggleFrame), state: self.frameState ) view.addSubview(self.frameSettingsView!) - view.addSubview(SelectRow( + view.addSubview(selectRow( frame: NSRect(x: 0, y: (rowHeight + Constants.Settings.margin) * 0, width: view.frame.width, height: rowHeight), - title: LocalizedString("Color"), + title: localizedString("Color"), action: #selector(toggleColor), items: self.colors, selected: self.colorState.key @@ -305,7 +298,7 @@ public class BarChart: WidgetWrapper { Store.shared.set(key: "\(self.title)_\(self.type.rawValue)_box", value: self.boxState) if self.frameState { - FindAndToggleNSControlState(self.frameSettingsView, state: .off) + findAndToggleNSControlState(self.frameSettingsView, state: .off) self.frameState = false Store.shared.set(key: "\(self.title)_\(self.type.rawValue)_frame", value: self.frameState) } @@ -324,7 +317,7 @@ public class BarChart: WidgetWrapper { Store.shared.set(key: "\(self.title)_\(self.type.rawValue)_frame", value: self.frameState) if self.boxState { - FindAndToggleNSControlState(self.boxSettingsView, state: .off) + findAndToggleNSControlState(self.boxSettingsView, state: .off) self.boxState = false Store.shared.set(key: "\(self.title)_\(self.type.rawValue)_box", value: self.boxState) } diff --git a/ModuleKit/Widgets/Battery.swift b/ModuleKit/Widgets/Battery.swift index 150dd982..c069d7de 100644 --- a/ModuleKit/Widgets/Battery.swift +++ b/ModuleKit/Widgets/Battery.swift @@ -56,6 +56,7 @@ public class BatterykWidget: WidgetWrapper { fatalError("init(coder:) has not been implemented") } + // swiftlint:disable function_body_length public override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) @@ -169,7 +170,7 @@ public class BatterykWidget: WidgetWrapper { CGPoint(x: batteryCenter.x+1, y: batteryCenter.y+1.5), CGPoint(x: batteryCenter.x+3, y: max.y), // top CGPoint(x: min.x, y: batteryCenter.y-1.5), - CGPoint(x: batteryCenter.x-1, y: batteryCenter.y-1.5), + CGPoint(x: batteryCenter.x-1, y: batteryCenter.y-1.5) ] } else { let iconSize: CGSize = CGSize(width: 9, height: batterySize.height + 2) @@ -201,7 +202,7 @@ public class BatterykWidget: WidgetWrapper { CGPoint(x: batteryCenter.x-4, y: batteryCenter.y + 0.5), CGPoint(x: batteryCenter.x-1.5, y: batteryCenter.y - 2.5), - CGPoint(x: batteryCenter.x-1.5, y: minY+0.5), + CGPoint(x: batteryCenter.x-1.5, y: minY+0.5) ] } @@ -312,24 +313,24 @@ public class BatterykWidget: WidgetWrapper { height: height )) - view.addSubview(SelectRow( + view.addSubview(selectRow( frame: NSRect(x: 0, y: (rowHeight + Constants.Settings.margin) * 2, width: view.frame.width, height: rowHeight), - title: LocalizedString("Additional information"), + title: localizedString("Additional information"), action: #selector(toggleAdditional), items: BatteryAdditionals, selected: self.additional )) - view.addSubview(ToggleTitleRow( + view.addSubview(toggleTitleRow( frame: NSRect(x: 0, y: (rowHeight + Constants.Settings.margin) * 1, width: view.frame.width, height: rowHeight), - title: LocalizedString("Hide additional information when full"), + title: localizedString("Hide additional information when full"), action: #selector(toggleHideAdditionalWhenFull), state: self.hideAdditionalWhenFull )) - view.addSubview(ToggleTitleRow( + view.addSubview(toggleTitleRow( frame: NSRect(x: 0, y: (rowHeight + Constants.Settings.margin) * 0, width: view.frame.width, height: rowHeight), - title: LocalizedString("Colorize"), + title: localizedString("Colorize"), action: #selector(toggleColor), state: self.colorState )) diff --git a/ModuleKit/Widgets/LineChart.swift b/ModuleKit/Widgets/LineChart.swift index 54db5819..5ef72fba 100644 --- a/ModuleKit/Widgets/LineChart.swift +++ b/ModuleKit/Widgets/LineChart.swift @@ -96,6 +96,7 @@ public class LineChart: WidgetWrapper { fatalError("init(coder:) has not been implemented") } + // swiftlint:disable function_body_length public override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) @@ -140,7 +141,7 @@ public class LineChart: WidgetWrapper { str.draw(with: rect) yMargin += letterHeight } - width = width + letterWidth + Constants.Widget.spacing + width += letterWidth + Constants.Widget.spacing x = letterWidth + Constants.Widget.spacing } @@ -208,10 +209,10 @@ public class LineChart: WidgetWrapper { } public override func setValues(_ values: [value_t]) { - let historyValues = values.map{ $0.widget_value }.suffix(60) + let historyValues = values.map{ $0.widgetValue }.suffix(60) let end = self.chart.points.count - if historyValues.count != 0 { + if !historyValues.isEmpty { self.chart.points.replaceSubrange(end-historyValues.count...end-1, with: historyValues) } @@ -255,47 +256,47 @@ public class LineChart: WidgetWrapper { height: height )) - view.addSubview(ToggleTitleRow( + view.addSubview(toggleTitleRow( frame: NSRect(x: 0, y: (rowHeight + Constants.Settings.margin) * 5, width: view.frame.width, height: rowHeight), - title: LocalizedString("Label"), + title: localizedString("Label"), action: #selector(toggleLabel), state: self.labelState )) - view.addSubview(ToggleTitleRow( + view.addSubview(toggleTitleRow( frame: NSRect(x: 0, y: (rowHeight + Constants.Settings.margin) * 4, width: view.frame.width, height: rowHeight), - title: LocalizedString("Value"), + title: localizedString("Value"), action: #selector(toggleValue), state: self.valueState )) - self.boxSettingsView = ToggleTitleRow( + self.boxSettingsView = toggleTitleRow( frame: NSRect(x: 0, y: (rowHeight + Constants.Settings.margin) * 3, width: view.frame.width, height: rowHeight), - title: LocalizedString("Box"), + title: localizedString("Box"), action: #selector(toggleBox), state: self.boxState ) view.addSubview(self.boxSettingsView!) - self.frameSettingsView = ToggleTitleRow( + self.frameSettingsView = toggleTitleRow( frame: NSRect(x: 0, y: (rowHeight + Constants.Settings.margin) * 2, width: view.frame.width, height: rowHeight), - title: LocalizedString("Frame"), + title: localizedString("Frame"), action: #selector(toggleFrame), state: self.frameState ) view.addSubview(self.frameSettingsView!) - view.addSubview(SelectRow( + view.addSubview(selectRow( frame: NSRect(x: 0, y: (rowHeight + Constants.Settings.margin) * 1, width: view.frame.width, height: rowHeight), - title: LocalizedString("Color"), + title: localizedString("Color"), action: #selector(toggleColor), items: self.colors, selected: self.colorState.key )) - view.addSubview(ToggleTitleRow( + view.addSubview(toggleTitleRow( frame: NSRect(x: 0, y: (rowHeight + Constants.Settings.margin) * 0, width: view.frame.width, height: rowHeight), - title: LocalizedString("Colorize value"), + title: localizedString("Colorize value"), action: #selector(toggleValueColor), state: self.valueColorState )) @@ -326,7 +327,7 @@ public class LineChart: WidgetWrapper { Store.shared.set(key: "\(self.title)_\(self.type.rawValue)_box", value: self.boxState) if self.frameState { - FindAndToggleNSControlState(self.frameSettingsView, state: .off) + findAndToggleNSControlState(self.frameSettingsView, state: .off) self.frameState = false Store.shared.set(key: "\(self.title)_\(self.type.rawValue)_frame", value: self.frameState) } @@ -345,7 +346,7 @@ public class LineChart: WidgetWrapper { Store.shared.set(key: "\(self.title)_\(self.type.rawValue)_frame", value: self.frameState) if self.boxState { - FindAndToggleNSControlState(self.boxSettingsView, state: .off) + findAndToggleNSControlState(self.boxSettingsView, state: .off) self.boxState = false Store.shared.set(key: "\(self.title)_\(self.type.rawValue)_box", value: self.boxState) } diff --git a/ModuleKit/Widgets/Memory.swift b/ModuleKit/Widgets/Memory.swift index 0bb5b605..22a86b2e 100644 --- a/ModuleKit/Widgets/Memory.swift +++ b/ModuleKit/Widgets/Memory.swift @@ -110,9 +110,9 @@ public class MemoryWidget: WidgetWrapper { height: height )) - view.addSubview(ToggleTitleRow( + view.addSubview(toggleTitleRow( frame: NSRect(x: 0, y: (rowHeight + Constants.Settings.margin) * 0, width: view.frame.width, height: rowHeight), - title: LocalizedString("Reverse values order"), + title: localizedString("Reverse values order"), action: #selector(toggleOrder), state: self.orderReversedState )) diff --git a/ModuleKit/Widgets/Mini.swift b/ModuleKit/Widgets/Mini.swift index 741764d1..76618ec2 100644 --- a/ModuleKit/Widgets/Mini.swift +++ b/ModuleKit/Widgets/Mini.swift @@ -177,16 +177,16 @@ public class Mini: WidgetWrapper { height: height )) - view.addSubview(ToggleTitleRow( + view.addSubview(toggleTitleRow( frame: NSRect(x: 0, y: rowHeight + Constants.Settings.margin, width: view.frame.width, height: rowHeight), - title: LocalizedString("Label"), + title: localizedString("Label"), action: #selector(toggleLabel), state: self.labelState )) - view.addSubview(SelectRow( + view.addSubview(selectRow( frame: NSRect(x: 0, y: (rowHeight + Constants.Settings.margin) * 0, width: view.frame.width, height: rowHeight), - title: LocalizedString("Color"), + title: localizedString("Color"), action: #selector(toggleColor), items: self.colors, selected: self.colorState.key diff --git a/ModuleKit/Widgets/NetworkChart.swift b/ModuleKit/Widgets/NetworkChart.swift index fd0544d9..8d4946f3 100644 --- a/ModuleKit/Widgets/NetworkChart.swift +++ b/ModuleKit/Widgets/NetworkChart.swift @@ -128,17 +128,17 @@ public class NetworkChart: WidgetWrapper { height: height )) - self.boxSettingsView = ToggleTitleRow( + self.boxSettingsView = toggleTitleRow( frame: NSRect(x: 0, y: (rowHeight + Constants.Settings.margin) * 1, width: view.frame.width, height: rowHeight), - title: LocalizedString("Box"), + title: localizedString("Box"), action: #selector(toggleBox), state: self.boxState ) view.addSubview(self.boxSettingsView!) - self.frameSettingsView = ToggleTitleRow( + self.frameSettingsView = toggleTitleRow( frame: NSRect(x: 0, y: (rowHeight + Constants.Settings.margin) * 0, width: view.frame.width, height: rowHeight), - title: LocalizedString("Frame"), + title: localizedString("Frame"), action: #selector(toggleFrame), state: self.frameState ) @@ -158,7 +158,7 @@ public class NetworkChart: WidgetWrapper { Store.shared.set(key: "\(self.title)_\(self.type.rawValue)_box", value: self.boxState) if self.frameState { - FindAndToggleNSControlState(self.frameSettingsView, state: .off) + findAndToggleNSControlState(self.frameSettingsView, state: .off) self.frameState = false Store.shared.set(key: "\(self.title)_\(self.type.rawValue)_frame", value: self.frameState) } @@ -177,7 +177,7 @@ public class NetworkChart: WidgetWrapper { Store.shared.set(key: "\(self.title)_\(self.type.rawValue)_frame", value: self.frameState) if self.boxState { - FindAndToggleNSControlState(self.boxSettingsView, state: .off) + findAndToggleNSControlState(self.boxSettingsView, state: .off) self.boxState = false Store.shared.set(key: "\(self.title)_\(self.type.rawValue)_box", value: self.boxState) } diff --git a/ModuleKit/Widgets/PieChart.swift b/ModuleKit/Widgets/PieChart.swift index 99647b6b..193cc1e7 100644 --- a/ModuleKit/Widgets/PieChart.swift +++ b/ModuleKit/Widgets/PieChart.swift @@ -105,9 +105,9 @@ public class PieChart: WidgetWrapper { height: height )) - view.addSubview(ToggleTitleRow( + view.addSubview(toggleTitleRow( frame: NSRect(x: 0, y: 0, width: view.frame.width, height: rowHeight), - title: LocalizedString("Label"), + title: localizedString("Label"), action: #selector(toggleLabel), state: self.labelState )) diff --git a/ModuleKit/Widgets/Sensors.swift b/ModuleKit/Widgets/Sensors.swift index 1655b3a0..0e0951af 100644 --- a/ModuleKit/Widgets/Sensors.swift +++ b/ModuleKit/Widgets/Sensors.swift @@ -63,7 +63,7 @@ public class SensorsWidget: WidgetWrapper { public override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) - guard self.values.count != 0 else { + guard !self.values.isEmpty else { self.setWidth(1) return } @@ -186,17 +186,17 @@ public class SensorsWidget: WidgetWrapper { public override func settings(width: CGFloat) -> NSView { let view = SettingsContainerView(width: width) - view.addArrangedSubview(SelectRow( + view.addArrangedSubview(selectRow( frame: NSRect(x: 0, y: 0, width: view.frame.width, height: Constants.Settings.row), - title: LocalizedString("Display mode"), + title: localizedString("Display mode"), action: #selector(changeMode), items: SensorsWidgetMode, selected: self.modeState )) - view.addArrangedSubview(ToggleTitleRow( + view.addArrangedSubview(toggleTitleRow( frame: NSRect(x: 0, y: 0, width: view.frame.width, height: Constants.Settings.row), - title: LocalizedString("Static width"), + title: localizedString("Static width"), action: #selector(toggleSize), state: self.fixedSizeState )) diff --git a/ModuleKit/Widgets/Speed.swift b/ModuleKit/Widgets/Speed.swift index 7edd3d0a..49cd7282 100644 --- a/ModuleKit/Widgets/Speed.swift +++ b/ModuleKit/Widgets/Speed.swift @@ -84,7 +84,6 @@ public class SpeedWidget: WidgetWrapper { default: x = 0 width = 0 - break } if self.valueState { @@ -197,7 +196,7 @@ public class SpeedWidget: WidgetWrapper { str.draw(with: rect) } - if self.symbols.count > 0 { + if !self.symbols.isEmpty { let uploadAttributes = [ NSAttributedString.Key.font: NSFont.systemFont(ofSize: 9, weight: .regular), NSAttributedString.Key.foregroundColor: uploadValue >= 1_024 ? NSColor.red : NSColor.textColor, @@ -220,25 +219,25 @@ public class SpeedWidget: WidgetWrapper { height: height )) - view.addSubview(SelectRow( + view.addSubview(selectRow( frame: NSRect(x: 0, y: (rowHeight+Constants.Settings.margin) * 2, width: view.frame.width, height: rowHeight), - title: LocalizedString("Pictogram"), + title: localizedString("Pictogram"), action: #selector(toggleIcon), items: SpeedPictogram, selected: self.icon )) - view.addSubview(SelectRow( + view.addSubview(selectRow( frame: NSRect(x: 0, y: rowHeight + Constants.Settings.margin, width: view.frame.width, height: rowHeight), - title: LocalizedString("Base"), + title: localizedString("Base"), action: #selector(toggleBase), items: SpeedBase, selected: self.baseValue )) - view.addSubview(ToggleTitleRow( + view.addSubview(toggleTitleRow( frame: NSRect(x: 0, y: 0, width: view.frame.width, height: rowHeight), - title: LocalizedString("Value"), + title: localizedString("Value"), action: #selector(toggleValue), state: self.valueState )) diff --git a/ModuleKit/module.swift b/ModuleKit/module.swift index 82e6da1d..2e07ac9f 100644 --- a/ModuleKit/module.swift +++ b/ModuleKit/module.swift @@ -24,7 +24,7 @@ public protocol Module_p { public struct module_c { public var name: String = "" - public var icon: NSImage? = nil + public var icon: NSImage? var defaultState: Bool = false var defaultWidget: widget_t = .unknown @@ -43,7 +43,7 @@ public struct module_c { } if let widgetsDict = dict["Widgets"] as? NSDictionary { - var list: [String : Int] = [:] + var list: [String: Int] = [:] self.widgetsConfig = widgetsDict for widgetName in widgetsDict.allKeys { @@ -107,6 +107,7 @@ open class Module: Module_p { NotificationCenter.default.addObserver(self, selector: #selector(listenForPopupToggle), name: .togglePopup, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(listenForToggleWidget), name: .toggleWidget, object: nil) + // swiftlint:disable empty_count if self.config.widgetsConfig.count != 0 { self.initWidgets() } else { @@ -303,12 +304,12 @@ open class Module: Module_p { guard let name = notification.userInfo?["module"] as? String, name == self.config.name else { return } - let count = self.widgets.filter({ $0.isActive }).count + let isEmpty = self.widgets.filter({ $0.isActive }).isEmpty var state = self.enabled - if count == 0 && self.enabled { + if isEmpty && self.enabled { state = false - } else if count != 0 && !self.enabled { + } else if !isEmpty && !self.enabled { state = true } diff --git a/ModuleKit/popup.swift b/ModuleKit/popup.swift index 64d44bb7..74e409fb 100644 --- a/ModuleKit/popup.swift +++ b/ModuleKit/popup.swift @@ -25,7 +25,12 @@ internal class PopupWindow: NSWindow, NSWindowDelegate { self.viewController.visibilityCallback = visibilityCallback super.init( - contentRect: NSMakeRect(0, 0, self.viewController.view.frame.width, self.viewController.view.frame.height), + contentRect: NSRect( + x: 0, + y: 0, + width: self.viewController.view.frame.width, + height: self.viewController.view.frame.height + ), styleMask: [.titled, .fullSizeContentView], backing: .buffered, defer: true @@ -240,7 +245,7 @@ internal class HeaderView: NSStackView { activity.isBordered = false activity.action = #selector(openActivityMonitor) activity.target = self - activity.toolTip = LocalizedString("Open Activity Monitor") + activity.toolTip = localizedString("Open Activity Monitor") activity.focusRingType = .none self.activityButton = activity @@ -268,7 +273,7 @@ internal class HeaderView: NSStackView { settings.isBordered = false settings.action = #selector(openSettings) settings.target = self - settings.toolTip = LocalizedString("Open module settings") + settings.toolTip = localizedString("Open module settings") settings.focusRingType = .none self.settingsButton = settings @@ -279,7 +284,7 @@ internal class HeaderView: NSStackView { NSLayoutConstraint.activate([ title.widthAnchor.constraint( equalToConstant: self.frame.width - activity.intrinsicContentSize.width - settings.intrinsicContentSize.width - ), + ) ]) } @@ -296,8 +301,8 @@ internal class HeaderView: NSStackView { NSColor.gridColor.set() let line = NSBezierPath() - line.move(to: NSMakePoint(0, 0)) - line.line(to: NSMakePoint(self.frame.width, 0)) + line.move(to: NSPoint(x: 0, y: 0)) + line.line(to: NSPoint(x: self.frame.width, y: 0)) line.lineWidth = 1 line.stroke() } @@ -326,11 +331,11 @@ internal class HeaderView: NSStackView { public func setCloseButton(_ state: Bool) { if state && !self.isCloseAction { self.activityButton?.image = Bundle(for: type(of: self)).image(forResource: "close")! - self.activityButton?.toolTip = LocalizedString("Close popup") + self.activityButton?.toolTip = localizedString("Close popup") self.isCloseAction = true } else if !state && self.isCloseAction { self.activityButton?.image = Bundle(for: type(of: self)).image(forResource: "chart")! - self.activityButton?.toolTip = LocalizedString("Open Activity Monitor") + self.activityButton?.toolTip = localizedString("Open Activity Monitor") self.isCloseAction = false } } diff --git a/ModuleKit/reader.swift b/ModuleKit/reader.swift index bf7930be..8ff0c120 100644 --- a/ModuleKit/reader.swift +++ b/ModuleKit/reader.swift @@ -15,36 +15,36 @@ import os.log import StatsKit public protocol value_t { - var widget_value: Double { get } + var widgetValue: Double { get } } public protocol Reader_p { var optional: Bool { get } var popup: Bool { get } - func setup() -> Void - func read() -> Void - func terminate() -> Void + func setup() + func read() + func terminate() func getValue() -> T func getHistory() -> [value_t] - func start() -> Void - func pause() -> Void - func stop() -> Void + func start() + func pause() + func stop() - func lock() -> Void - func unlock() -> Void + func lock() + func unlock() - func initStoreValues(title: String) -> Void - func setInterval(_ value: Int) -> Void + func initStoreValues(title: String) + func setInterval(_ value: Int) } public protocol ReaderInternal_p { associatedtype T var value: T? { get } - func read() -> Void + func read() } open class Reader: ReaderInternal_p { diff --git a/ModuleKit/settings.swift b/ModuleKit/settings.swift index fb0cd5c1..70af7c40 100644 --- a/ModuleKit/settings.swift +++ b/ModuleKit/settings.swift @@ -13,7 +13,7 @@ import Cocoa import StatsKit public protocol Settings_p: NSView { - var toggleCallback: () -> () { get set } + var toggleCallback: () -> Void { get set } } public protocol Settings_v: NSView { @@ -22,7 +22,7 @@ public protocol Settings_v: NSView { } open class Settings: NSView, Settings_p { - public var toggleCallback: () -> () = {} + public var toggleCallback: () -> Void = {} private let headerHeight: CGFloat = 42 @@ -177,7 +177,7 @@ open class Settings: NSView, Settings_p { NSLayoutConstraint.activate([ container.heightAnchor.constraint(equalToConstant: container.frame.height), - view.heightAnchor.constraint(equalTo: container.heightAnchor), + view.heightAnchor.constraint(equalTo: container.heightAnchor) ]) } @@ -200,7 +200,7 @@ open class Settings: NSView, Settings_p { } NSLayoutConstraint.activate([ - container.heightAnchor.constraint(equalTo: settingsView.heightAnchor), + container.heightAnchor.constraint(equalTo: settingsView.heightAnchor) ]) } @@ -235,7 +235,7 @@ open class Settings: NSView, Settings_p { } NSLayoutConstraint.activate([ - container.heightAnchor.constraint(equalTo: settingsView.heightAnchor), + container.heightAnchor.constraint(equalTo: settingsView.heightAnchor) ]) } @@ -247,7 +247,7 @@ open class Settings: NSView, Settings_p { if let name = notification.userInfo?["module"] as? String { if name == self.config.pointee.name { if let state = notification.userInfo?["state"] as? Bool { - ToggleNSControlState(self.enableControl, state: state ? .on : .off) + toggleNSControlState(self.enableControl, state: state ? .on : .off) } } } @@ -263,7 +263,7 @@ open class Settings: NSView, Settings_p { self.moduleSettingsContainer?.addSubview(settingsView) NSLayoutConstraint.activate([ - container.heightAnchor.constraint(equalTo: settingsView.heightAnchor), + container.heightAnchor.constraint(equalTo: settingsView.heightAnchor) ]) } } @@ -302,7 +302,7 @@ internal class WidgetPreview: NSStackView { self.layer?.cornerRadius = 2 self.layer?.borderColor = self.widget.pointee.isActive ? NSColor.systemBlue.cgColor : NSColor(hexString: "#dddddd").cgColor self.layer?.borderWidth = 1 - self.toolTip = LocalizedString("Select widget", widget.pointee.type.name()) + self.toolTip = localizedString("Select widget", widget.pointee.type.name()) self.orientation = .horizontal self.distribution = .fillProportionally @@ -337,7 +337,12 @@ internal class WidgetPreview: NSStackView { }) let rect = NSRect(x: Constants.Widget.spacing, y: 0, width: value, height: self!.frame.height) - let trackingArea = NSTrackingArea(rect: rect, options: [NSTrackingArea.Options.activeAlways, NSTrackingArea.Options.mouseEnteredAndExited, NSTrackingArea.Options.activeInActiveApp], owner: self, userInfo: nil) + let trackingArea = NSTrackingArea( + rect: rect, + options: [NSTrackingArea.Options.activeAlways, NSTrackingArea.Options.mouseEnteredAndExited, NSTrackingArea.Options.activeInActiveApp], + owner: self, + userInfo: nil + ) self?.addTrackingArea(trackingArea) } @@ -350,7 +355,7 @@ internal class WidgetPreview: NSStackView { )) NSLayoutConstraint.activate([ - self.heightAnchor.constraint(equalToConstant: self.frame.height), + self.heightAnchor.constraint(equalToConstant: self.frame.height) ]) self.widthConstant = self.widthAnchor.constraint(equalTo: self.widget.pointee.preview.widthAnchor, constant: self.size) @@ -360,8 +365,8 @@ internal class WidgetPreview: NSStackView { private func initButton() -> NSView { let size: CGFloat = Constants.Widget.height let button = NSButton(frame: NSRect(x: 0, y: 0, width: size, height: size)) - button.title = LocalizedString("Open widget settings") - button.toolTip = LocalizedString("Open widget settings") + button.title = localizedString("Open widget settings") + button.toolTip = localizedString("Open widget settings") button.bezelStyle = .regularSquare if let image = Bundle(for: type(of: self)).image(forResource: "widget_settings") { button.image = image @@ -374,7 +379,7 @@ internal class WidgetPreview: NSStackView { button.focusRingType = .none NSLayoutConstraint.activate([ - button.widthAnchor.constraint(equalToConstant: button.frame.width), + button.widthAnchor.constraint(equalToConstant: button.frame.width) ]) return button @@ -387,7 +392,7 @@ internal class WidgetPreview: NSStackView { separator.layer?.backgroundColor = NSColor(hexString: "#dddddd").cgColor NSLayoutConstraint.activate([ - separator.heightAnchor.constraint(equalToConstant: Constants.Widget.height), + separator.heightAnchor.constraint(equalToConstant: Constants.Widget.height) ]) return separator diff --git a/ModuleKit/widget.swift b/ModuleKit/widget.swift index 47673025..17c2ac51 100644 --- a/ModuleKit/widget.swift +++ b/ModuleKit/widget.swift @@ -37,43 +37,33 @@ public enum widget_t: String { case .mini: preview = Mini(title: module, config: widgetConfig, preview: true) item = Mini(title: module, config: widgetConfig, preview: false) - break case .lineChart: preview = LineChart(title: module, config: widgetConfig, preview: true) item = LineChart(title: module, config: widgetConfig, preview: false) - break case .barChart: preview = BarChart(title: module, config: widgetConfig, preview: true) item = BarChart(title: module, config: widgetConfig, preview: false) - break case .pieChart: preview = PieChart(title: module, config: widgetConfig, preview: true) item = PieChart(title: module, config: widgetConfig, preview: false) - break case .networkChart: preview = NetworkChart(title: module, config: widgetConfig, preview: true) item = NetworkChart(title: module, config: widgetConfig, preview: false) - break case .speed: preview = SpeedWidget(title: module, config: widgetConfig, preview: true) item = SpeedWidget(title: module, config: widgetConfig, preview: false) - break case .battery: preview = BatterykWidget(title: module, config: widgetConfig, preview: true) item = BatterykWidget(title: module, config: widgetConfig, preview: false) - break case .sensors: preview = SensorsWidget(title: module, config: widgetConfig, preview: true) item = SensorsWidget(title: module, config: widgetConfig, preview: false) - break case .memory: preview = MemoryWidget(title: module, config: widgetConfig, preview: true) item = MemoryWidget(title: module, config: widgetConfig, preview: false) - break case .label: preview = Label(title: module, config: widgetConfig, preview: true) item = Label(title: module, config: widgetConfig, preview: false) - break default: break } @@ -86,17 +76,17 @@ public enum widget_t: String { public func name() -> String { switch self { - case .mini: return LocalizedString("Mini widget") - case .lineChart: return LocalizedString("Line chart widget") - case .barChart: return LocalizedString("Bar chart widget") - case .pieChart: return LocalizedString("Pie chart widget") - case .networkChart: return LocalizedString("Network chart widget") - case .speed: return LocalizedString("Speed widget") - case .battery: return LocalizedString("Battery widget") - case .sensors: return LocalizedString("Text widget") - case .memory: return LocalizedString("Memory widget") - case .label: return LocalizedString("Label widget") - default: return "" + case .mini: return localizedString("Mini widget") + case .lineChart: return localizedString("Line chart widget") + case .barChart: return localizedString("Bar chart widget") + case .pieChart: return localizedString("Pie chart widget") + case .networkChart: return localizedString("Network chart widget") + case .speed: return localizedString("Speed widget") + case .battery: return localizedString("Battery widget") + case .sensors: return localizedString("Text widget") + case .memory: return localizedString("Memory widget") + case .label: return localizedString("Label widget") + default: return "" } } } @@ -247,7 +237,7 @@ public class Widget { NotificationCenter.default.post(name: .togglePopup, object: nil, userInfo: [ "module": self.module, "origin": window.frame.origin, - "center": window.frame.width/2, + "center": window.frame.width/2 ]) } } diff --git a/Modules/Battery/main.swift b/Modules/Battery/main.swift index 8d3b3389..4b61cd6e 100644 --- a/Modules/Battery/main.swift +++ b/Modules/Battery/main.swift @@ -33,7 +33,7 @@ struct Battery_Usage: value_t { var timeToCharge: Int = 0 var timeOnACPower: Date? = nil - public var widget_value: Double { + public var widgetValue: Double { get { return self.level } @@ -98,7 +98,7 @@ public class Battery: Module { public override func isAvailable() -> Bool { let snapshot = IOPSCopyPowerSourcesInfo().takeRetainedValue() let sources = IOPSCopyPowerSourcesList(snapshot).takeRetainedValue() as Array - return sources.count > 0 + return !sources.isEmpty } private func usageCallback(_ raw: Battery_Usage?) { @@ -149,13 +149,13 @@ public class Battery: Module { } if value.level <= notificationLevel && self.lowNotification == nil { - var subtitle = LocalizedString("Battery remaining", "\(Int(value.level*100))") + var subtitle = localizedString("Battery remaining", "\(Int(value.level*100))") if value.timeToEmpty > 0 { subtitle += " (\(Double(value.timeToEmpty*60).printSecondsToHoursMinutesSeconds()))" } self.lowNotification = showNotification( - title: LocalizedString("Low battery"), + title: localizedString("Low battery"), subtitle: subtitle, id: "battery-level", icon: NSImage(named: NSImage.Name("low-battery"))! @@ -186,13 +186,13 @@ public class Battery: Module { } if value.level >= notificationLevel && self.highNotification == nil { - var subtitle = LocalizedString("Battery remaining to full charge", "\(Int((1-value.level)*100))") + var subtitle = localizedString("Battery remaining to full charge", "\(Int((1-value.level)*100))") if value.timeToCharge > 0 { subtitle += " (\(Double(value.timeToCharge*60).printSecondsToHoursMinutesSeconds()))" } self.highNotification = showNotification( - title: LocalizedString("High battery"), + title: localizedString("High battery"), subtitle: subtitle, id: "battery-level2", icon: NSImage(named: NSImage.Name("high-battery"))! diff --git a/Modules/Battery/popup.swift b/Modules/Battery/popup.swift index 02a8758b..d8f3d6c9 100644 --- a/Modules/Battery/popup.swift +++ b/Modules/Battery/popup.swift @@ -129,7 +129,12 @@ internal class Popup: NSView, Popup_p { let view: NSView = NSView(frame: NSRect(x: 0, y: self.frame.height - self.dashboardHeight, width: self.frame.width, height: self.dashboardHeight)) let container: NSView = NSView(frame: NSRect(x: 0, y: 0, width: view.frame.width, height: self.dashboardHeight)) - self.dashboardBatteryView = BatteryView(frame: NSRect(x: Constants.Popup.margins, y: Constants.Popup.margins, width: view.frame.width - (Constants.Popup.margins*2), height: view.frame.height - (Constants.Popup.margins*2))) + self.dashboardBatteryView = BatteryView(frame: NSRect( + x: Constants.Popup.margins, + y: Constants.Popup.margins, + width: view.frame.width - (Constants.Popup.margins*2), + height: view.frame.height - (Constants.Popup.margins*2) + )) container.addSubview(self.dashboardBatteryView!) view.addSubview(container) @@ -139,17 +144,17 @@ internal class Popup: NSView, Popup_p { private func initDetails() -> NSView { let view: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: self.detailsHeight)) - let separator = SeparatorView(LocalizedString("Details"), origin: NSPoint(x: 0, y: self.detailsHeight-Constants.Popup.separatorHeight), width: self.frame.width) + let separator = separatorView(localizedString("Details"), origin: NSPoint(x: 0, y: self.detailsHeight-Constants.Popup.separatorHeight), width: self.frame.width) let container: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: separator.frame.origin.y)) - self.levelField = PopupRow(container, n: 5, title: "\(LocalizedString("Level")):", value: "").1 - self.sourceField = PopupRow(container, n: 4, title: "\(LocalizedString("Source")):", value: "").1 - let t = self.labelValue(container, n: 3, title: "\(LocalizedString("Time")):", value: "") + self.levelField = popupRow(container, n: 5, title: "\(localizedString("Level")):", value: "").1 + self.sourceField = popupRow(container, n: 4, title: "\(localizedString("Source")):", value: "").1 + let t = self.labelValue(container, n: 3, title: "\(localizedString("Time")):", value: "") self.timeLabelField = t.0 self.timeField = t.1 - self.healthField = PopupRow(container, n: 2, title: "\(LocalizedString("Health")):", value: "").1 - self.cyclesField = PopupRow(container, n: 1, title: "\(LocalizedString("Cycles")):", value: "").1 - self.lastChargeField = PopupRow(container, n: 0, title: "\(LocalizedString("Last charge")):", value: "").1 + self.healthField = popupRow(container, n: 2, title: "\(localizedString("Health")):", value: "").1 + self.cyclesField = popupRow(container, n: 1, title: "\(localizedString("Cycles")):", value: "").1 + self.lastChargeField = popupRow(container, n: 0, title: "\(localizedString("Last charge")):", value: "").1 view.addSubview(separator) view.addSubview(container) @@ -159,13 +164,13 @@ internal class Popup: NSView, Popup_p { private func initBattery() -> NSView { let view: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: self.batteryHeight)) - let separator = SeparatorView(LocalizedString("Battery"), origin: NSPoint(x: 0, y: self.batteryHeight-Constants.Popup.separatorHeight), width: self.frame.width) + let separator = separatorView(localizedString("Battery"), origin: NSPoint(x: 0, y: self.batteryHeight-Constants.Popup.separatorHeight), width: self.frame.width) let container: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: separator.frame.origin.y)) - self.amperageField = PopupRow(container, n: 3, title: "\(LocalizedString("Amperage")):", value: "").1 - self.voltageField = PopupRow(container, n: 2, title: "\(LocalizedString("Voltage")):", value: "").1 - self.batteryPowerField = PopupRow(container, n: 1, title: "\(LocalizedString("Power")):", value: "").1 - self.temperatureField = PopupRow(container, n: 0, title: "\(LocalizedString("Temperature")):", value: "").1 + self.amperageField = popupRow(container, n: 3, title: "\(localizedString("Amperage")):", value: "").1 + self.voltageField = popupRow(container, n: 2, title: "\(localizedString("Voltage")):", value: "").1 + self.batteryPowerField = popupRow(container, n: 1, title: "\(localizedString("Power")):", value: "").1 + self.temperatureField = popupRow(container, n: 0, title: "\(localizedString("Temperature")):", value: "").1 view.addSubview(separator) view.addSubview(container) @@ -175,11 +180,11 @@ internal class Popup: NSView, Popup_p { private func initAdapter() -> NSView { let view: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: self.adapterHeight)) - let separator = SeparatorView(LocalizedString("Power adapter"), origin: NSPoint(x: 0, y: self.adapterHeight-Constants.Popup.separatorHeight), width: self.frame.width) + let separator = separatorView(localizedString("Power adapter"), origin: NSPoint(x: 0, y: self.adapterHeight-Constants.Popup.separatorHeight), width: self.frame.width) let container: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: separator.frame.origin.y)) - self.powerField = PopupRow(container, n: 1, title: "\(LocalizedString("Power")):", value: "").1 - self.chargingStateField = PopupRow(container, n: 0, title: "\(LocalizedString("Is charging")):", value: "").1 + self.powerField = popupRow(container, n: 1, title: "\(localizedString("Power")):", value: "").1 + self.chargingStateField = popupRow(container, n: 0, title: "\(localizedString("Is charging")):", value: "").1 self.adapterView = view @@ -191,7 +196,7 @@ internal class Popup: NSView, Popup_p { private func initProcesses() -> NSView { let view: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: self.processesHeight)) - let separator = SeparatorView(LocalizedString("Top processes"), origin: NSPoint(x: 0, y: self.processesHeight-Constants.Popup.separatorHeight), width: self.frame.width) + let separator = separatorView(localizedString("Top processes"), origin: NSPoint(x: 0, y: self.processesHeight-Constants.Popup.separatorHeight), width: self.frame.width) let container: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: separator.frame.origin.y)) for i in 0.. { let psInfo = IOPSCopyPowerSourcesInfo().takeRetainedValue() let psList = IOPSCopyPowerSourcesList(psInfo).takeRetainedValue() as [CFTypeRef] - if psList.count == 0 { + if psList.isEmpty { return } for ps in psList { - if let list = IOPSGetPowerSourceDescription(psInfo, ps).takeUnretainedValue() as? Dictionary { + if let list = IOPSGetPowerSourceDescription(psInfo, ps).takeUnretainedValue() as? [String: Any] { self.usage.powerSource = list[kIOPSPowerSourceStateKey] as? String ?? "AC Power" self.usage.isCharged = list[kIOPSIsChargedKey] as? Bool ?? false self.usage.isCharging = self.getBoolValue("IsCharging" as CFString) ?? false @@ -95,7 +95,7 @@ internal class UsageReader: Reader { var ACwatts: Int = 0 if let ACDetails = IOPSCopyExternalPowerAdapterDetails() { - if let ACList = ACDetails.takeRetainedValue() as? Dictionary { + if let ACList = ACDetails.takeRetainedValue() as? [String: Any] { guard let watts = ACList[kIOPSPowerAdapterWattsKey] else { return } @@ -171,7 +171,7 @@ public class ProcessReader: Reader<[TopProcess]> { let output = String(decoding: fileHandle.availableData, as: UTF8.self) var processes: [TopProcess] = [] - output.enumerateLines { (line, _) -> () in + output.enumerateLines { (line, _) -> Void in if line.matches("^\\d* +.+ \\d*.?\\d*$") { var str = line.trimmingCharacters(in: .whitespaces) @@ -195,7 +195,7 @@ public class ProcessReader: Reader<[TopProcess]> { } } - if processes.count != 0 { + if !processes.isEmpty { self.callback(processes.prefix(self.numberOfProcesses).reversed().reversed()) } } diff --git a/Modules/Battery/settings.swift b/Modules/Battery/settings.swift index 2956465e..c4bbf940 100644 --- a/Modules/Battery/settings.swift +++ b/Modules/Battery/settings.swift @@ -76,54 +76,54 @@ internal class Settings: NSView, Settings_v { return v } - self.addSubview(SelectTitleRow( + self.addSubview(selectTitleRow( frame: NSRect( x: Constants.Settings.margin, y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * (num-1), width: self.frame.width - (Constants.Settings.margin*2), height: rowHeight ), - title: LocalizedString("Low level notification"), + title: localizedString("Low level notification"), action: #selector(changeUpdateIntervalLow), items: lowLevels, selected: self.lowLevelNotification == "Disabled" ? self.lowLevelNotification : "\(Int((Double(self.lowLevelNotification) ?? 0)*100))%" )) - self.addSubview(SelectTitleRow( + self.addSubview(selectTitleRow( frame: NSRect( x: Constants.Settings.margin, y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * (num-2), width: self.frame.width - (Constants.Settings.margin*2), height: rowHeight ), - title: LocalizedString("High level notification"), + title: localizedString("High level notification"), action: #selector(changeUpdateIntervalHigh), items: highLevels, selected: self.highLevelNotification == "Disabled" ? self.highLevelNotification : "\(Int((Double(self.highLevelNotification) ?? 0)*100))%" )) - self.addSubview(SelectTitleRow( + self.addSubview(selectTitleRow( frame: NSRect( x: Constants.Settings.margin, y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * (num-3), width: self.frame.width - (Constants.Settings.margin*2), height: rowHeight ), - title: LocalizedString("Number of top processes"), + title: localizedString("Number of top processes"), action: #selector(changeNumberOfProcesses), items: NumbersOfProcesses.map{ "\($0)" }, selected: "\(self.numberOfProcesses)" )) if !widgets.filter({ $0 == .battery }).isEmpty { - self.addSubview(SelectRow( + self.addSubview(selectRow( frame: NSRect( x: Constants.Settings.margin, y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * 0, width: self.frame.width - (Constants.Settings.margin*2), height: rowHeight ), - title: LocalizedString("Time format"), + title: localizedString("Time format"), action: #selector(toggleTimeFormat), items: ShortLong, selected: self.timeFormat diff --git a/Modules/CPU/main.swift b/Modules/CPU/main.swift index f9ac04f2..338deb3f 100644 --- a/Modules/CPU/main.swift +++ b/Modules/CPU/main.swift @@ -18,7 +18,7 @@ public struct CPU_Load: value_t { var userLoad: Double = 0 var idleLoad: Double = 0 - public var widget_value: Double { + public var widgetValue: Double { get { return self.totalUsage } diff --git a/Modules/CPU/popup.swift b/Modules/CPU/popup.swift index 42c42916..fdeb6e78 100644 --- a/Modules/CPU/popup.swift +++ b/Modules/CPU/popup.swift @@ -123,17 +123,17 @@ internal class Popup: NSView, Popup_p { width: container.frame.height, height: container.frame.height ), segments: [], drawValue: true) - self.circle!.toolTip = LocalizedString("CPU usage") + self.circle!.toolTip = localizedString("CPU usage") container.addSubview(self.circle!) let centralWidth: CGFloat = self.dashboardHeight-20 let sideWidth: CGFloat = (view.frame.width - centralWidth - (Constants.Popup.margins*2))/2 self.temperatureCircle = HalfCircleGraphView(frame: NSRect(x: (sideWidth - 60)/2, y: 10, width: 60, height: 50)) - self.temperatureCircle!.toolTip = LocalizedString("CPU temperature") + self.temperatureCircle!.toolTip = localizedString("CPU temperature") (self.temperatureCircle! as NSView).isHidden = true self.frequencyCircle = HalfCircleGraphView(frame: NSRect(x: view.frame.width - 60 - Constants.Popup.margins*2, y: 10, width: 60, height: 50)) - self.frequencyCircle!.toolTip = LocalizedString("CPU frequency") + self.frequencyCircle!.toolTip = localizedString("CPU frequency") (self.frequencyCircle! as NSView).isHidden = true view.addSubview(self.temperatureCircle!) @@ -145,7 +145,7 @@ internal class Popup: NSView, Popup_p { private func initChart() -> NSView { let view: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: self.chartHeight)) - let separator = SeparatorView(LocalizedString("Usage history"), origin: NSPoint(x: 0, y: self.chartHeight-Constants.Popup.separatorHeight), width: self.frame.width) + let separator = separatorView(localizedString("Usage history"), origin: NSPoint(x: 0, y: self.chartHeight-Constants.Popup.separatorHeight), width: self.frame.width) let container: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: separator.frame.origin.y)) container.wantsLayer = true container.layer?.backgroundColor = NSColor.lightGray.withAlphaComponent(0.1).cgColor @@ -162,12 +162,12 @@ internal class Popup: NSView, Popup_p { private func initDetails() -> NSView { let view: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: self.detailsHeight)) - let separator = SeparatorView(LocalizedString("Details"), origin: NSPoint(x: 0, y: self.detailsHeight-Constants.Popup.separatorHeight), width: self.frame.width) + let separator = separatorView(localizedString("Details"), origin: NSPoint(x: 0, y: self.detailsHeight-Constants.Popup.separatorHeight), width: self.frame.width) let container: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: separator.frame.origin.y)) - self.systemField = PopupWithColorRow(container, color: NSColor.systemRed, n: 2, title: "\(LocalizedString("System")):", value: "") - self.userField = PopupWithColorRow(container, color: NSColor.systemBlue, n: 1, title: "\(LocalizedString("User")):", value: "") - self.idleField = PopupWithColorRow(container, color: NSColor.lightGray.withAlphaComponent(0.5), n: 0, title: "\(LocalizedString("Idle")):", value: "") + self.systemField = popupWithColorRow(container, color: NSColor.systemRed, n: 2, title: "\(localizedString("System")):", value: "") + self.userField = popupWithColorRow(container, color: NSColor.systemBlue, n: 1, title: "\(localizedString("User")):", value: "") + self.idleField = popupWithColorRow(container, color: NSColor.lightGray.withAlphaComponent(0.5), n: 0, title: "\(localizedString("Idle")):", value: "") view.addSubview(separator) view.addSubview(container) @@ -177,7 +177,7 @@ internal class Popup: NSView, Popup_p { private func initProcesses() -> NSView { let view: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: self.processesHeight)) - let separator = SeparatorView(LocalizedString("Top processes"), origin: NSPoint(x: 0, y: self.processesHeight-Constants.Popup.separatorHeight), width: self.frame.width) + let separator = separatorView(localizedString("Top processes"), origin: NSPoint(x: 0, y: self.processesHeight-Constants.Popup.separatorHeight), width: self.frame.width) let container: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: separator.frame.origin.y)) for i in 0.. { private var usagePerCore: [Double] = [] public override func setup() { - self.hasHyperthreadingCores = SysctlByName("hw.physicalcpu") != SysctlByName("hw.logicalcpu") - [CTL_HW, HW_NCPU].withUnsafeBufferPointer() { mib in + self.hasHyperthreadingCores = sysctlByName("hw.physicalcpu") != sysctlByName("hw.logicalcpu") + [CTL_HW, HW_NCPU].withUnsafeBufferPointer { mib in var sizeOfNumCPUs: size_t = MemoryLayout.size let status = sysctl(processor_info_array_t(mutating: mib.baseAddress), 2, &numCPUs, &sizeOfNumCPUs, nil, 0) if status != 0 { @@ -39,6 +39,7 @@ internal class LoadReader: Reader { } } + // swiftlint:disable function_body_length public override func read() { let result: kern_return_t = host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, &self.numCPUsU, &self.cpuInfo, &self.numCpuInfo) if result == KERN_SUCCESS { @@ -133,12 +134,12 @@ internal class LoadReader: Reader { } private func hostCPULoadInfo() -> host_cpu_load_info? { - let HOST_CPU_LOAD_INFO_COUNT = MemoryLayout.stride/MemoryLayout.stride - var size = mach_msg_type_number_t(HOST_CPU_LOAD_INFO_COUNT) + let count = MemoryLayout.stride/MemoryLayout.stride + var size = mach_msg_type_number_t(count) var cpuLoadInfo = host_cpu_load_info() let result: kern_return_t = withUnsafeMutablePointer(to: &cpuLoadInfo) { - $0.withMemoryRebound(to: integer_t.self, capacity: HOST_CPU_LOAD_INFO_COUNT) { + $0.withMemoryRebound(to: integer_t.self, capacity: count) { host_statistics(mach_host_self(), HOST_CPU_LOAD_INFO, $0, &size) } } @@ -202,7 +203,7 @@ public class ProcessReader: Reader<[TopProcess]> { var index = 0 var processes: [TopProcess] = [] - output.enumerateLines { (line, stop) -> () in + output.enumerateLines { (line, stop) -> Void in if index != 0 { var str = line.trimmingCharacters(in: .whitespaces) let pidString = str.findAndCrop(pattern: "^\\d+") @@ -250,6 +251,7 @@ public class TemperatureReader: Reader { } } +// swiftlint:disable identifier_name public class FrequencyReader: Reader { private typealias PGSample = UInt64 private typealias UDouble = UnsafeMutablePointer diff --git a/Modules/CPU/settings.swift b/Modules/CPU/settings.swift index 6ba8618b..0ba52688 100644 --- a/Modules/CPU/settings.swift +++ b/Modules/CPU/settings.swift @@ -40,7 +40,7 @@ internal class Settings: NSView, Settings_v { if !self.usagePerCoreState { self.hyperthreadState = false } - self.hasHyperthreadingCores = SysctlByName("hw.physicalcpu") != SysctlByName("hw.logicalcpu") + self.hasHyperthreadingCores = sysctlByName("hw.physicalcpu") != sysctlByName("hw.logicalcpu") super.init(frame: CGRect( x: 0, @@ -57,9 +57,10 @@ internal class Settings: NSView, Settings_v { fatalError("init(coder:) has not been implemented") } + // swiftlint:disable function_body_length public func load(widgets: [widget_t]) { self.subviews.forEach{ $0.removeFromSuperview() } - + var hasIPG = false #if arch(x86_64) @@ -74,49 +75,69 @@ internal class Settings: NSView, Settings_v { num += 1 } - self.addSubview(SelectTitleRow( - frame: NSRect(x: Constants.Settings.margin, y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * num, width: self.frame.width - (Constants.Settings.margin*2), height: rowHeight), - title: LocalizedString("Update interval"), + self.addSubview(selectTitleRow( + frame: NSRect( + x: Constants.Settings.margin, + y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * num, + width: self.frame.width - (Constants.Settings.margin*2), + height: rowHeight + ), + title: localizedString("Update interval"), action: #selector(changeUpdateInterval), items: ReaderUpdateIntervals.map{ "\($0) sec" }, selected: "\(self.updateIntervalValue) sec" )) if !widgets.filter({ $0 == .barChart }).isEmpty { - self.addSubview(ToggleTitleRow( - frame: NSRect(x: Constants.Settings.margin, y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * (num-1), width: self.frame.width - (Constants.Settings.margin*2), height: rowHeight), - title: LocalizedString("Show usage per core"), + self.addSubview(toggleTitleRow( + frame: NSRect( + x: Constants.Settings.margin, + y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * (num-1), + width: self.frame.width - (Constants.Settings.margin*2), + height: rowHeight + ), + title: localizedString("Show usage per core"), action: #selector(toggleUsagePerCore), state: self.usagePerCoreState )) if self.hasHyperthreadingCores { - self.hyperthreadView = ToggleTitleRow( - frame: NSRect(x: Constants.Settings.margin, y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * (num-2), width: self.frame.width - (Constants.Settings.margin*2), height: rowHeight), - title: LocalizedString("Show hyper-threading cores"), + self.hyperthreadView = toggleTitleRow( + frame: NSRect( + x: Constants.Settings.margin, + y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * (num-2), + width: self.frame.width - (Constants.Settings.margin*2), + height: rowHeight + ), + title: localizedString("Show hyper-threading cores"), action: #selector(toggleMultithreading), state: self.hyperthreadState ) if !self.usagePerCoreState { - FindAndToggleEnableNSControlState(self.hyperthreadView, state: false) - FindAndToggleNSControlState(self.hyperthreadView, state: .off) + findAndToggleEnableNSControlState(self.hyperthreadView, state: false) + findAndToggleNSControlState(self.hyperthreadView, state: .off) } self.addSubview(self.hyperthreadView!) } } if hasIPG { - self.addSubview(ToggleTitleRow( - frame: NSRect(x: Constants.Settings.margin, y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * 1, width: self.frame.width - (Constants.Settings.margin*2), height: rowHeight), - title: "\(LocalizedString("CPU frequency")) (IPG)", + self.addSubview(toggleTitleRow( + frame: NSRect( + x: Constants.Settings.margin, + y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * 1, + width: self.frame.width - (Constants.Settings.margin*2), + height: rowHeight + ), + title: "\(localizedString("CPU frequency")) (IPG)", action: #selector(toggleIPG), state: self.IPGState )) } - self.addSubview(SelectTitleRow( + self.addSubview(selectTitleRow( frame: NSRect(x: Constants.Settings.margin, y: Constants.Settings.margin, width: self.frame.width - (Constants.Settings.margin*2), height: rowHeight), - title: LocalizedString("Number of top processes"), + title: localizedString("Number of top processes"), action: #selector(changeNumberOfProcesses), items: NumbersOfProcesses.map{ "\($0)" }, selected: "\(self.numberOfProcesses)" @@ -153,11 +174,11 @@ internal class Settings: NSView, Settings_v { Store.shared.set(key: "\(self.title)_usagePerCore", value: self.usagePerCoreState) self.callback() - FindAndToggleEnableNSControlState(self.hyperthreadView, state: self.usagePerCoreState) + findAndToggleEnableNSControlState(self.hyperthreadView, state: self.usagePerCoreState) if !self.usagePerCoreState { self.hyperthreadState = false Store.shared.set(key: "\(self.title)_hyperhreading", value: self.hyperthreadState) - FindAndToggleNSControlState(self.hyperthreadView, state: .off) + findAndToggleNSControlState(self.hyperthreadView, state: .off) } } diff --git a/Modules/Disk/popup.swift b/Modules/Disk/popup.swift index 1c36b19c..0f7bcf59 100644 --- a/Modules/Disk/popup.swift +++ b/Modules/Disk/popup.swift @@ -28,7 +28,7 @@ internal class Popup: NSView, Popup_p { } internal func capacityCallback(_ value: Disks) { - if self.list.count != value.count && self.list.count != 0 { + if self.list.count != value.count && !self.list.isEmpty { self.subviews.forEach{ $0.removeFromSuperview() } self.list = [:] } @@ -138,7 +138,7 @@ internal class DiskNameAndBarView: NSView { self.uri = path super.init(frame: frame) - self.toolTip = LocalizedString("Open disk") + self.toolTip = localizedString("Open disk") self.addName(name: name) self.addHorizontalBar(size: size, free: free) @@ -274,7 +274,7 @@ internal class DiskLegendView: NSView { self.free = free super.init(frame: frame) - self.toolTip = LocalizedString("Switch view") + self.toolTip = localizedString("Switch view") let height: CGFloat = 14 let view: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height)) @@ -336,9 +336,9 @@ internal class DiskLegendView: NSView { if usedSpace < 0 { usedSpace = 0 } - value = LocalizedString("Used disk memory", DiskSize(usedSpace).getReadableMemory(), DiskSize(self.size).getReadableMemory()) + value = localizedString("Used disk memory", DiskSize(usedSpace).getReadableMemory(), DiskSize(self.size).getReadableMemory()) } else { - value = LocalizedString("Free disk memory", DiskSize(free).getReadableMemory(), DiskSize(self.size).getReadableMemory()) + value = localizedString("Free disk memory", DiskSize(free).getReadableMemory(), DiskSize(self.size).getReadableMemory()) } return value diff --git a/Modules/Disk/settings.swift b/Modules/Disk/settings.swift index 0de362da..6d528718 100644 --- a/Modules/Disk/settings.swift +++ b/Modules/Disk/settings.swift @@ -53,9 +53,14 @@ internal class Settings: NSView, Settings_v { let rowHeight: CGFloat = 30 let num: CGFloat = 3 - self.intervalSelectView = SelectTitleRow( - frame: NSRect(x: Constants.Settings.margin, y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * 2, width: self.frame.width - (Constants.Settings.margin*2), height: rowHeight), - title: LocalizedString("Update interval"), + self.intervalSelectView = selectTitleRow( + frame: NSRect( + x: Constants.Settings.margin, + y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * 2, + width: self.frame.width - (Constants.Settings.margin*2), + height: rowHeight + ), + title: localizedString("Update interval"), action: #selector(changeUpdateInterval), items: ReaderUpdateIntervals.map{ "\($0) sec" }, selected: "\(self.updateIntervalValue) sec" @@ -64,9 +69,14 @@ internal class Settings: NSView, Settings_v { self.addDiskSelector() - self.addSubview(ToggleTitleRow( - frame: NSRect(x: Constants.Settings.margin, y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * 0, width: self.frame.width - (Constants.Settings.margin*2), height: rowHeight), - title: LocalizedString("Show removable disks"), + self.addSubview(toggleTitleRow( + frame: NSRect( + x: Constants.Settings.margin, + y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * 0, + width: self.frame.width - (Constants.Settings.margin*2), + height: rowHeight + ), + title: localizedString("Show removable disks"), action: #selector(toggleRemovable), state: self.removableState )) @@ -82,7 +92,7 @@ internal class Settings: NSView, Settings_v { height: 30 )) - let rowTitle: NSTextField = LabelField(frame: NSRect(x: 0, y: (view.frame.height - 16)/2, width: view.frame.width - 52, height: 17), LocalizedString("Disk to show")) + let rowTitle: NSTextField = LabelField(frame: NSRect(x: 0, y: (view.frame.height - 16)/2, width: view.frame.width - 52, height: 17), localizedString("Disk to show")) rowTitle.font = NSFont.systemFont(ofSize: 13, weight: .light) rowTitle.textColor = .textColor diff --git a/Modules/Fans/main.swift b/Modules/Fans/main.swift index 53410420..b302be91 100644 --- a/Modules/Fans/main.swift +++ b/Modules/Fans/main.swift @@ -76,7 +76,7 @@ public class Fans: Module { } private func checkIfNoSensorsEnabled() { - if self.fansReader.list.filter({ $0.state }).count == 0 { + if self.fansReader.list.filter({ $0.state }).isEmpty { NotificationCenter.default.post(name: .toggleModule, object: nil, userInfo: ["module": self.config.name, "state": false]) } } diff --git a/Modules/Fans/popup.swift b/Modules/Fans/popup.swift index 46a4d76f..628ab3f2 100644 --- a/Modules/Fans/popup.swift +++ b/Modules/Fans/popup.swift @@ -242,7 +242,7 @@ internal class FanView: NSStackView { let minField: NSTextField = TextView(frame: NSRect(x: 0, y: 0, width: 80, height: levels.frame.height)) minField.font = NSFont.systemFont(ofSize: 11, weight: .light) minField.textColor = .secondaryLabelColor - minField.stringValue = "\(LocalizedString("Min")): \(Int(self.fan.minSpeed))" + minField.stringValue = "\(localizedString("Min")): \(Int(self.fan.minSpeed))" minField.alignment = .left let valueField: NSTextField = TextView(frame: NSRect(x: 80, y: 0, width: levels.frame.width - 160, height: levels.frame.height)) @@ -253,7 +253,7 @@ internal class FanView: NSStackView { let maxField: NSTextField = TextView(frame: NSRect(x: levels.frame.width - 80, y: 0, width: 80, height: levels.frame.height)) maxField.font = NSFont.systemFont(ofSize: 11, weight: .light) maxField.textColor = .secondaryLabelColor - maxField.stringValue = "\(LocalizedString("Max")): \(Int(self.fan.maxSpeed))" + maxField.stringValue = "\(localizedString("Max")): \(Int(self.fan.maxSpeed))" maxField.alignment = .right controls.addArrangedSubview(slider) @@ -340,8 +340,8 @@ internal class FanView: NSStackView { private class ModeButtons: NSStackView { public var callback: (FanMode) -> Void = {_ in } - private var autoBtn: NSButton = NSButton(title: LocalizedString("Automatic"), target: nil, action: #selector(autoMode)) - private var manualBtn: NSButton = NSButton(title: LocalizedString("Manual"), target: nil, action: #selector(manualMode)) + private var autoBtn: NSButton = NSButton(title: localizedString("Automatic"), target: nil, action: #selector(autoMode)) + private var manualBtn: NSButton = NSButton(title: localizedString("Manual"), target: nil, action: #selector(manualMode)) public init(frame: NSRect, mode: FanMode) { super.init(frame: frame) diff --git a/Modules/Fans/settings.swift b/Modules/Fans/settings.swift index 028731a6..32325236 100644 --- a/Modules/Fans/settings.swift +++ b/Modules/Fans/settings.swift @@ -60,27 +60,27 @@ internal class Settings: NSStackView, Settings_v { } self.subviews.forEach{ $0.removeFromSuperview() } - self.addArrangedSubview(SelectTitleRow( + self.addArrangedSubview(selectTitleRow( frame: NSRect( x: Constants.Settings.margin, y: 0, width: self.frame.width - (Constants.Settings.margin*2), height: Constants.Settings.row ), - title: LocalizedString("Update interval"), + title: localizedString("Update interval"), action: #selector(changeUpdateInterval), items: ReaderUpdateIntervals.map{ "\($0) sec" }, selected: "\(self.updateIntervalValue) sec" )) - self.addArrangedSubview(ToggleTitleRow( + self.addArrangedSubview(toggleTitleRow( frame: NSRect( x: Constants.Settings.margin, y: 0, width: self.frame.width - (Constants.Settings.margin*2), height: Constants.Settings.row ), - title: LocalizedString("Label"), + title: localizedString("Label"), action: #selector(toggleLabelState), state: self.labelState )) @@ -95,7 +95,7 @@ internal class Settings: NSStackView, Settings_v { view.distribution = .gravityAreas view.spacing = Constants.Settings.margin - let title: NSTextField = LabelField(frame: NSRect(x: 0, y: 0, width: view.frame.width, height: 19), LocalizedString("Fans")) + let title: NSTextField = LabelField(frame: NSRect(x: 0, y: 0, width: view.frame.width, height: 19), localizedString("Fans")) title.font = NSFont.systemFont(ofSize: 14, weight: .regular) title.textColor = .secondaryLabelColor title.alignment = .center @@ -103,7 +103,7 @@ internal class Settings: NSStackView, Settings_v { view.addArrangedSubview(title) self.list.pointee.reversed().forEach { (f: Fan) in - let row: NSView = ToggleTitleRow( + let row: NSView = toggleTitleRow( frame: NSRect(x: 0, y: 0, width: view.frame.width, height: Constants.Settings.row), title: f.name, action: #selector(self.handleSelection), @@ -119,7 +119,7 @@ internal class Settings: NSStackView, Settings_v { view.setFrameSize(NSSize(width: view.frame.width, height: listHeight)) NSLayoutConstraint.activate([ view.heightAnchor.constraint(equalToConstant: listHeight), - view.widthAnchor.constraint(equalToConstant: view.bounds.width), + view.widthAnchor.constraint(equalToConstant: view.bounds.width) ]) self.addArrangedSubview(view) @@ -140,7 +140,7 @@ internal class Settings: NSStackView, Settings_v { state = sender is NSButton ? (sender as! NSButton).state: nil } - Store.shared.set(key: "fan_\(id.rawValue)", value: state! == NSControl.StateValue.on) + Store.shared.set(key: "fan_\(id.rawValue)", value: state! == NSControl.StateValue.on) self.callback() } diff --git a/Modules/GPU/main.swift b/Modules/GPU/main.swift index 322d532d..5c1fe52d 100644 --- a/Modules/GPU/main.swift +++ b/Modules/GPU/main.swift @@ -54,7 +54,7 @@ public struct GPUs: value_t { return self.list.filter{ $0.state && $0.utilization != nil }.sorted{ $0.utilization ?? 0 > $1.utilization ?? 0 } } - public var widget_value: Double { + public var widgetValue: Double { get { return list.isEmpty ? 0 : (list[0].utilization ?? 0) } diff --git a/Modules/GPU/popup.swift b/Modules/GPU/popup.swift index 84080bc4..99cde9cc 100644 --- a/Modules/GPU/popup.swift +++ b/Modules/GPU/popup.swift @@ -122,10 +122,10 @@ private class GPUView: NSStackView { let stateView: NSView = NSView(frame: NSRect(x: width - 8, y: (view.frame.height-7)/2, width: 6, height: 6)) stateView.wantsLayer = true stateView.layer?.backgroundColor = (self.value.state ? NSColor.systemGreen : NSColor.systemRed).cgColor - stateView.toolTip = LocalizedString("GPU \(self.value.state ? "enabled" : "disabled")") + stateView.toolTip = localizedString("GPU \(self.value.state ? "enabled" : "disabled")") stateView.layer?.cornerRadius = 4 - let details = LocalizedString("Details").uppercased() + let details = localizedString("Details").uppercased() let w = details.widthOfString(usingFont: NSFont.systemFont(ofSize: 9, weight: .regular)) + 8 let button = NSButtonWithPadding() button.frame = CGRect(x: view.frame.width - w, y: 2, width: w, height: view.frame.height-2) @@ -135,7 +135,7 @@ private class GPUView: NSStackView { button.isBordered = false button.action = #selector(self.showDetails) button.target = self - button.toolTip = LocalizedString("Details") + button.toolTip = localizedString("Details") button.title = details button.font = NSFont.systemFont(ofSize: 9, weight: .regular) @@ -194,7 +194,7 @@ private class GPUView: NSStackView { } else { circle = HalfCircleGraphView(frame: NSRect(x: 0, y: 0, width: circleSize, height: circleSize)) circle.id = id - circle.toolTip = LocalizedString("GPU \(id)") + circle.toolTip = localizedString("GPU \(id)") if let row = self.circleRow { row.setFrameSize(NSSize(width: row.frame.width, height: self.circleSize + 20)) row.edgeInsets = NSEdgeInsets(top: 10, left: 0, bottom: 0, right: 0) @@ -211,7 +211,7 @@ private class GPUView: NSStackView { chart.layer?.backgroundColor = NSColor.lightGray.withAlphaComponent(0.1).cgColor chart.layer?.cornerRadius = 3 chart.id = id - chart.toolTip = LocalizedString("GPU \(id)") + chart.toolTip = localizedString("GPU \(id)") if let row = self.chartRow { row.setFrameSize(NSSize(width: row.frame.width, height: self.chartSize + 20)) row.spacing = Constants.Popup.margins @@ -246,9 +246,9 @@ private class GPUView: NSStackView { public func update(_ gpu: GPU_Info) { self.detailsView.update(gpu) - if (self.window?.isVisible ?? false) { + if self.window?.isVisible ?? false { self.stateView?.layer?.backgroundColor = (gpu.state ? NSColor.systemGreen : NSColor.systemRed).cgColor - self.stateView?.toolTip = LocalizedString("GPU \(gpu.state ? "enabled" : "disabled")") + self.stateView?.toolTip = localizedString("GPU \(gpu.state ? "enabled" : "disabled")") self.addStats(id: "temperature", gpu.temperature) self.addStats(id: "utilization", gpu.utilization) @@ -306,44 +306,44 @@ private class GPUDetails: NSView { var num: CGFloat = 2 if let value = value.vendor { - grid.addRow(with: keyValueRow("\(LocalizedString("Vendor")):", value)) + grid.addRow(with: keyValueRow("\(localizedString("Vendor")):", value)) num += 1 } - grid.addRow(with: keyValueRow("\(LocalizedString("Model")):", value.model)) + grid.addRow(with: keyValueRow("\(localizedString("Model")):", value.model)) - let state: String = value.state ? LocalizedString("Active") : LocalizedString("Non active") - let arr = keyValueRow("\(LocalizedString("Status")):", state) + let state: String = value.state ? localizedString("Active") : localizedString("Non active") + let arr = keyValueRow("\(localizedString("Status")):", state) self.status = arr.last grid.addRow(with: arr) if let value = value.fanSpeed { - let arr = keyValueRow("\(LocalizedString("Fan speed")):", "\(value)%") + let arr = keyValueRow("\(localizedString("Fan speed")):", "\(value)%") self.fanSpeed = arr.last grid.addRow(with: arr) num += 1 } if let value = value.coreClock { - let arr = keyValueRow("\(LocalizedString("Core clock")):", "\(value)MHz") + let arr = keyValueRow("\(localizedString("Core clock")):", "\(value)MHz") self.coreClock = arr.last grid.addRow(with: arr) num += 1 } if let value = value.memoryClock { - let arr = keyValueRow("\(LocalizedString("Memory clock")):", "\(value)MHz") + let arr = keyValueRow("\(localizedString("Memory clock")):", "\(value)MHz") self.memoryClock = arr.last grid.addRow(with: arr) num += 1 } if let value = value.temperature { - let arr = keyValueRow("\(LocalizedString("Temperature")):", Temperature(Double(value))) + let arr = keyValueRow("\(localizedString("Temperature")):", Temperature(Double(value))) self.temperature = arr.last grid.addRow(with: arr) num += 1 } if let value = value.utilization { - let arr = keyValueRow("\(LocalizedString("Utilization")):", "\(Int(value*100))%") + let arr = keyValueRow("\(localizedString("Utilization")):", "\(Int(value*100))%") self.utilization = arr.last grid.addRow(with: arr) num += 1 @@ -366,7 +366,7 @@ private class GPUDetails: NSView { } public func update(_ gpu: GPU_Info) { - self.status?.stringValue = gpu.state ? LocalizedString("Active") : LocalizedString("Non active") + self.status?.stringValue = gpu.state ? localizedString("Active") : localizedString("Non active") if let value = gpu.fanSpeed { self.fanSpeed?.stringValue = "\(value)%" diff --git a/Modules/GPU/reader.swift b/Modules/GPU/reader.swift index 4467c980..3afa9f66 100644 --- a/Modules/GPU/reader.swift +++ b/Modules/GPU/reader.swift @@ -63,6 +63,7 @@ internal class InfoReader: Reader { } } + // swiftlint:disable function_body_length public override func read() { guard let accelerators = fetchIOService(kIOAcceleratorClassName) else { return @@ -75,7 +76,7 @@ internal class InfoReader: Reader { return } - guard let stats = accelerator["PerformanceStatistics"] as? [String:Any] else { + guard let stats = accelerator["PerformanceStatistics"] as? [String: Any] else { os_log(.error, log: log, "PerformanceStatistics not found") return } @@ -154,7 +155,7 @@ internal class InfoReader: Reader { return } - if let agcInfo = accelerator["AGCInfo"] as? [String:Int], let state = agcInfo["poweredOffByAGC"] { + if let agcInfo = accelerator["AGCInfo"] as? [String: Int], let state = agcInfo["poweredOffByAGC"] { self.gpus.list[idx].state = state == 0 } diff --git a/Modules/GPU/settings.swift b/Modules/GPU/settings.swift index 6686434b..72016b69 100644 --- a/Modules/GPU/settings.swift +++ b/Modules/GPU/settings.swift @@ -54,28 +54,28 @@ internal class Settings: NSView, Settings_v { let rowHeight: CGFloat = 30 let num: CGFloat = widgets.filter{ $0 == .mini }.isEmpty ? 2 : 3 - self.addSubview(SelectTitleRow( + self.addSubview(selectTitleRow( frame: NSRect( x: Constants.Settings.margin, y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * (num-1), width: self.frame.width - (Constants.Settings.margin*2), height: rowHeight ), - title: LocalizedString("Update interval"), + title: localizedString("Update interval"), action: #selector(changeUpdateInterval), items: ReaderUpdateIntervals.map{ "\($0) sec" }, selected: "\(self.updateIntervalValue) sec" )) if !widgets.filter({ $0 == .mini }).isEmpty { - self.addSubview(ToggleTitleRow( + self.addSubview(toggleTitleRow( frame: NSRect( x: Constants.Settings.margin, y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * 1, width: self.frame.width - (Constants.Settings.margin*2), height: rowHeight ), - title: LocalizedString("Show GPU type"), + title: localizedString("Show GPU type"), action: #selector(toggleShowType), state: self.showTypeValue )) @@ -95,7 +95,7 @@ internal class Settings: NSView, Settings_v { let view: NSGridView = NSGridView(frame: frame) view.yPlacement = .center - let title: NSTextField = LabelField(frame: NSRect(x: 0, y: 0, width: 100, height: 17), LocalizedString("GPU to show")) + let title: NSTextField = LabelField(frame: NSRect(x: 0, y: 0, width: 100, height: 17), localizedString("GPU to show")) title.font = NSFont.systemFont(ofSize: 13, weight: .light) title.textColor = .textColor @@ -116,7 +116,7 @@ internal class Settings: NSView, Settings_v { internal func setList(_ gpus: GPUs) { var list: [KeyValue_t] = [ KeyValue_t(key: "automatic", value: "Automatic"), - KeyValue_t(key: "separator", value: "separator"), + KeyValue_t(key: "separator", value: "separator") ] gpus.active().forEach{ list.append(KeyValue_t(key: $0.model, value: $0.model)) } @@ -132,7 +132,7 @@ internal class Settings: NSView, Settings_v { if item.key.contains("separator") { menu.addItem(NSMenuItem.separator()) } else { - let interfaceMenu = NSMenuItem(title: LocalizedString(item.value), action: nil, keyEquivalent: "") + let interfaceMenu = NSMenuItem(title: localizedString(item.value), action: nil, keyEquivalent: "") interfaceMenu.representedObject = item.key menu.addItem(interfaceMenu) if self.selectedGPU == item.key { diff --git a/Modules/Net/main.swift b/Modules/Net/main.swift index b631961d..c2cd7329 100644 --- a/Modules/Net/main.swift +++ b/Modules/Net/main.swift @@ -58,7 +58,7 @@ public struct Network_Usage: value_t { self.ssid = nil } - public var widget_value: Double = 0 + public var widgetValue: Double = 0 } public struct Network_Process { @@ -130,7 +130,7 @@ public class Network: Module { list.append(displayName as String) } } - return list.count > 0 + return !list.isEmpty } private func usageCallback(_ raw: Network_Usage?) { diff --git a/Modules/Net/popup.swift b/Modules/Net/popup.swift index a2e0326a..e3145646 100644 --- a/Modules/Net/popup.swift +++ b/Modules/Net/popup.swift @@ -8,11 +8,13 @@ // // Copyright © 2020 Serhiy Mytrovtsiy. All rights reserved. // +// swiftlint:disable file_length import Cocoa import ModuleKit import StatsKit +// swiftlint:disable type_body_length internal class Popup: NSStackView, Popup_p { public var sizeCallback: ((NSSize) -> Void)? = nil @@ -107,14 +109,14 @@ internal class Popup: NSStackView, Popup_p { view.heightAnchor.constraint(equalToConstant: view.bounds.height).isActive = true let leftPart: NSView = NSView(frame: NSRect(x: 0, y: 0, width: view.frame.width / 2, height: view.frame.height)) - let uploadFields = self.topValueView(leftPart, title: LocalizedString("Uploading"), color: NSColor.systemRed) + let uploadFields = self.topValueView(leftPart, title: localizedString("Uploading"), color: NSColor.systemRed) self.uploadView = uploadFields.0 self.uploadValueField = uploadFields.1 self.uploadUnitField = uploadFields.2 self.uploadStateView = uploadFields.3 let rightPart: NSView = NSView(frame: NSRect(x: view.frame.width / 2, y: 0, width: view.frame.width / 2, height: view.frame.height)) - let downloadFields = self.topValueView(rightPart, title: LocalizedString("Downloading"), color: NSColor.systemBlue) + let downloadFields = self.topValueView(rightPart, title: localizedString("Downloading"), color: NSColor.systemBlue) self.downloadView = downloadFields.0 self.downloadValueField = downloadFields.1 self.downloadUnitField = downloadFields.2 @@ -130,7 +132,7 @@ internal class Popup: NSStackView, Popup_p { let view: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: 90 + Constants.Popup.separatorHeight)) view.heightAnchor.constraint(equalToConstant: view.bounds.height).isActive = true - let separator = SeparatorView(LocalizedString("Usage history"), origin: NSPoint(x: 0, y: 90), width: self.frame.width) + let separator = separatorView(localizedString("Usage history"), origin: NSPoint(x: 0, y: 90), width: self.frame.width) let container: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: separator.frame.origin.y)) container.wantsLayer = true container.layer?.backgroundColor = NSColor.lightGray.withAlphaComponent(0.1).cgColor @@ -168,21 +170,21 @@ internal class Popup: NSStackView, Popup_p { button.contentTintColor = .lightGray button.action = #selector(self.resetTotalNetworkUsage) button.target = self - button.toolTip = LocalizedString("Reset") + button.toolTip = localizedString("Reset") button.image = Bundle(for: Module.self).image(forResource: "refresh")! - row.addSubview(SeparatorView(LocalizedString("Details"), origin: NSPoint(x: 0, y: 0), width: self.frame.width)) + row.addSubview(separatorView(localizedString("Details"), origin: NSPoint(x: 0, y: 0), width: self.frame.width)) row.addSubview(button) container.addArrangedSubview(row) - self.totalUploadField = PopupWithColorRow(container, color: NSColor.systemRed, n: 5, title: "\(LocalizedString("Total upload")):", value: "0") - self.totalDownloadField = PopupWithColorRow(container, color: NSColor.systemBlue, n: 4, title: "\(LocalizedString("Total download")):", value: "0") + self.totalUploadField = popupWithColorRow(container, color: NSColor.systemRed, n: 5, title: "\(localizedString("Total upload")):", value: "0") + self.totalDownloadField = popupWithColorRow(container, color: NSColor.systemBlue, n: 4, title: "\(localizedString("Total download")):", value: "0") - self.interfaceField = PopupRow(container, n: 3, title: "\(LocalizedString("Interface")):", value: LocalizedString("Unknown")).1 - self.ssidField = PopupRow(container, n: 2, title: "\(LocalizedString("Network")):", value: LocalizedString("Unknown")).1 - self.macAdressField = PopupRow(container, n: 1, title: "\(LocalizedString("Physical address")):", value: LocalizedString("Unknown")).1 - self.localIPField = PopupRow(container, n: 0, title: "\(LocalizedString("Local IP")):", value: LocalizedString("Unknown")).1 + self.interfaceField = popupRow(container, n: 3, title: "\(localizedString("Interface")):", value: localizedString("Unknown")).1 + self.ssidField = popupRow(container, n: 2, title: "\(localizedString("Network")):", value: localizedString("Unknown")).1 + self.macAdressField = popupRow(container, n: 1, title: "\(localizedString("Physical address")):", value: localizedString("Unknown")).1 + self.localIPField = popupRow(container, n: 0, title: "\(localizedString("Local IP")):", value: localizedString("Unknown")).1 self.localIPField?.isSelectable = true self.macAdressField?.isSelectable = true @@ -214,16 +216,16 @@ internal class Popup: NSStackView, Popup_p { button.contentTintColor = .lightGray button.action = #selector(self.refreshPublicIP) button.target = self - button.toolTip = LocalizedString("Refresh") + button.toolTip = localizedString("Refresh") button.image = Bundle(for: Module.self).image(forResource: "refresh")! - row.addSubview(SeparatorView(LocalizedString("Public IP"), origin: NSPoint(x: 0, y: 0), width: self.frame.width)) + row.addSubview(separatorView(localizedString("Public IP"), origin: NSPoint(x: 0, y: 0), width: self.frame.width)) row.addSubview(button) container.addArrangedSubview(row) - self.publicIPv4Field = PopupRow(container, title: "\(LocalizedString("v4")):", value: LocalizedString("Unknown")).1 - self.publicIPv6Field = PopupRow(container, title: "\(LocalizedString("v6")):", value: LocalizedString("Unknown")).1 + self.publicIPv4Field = popupRow(container, title: "\(localizedString("v4")):", value: localizedString("Unknown")).1 + self.publicIPv6Field = popupRow(container, title: "\(localizedString("v6")):", value: localizedString("Unknown")).1 self.publicIPv4Field?.isSelectable = true if let valueView = self.publicIPv6Field { @@ -247,7 +249,7 @@ internal class Popup: NSStackView, Popup_p { private func initProcesses() -> NSView { let view: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: self.processesHeight)) - let separator = SeparatorView(LocalizedString("Top processes"), origin: NSPoint(x: 0, y: self.processesHeight-Constants.Popup.separatorHeight), width: self.frame.width) + let separator = separatorView(localizedString("Top processes"), origin: NSPoint(x: 0, y: self.processesHeight-Constants.Popup.separatorHeight), width: self.frame.width) let container: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: separator.frame.origin.y)) for i in 0.. (NSView, NSTextField, NSTextField, ColorView) { let topHeight: CGFloat = 30 let titleHeight: CGFloat = 15 diff --git a/Modules/Net/readers.swift b/Modules/Net/readers.swift index 3d9efdb3..1ce76ac6 100644 --- a/Modules/Net/readers.swift +++ b/Modules/Net/readers.swift @@ -163,7 +163,7 @@ internal class UsageReader: Reader { var totalUpload: Int64 = 0 var totalDownload: Int64 = 0 var firstLine = false - output.enumerateLines { (line, _) -> () in + output.enumerateLines { (line, _) -> Void in if !firstLine { firstLine = true return @@ -297,6 +297,7 @@ public class ProcessReader: Reader<[Network_Process]> { self.popup = true } + // swiftlint:disable function_body_length public override func read() { if self.numberOfProcesses == 0 { return @@ -335,7 +336,7 @@ public class ProcessReader: Reader<[Network_Process]> { var list: [Network_Process] = [] var firstLine = false - output.enumerateLines { (line, _) -> () in + output.enumerateLines { (line, _) -> Void in if !firstLine { firstLine = true return @@ -371,7 +372,7 @@ public class ProcessReader: Reader<[Network_Process]> { } var processes: [Network_Process] = [] - if self.previous.count == 0 { + if self.previous.isEmpty { self.previous = list processes = list } else { @@ -391,7 +392,7 @@ public class ProcessReader: Reader<[Network_Process]> { upload = 0 } - processes.append(Network_Process(time: time, name: p.name, pid: p.pid, download: download, upload: upload, icon: p.icon)) + processes.append(Network_Process(time: time, name: p.name, pid: p.pid, download: download, upload: upload, icon: p.icon)) } } self.previous = list diff --git a/Modules/Net/settings.swift b/Modules/Net/settings.swift index 0ea15016..f26ae822 100644 --- a/Modules/Net/settings.swift +++ b/Modules/Net/settings.swift @@ -58,17 +58,27 @@ internal class Settings: NSView, Settings_v { let rowHeight: CGFloat = 30 let num: CGFloat = 2 - self.addSubview(SelectTitleRow( - frame: NSRect(x: Constants.Settings.margin, y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * 2, width: self.frame.width - (Constants.Settings.margin*2), height: 30), - title: LocalizedString("Number of top processes"), + self.addSubview(selectTitleRow( + frame: NSRect( + x: Constants.Settings.margin, + y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * 2, + width: self.frame.width - (Constants.Settings.margin*2), + height: 30 + ), + title: localizedString("Number of top processes"), action: #selector(changeNumberOfProcesses), items: NumbersOfProcesses.map{ "\($0)" }, selected: "\(self.numberOfProcesses)" )) - self.addSubview(SelectRow( - frame: NSRect(x: Constants.Settings.margin, y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * 1, width: self.frame.width - (Constants.Settings.margin*2), height: 30), - title: LocalizedString("Reader type"), + self.addSubview(selectRow( + frame: NSRect( + x: Constants.Settings.margin, + y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * 1, + width: self.frame.width - (Constants.Settings.margin*2), + height: 30 + ), + title: localizedString("Reader type"), action: #selector(changeReaderType), items: NetworkReaders, selected: self.readerType @@ -82,7 +92,7 @@ internal class Settings: NSView, Settings_v { private func addInterfaceSelector() { let view: NSView = NSView(frame: NSRect(x: Constants.Settings.margin, y: Constants.Settings.margin, width: self.frame.width, height: 30)) - let rowTitle: NSTextField = LabelField(frame: NSRect(x: 0, y: (view.frame.height - 16)/2, width: view.frame.width - 52, height: 17), LocalizedString("Network interface")) + let rowTitle: NSTextField = LabelField(frame: NSRect(x: 0, y: (view.frame.height - 16)/2, width: view.frame.width - 52, height: 17), localizedString("Network interface")) rowTitle.font = NSFont.systemFont(ofSize: 13, weight: .light) rowTitle.textColor = .textColor diff --git a/Modules/RAM/main.swift b/Modules/RAM/main.swift index 1960a83c..1b87fd2f 100644 --- a/Modules/RAM/main.swift +++ b/Modules/RAM/main.swift @@ -30,7 +30,7 @@ public struct RAM_Usage: value_t { var pressureLevel: Int var swap: Swap - public var widget_value: Double { + public var widgetValue: Double { get { return self.usage } diff --git a/Modules/RAM/popup.swift b/Modules/RAM/popup.swift index 426e314f..dd59f9a6 100644 --- a/Modules/RAM/popup.swift +++ b/Modules/RAM/popup.swift @@ -122,13 +122,13 @@ internal class Popup: NSView, Popup_p { width: container.frame.height, height: container.frame.height ), segments: [], drawValue: true) - self.circle!.toolTip = LocalizedString("Memory usage") + self.circle!.toolTip = localizedString("Memory usage") container.addSubview(self.circle!) let centralWidth: CGFloat = self.dashboardHeight-20 let sideWidth: CGFloat = (view.frame.width - centralWidth - (Constants.Popup.margins*2))/2 self.level = PressureView(frame: NSRect(x: (sideWidth - 60)/2, y: 10, width: 60, height: 50)) - self.level!.toolTip = LocalizedString("Memory pressure") + self.level!.toolTip = localizedString("Memory pressure") view.addSubview(self.level!) view.addSubview(container) @@ -138,7 +138,7 @@ internal class Popup: NSView, Popup_p { private func initChart() -> NSView { let view: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: self.chartHeight)) - let separator = SeparatorView(LocalizedString("Usage history"), origin: NSPoint(x: 0, y: self.chartHeight-Constants.Popup.separatorHeight), width: self.frame.width) + let separator = separatorView(localizedString("Usage history"), origin: NSPoint(x: 0, y: self.chartHeight-Constants.Popup.separatorHeight), width: self.frame.width) let container: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: separator.frame.origin.y)) container.wantsLayer = true container.layer?.backgroundColor = NSColor.lightGray.withAlphaComponent(0.1).cgColor @@ -155,15 +155,15 @@ internal class Popup: NSView, Popup_p { private func initDetails() -> NSView { let view: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: self.detailsHeight)) - let separator = SeparatorView(LocalizedString("Details"), origin: NSPoint(x: 0, y: self.detailsHeight-Constants.Popup.separatorHeight), width: self.frame.width) + let separator = separatorView(localizedString("Details"), origin: NSPoint(x: 0, y: self.detailsHeight-Constants.Popup.separatorHeight), width: self.frame.width) let container: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: separator.frame.origin.y)) - self.usedField = PopupRow(container, n: 5, title: "\(LocalizedString("Used")):", value: "").1 - self.appField = PopupWithColorRow(container, color: NSColor.systemBlue, n: 4, title: "\(LocalizedString("App")):", value: "") - self.wiredField = PopupWithColorRow(container, color: NSColor.systemOrange, n: 3, title: "\(LocalizedString("Wired")):", value: "") - self.compressedField = PopupWithColorRow(container, color: NSColor.systemPink, n: 2, title: "\(LocalizedString("Compressed")):", value: "") - self.freeField = PopupWithColorRow(container, color: NSColor.lightGray.withAlphaComponent(0.5), n: 1, title: "\(LocalizedString("Free")):", value: "") - self.swapField = PopupRow(container, n: 0, title: "\(LocalizedString("Swap")):", value: "").1 + self.usedField = popupRow(container, n: 5, title: "\(localizedString("Used")):", value: "").1 + self.appField = popupWithColorRow(container, color: NSColor.systemBlue, n: 4, title: "\(localizedString("App")):", value: "") + self.wiredField = popupWithColorRow(container, color: NSColor.systemOrange, n: 3, title: "\(localizedString("Wired")):", value: "") + self.compressedField = popupWithColorRow(container, color: NSColor.systemPink, n: 2, title: "\(localizedString("Compressed")):", value: "") + self.freeField = popupWithColorRow(container, color: NSColor.lightGray.withAlphaComponent(0.5), n: 1, title: "\(localizedString("Free")):", value: "") + self.swapField = popupRow(container, n: 0, title: "\(localizedString("Swap")):", value: "").1 view.addSubview(separator) view.addSubview(container) @@ -173,7 +173,7 @@ internal class Popup: NSView, Popup_p { private func initProcesses() -> NSView { let view: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: self.processesHeight)) - let separator = SeparatorView(LocalizedString("Top processes"), origin: NSPoint(x: 0, y: self.processesHeight-Constants.Popup.separatorHeight), width: self.frame.width) + let separator = separatorView(localizedString("Top processes"), origin: NSPoint(x: 0, y: self.processesHeight-Constants.Popup.separatorHeight), width: self.frame.width) let container: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: separator.frame.origin.y)) for i in 0.. { let used = active + inactive + speculative + wired + compressed - purgeable - external let free = self.totalSize - used - var int_size: size_t = MemoryLayout.size + var intSize: size_t = MemoryLayout.size var pressureLevel: Int = 0 - sysctlbyname("kern.memorystatus_vm_pressure_level", &pressureLevel, &int_size, nil, 0) + sysctlbyname("kern.memorystatus_vm_pressure_level", &pressureLevel, &intSize, nil, 0) - var string_size: size_t = MemoryLayout.size + var stringSize: size_t = MemoryLayout.size var swap: xsw_usage = xsw_usage() - sysctlbyname("vm.swapusage", &swap, &string_size, nil, 0) + sysctlbyname("vm.swapusage", &swap, &stringSize, nil, 0) self.callback(RAM_Usage( total: self.totalSize, @@ -145,7 +145,7 @@ public class ProcessReader: Reader<[TopProcess]> { } var processes: [TopProcess] = [] - output.enumerateLines { (line, _) -> () in + output.enumerateLines { (line, _) -> Void in if line.matches("^\\d+ +.* +\\d+[A-Z]*\\+?\\-? *$") { var str = line.trimmingCharacters(in: .whitespaces) let pidString = str.findAndCrop(pattern: "^\\d+") @@ -154,7 +154,7 @@ public class ProcessReader: Reader<[TopProcess]> { command = command.replacingOccurrences(of: usageString, with: "") if let regex = try? NSRegularExpression(pattern: " (\\+|\\-)*$", options: .caseInsensitive) { - command = regex.stringByReplacingMatches(in: command, options: [], range: NSRange(location: 0, length: command.count), withTemplate: "") + command = regex.stringByReplacingMatches(in: command, options: [], range: NSRange(location: 0, length: command.count), withTemplate: "") } let pid = Int(pidString.filter("01234567890.".contains)) ?? 0 diff --git a/Modules/RAM/settings.swift b/Modules/RAM/settings.swift index 41501423..37c5f439 100644 --- a/Modules/RAM/settings.swift +++ b/Modules/RAM/settings.swift @@ -49,17 +49,22 @@ internal class Settings: NSView, Settings_v { let rowHeight: CGFloat = 30 let num: CGFloat = 1 - self.addSubview(SelectTitleRow( - frame: NSRect(x: Constants.Settings.margin, y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * num, width: self.frame.width - (Constants.Settings.margin*2), height: rowHeight), - title: LocalizedString("Update interval"), + self.addSubview(selectTitleRow( + frame: NSRect( + x: Constants.Settings.margin, + y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * num, + width: self.frame.width - (Constants.Settings.margin*2), + height: rowHeight + ), + title: localizedString("Update interval"), action: #selector(changeUpdateInterval), items: ReaderUpdateIntervals.map{ "\($0) sec" }, selected: "\(self.updateIntervalValue) sec" )) - self.addSubview(SelectTitleRow( + self.addSubview(selectTitleRow( frame: NSRect(x: Constants.Settings.margin, y: Constants.Settings.margin, width: self.frame.width - (Constants.Settings.margin*2), height: rowHeight), - title: LocalizedString("Number of top processes"), + title: localizedString("Number of top processes"), action: #selector(changeNumberOfProcesses), items: NumbersOfProcesses.map{ "\($0)" }, selected: "\(self.numberOfProcesses)" diff --git a/Modules/Sensors/main.swift b/Modules/Sensors/main.swift index d585aeaa..cbcf336a 100644 --- a/Modules/Sensors/main.swift +++ b/Modules/Sensors/main.swift @@ -58,7 +58,7 @@ public class Sensors: Module { } private func checkIfNoSensorsEnabled() { - if self.sensorsReader.list.filter({ $0.state }).count == 0 { + if self.sensorsReader.list.filter({ $0.state }).isEmpty { NotificationCenter.default.post(name: .toggleModule, object: nil, userInfo: ["module": self.config.name, "state": false]) } } diff --git a/Modules/Sensors/popup.swift b/Modules/Sensors/popup.swift index 3dac72ea..95a09251 100644 --- a/Modules/Sensors/popup.swift +++ b/Modules/Sensors/popup.swift @@ -54,13 +54,13 @@ internal class Popup: NSView, Popup_p { let height: CGFloat = CGFloat((22*filtered.count)) + Constants.Popup.separatorHeight let view: NSView = NSView(frame: NSRect(x: 0, y: y, width: self.frame.width, height: height)) - let separator = SeparatorView(LocalizedString(typ.rawValue), origin: NSPoint(x: 0, y: view.frame.height - Constants.Popup.separatorHeight), width: self.frame.width) + let separator = separatorView(localizedString(typ.rawValue), origin: NSPoint(x: 0, y: view.frame.height - Constants.Popup.separatorHeight), width: self.frame.width) view.addSubview(separator) var i: CGFloat = 0 groups.reversed().forEach { (group: SensorGroup) in filtered.reversed().filter{ $0.group == group }.forEach { (s: Sensor_t) in - let (key, value) = PopupRow(view, n: i, title: "\(s.name):", value: s.formattedValue) + let (key, value) = popupRow(view, n: i, title: "\(s.name):", value: s.formattedValue) key.toolTip = s.key self.list[s.key] = value i += 1 @@ -77,7 +77,7 @@ internal class Popup: NSView, Popup_p { internal func usageCallback(_ values: [Sensor_t]) { DispatchQueue.main.async(execute: { - if (self.window?.isVisible ?? false) { + if self.window?.isVisible ?? false { values.forEach { (s: Sensor_t) in if self.list[s.key] != nil { self.list[s.key]?.stringValue = s.formattedValue diff --git a/Modules/Sensors/settings.swift b/Modules/Sensors/settings.swift index afa937f9..e4f626fe 100644 --- a/Modules/Sensors/settings.swift +++ b/Modules/Sensors/settings.swift @@ -68,9 +68,9 @@ internal class Settings: NSView, Settings_v { height: height )) - self.addSubview(SelectTitleRow( + self.addSubview(selectTitleRow( frame: NSRect(x: Constants.Settings.margin, y: height - rowHeight, width: view.frame.width, height: rowHeight), - title: LocalizedString("Update interval"), + title: localizedString("Update interval"), action: #selector(changeUpdateInterval), items: ReaderUpdateIntervals.map{ "\($0) sec" }, selected: "\(self.updateIntervalValue) sec" @@ -88,7 +88,7 @@ internal class Settings: NSView, Settings_v { groups.reversed().forEach { (group: SensorGroup) in filtered.reversed().filter{ $0.group == group }.forEach { (s: Sensor_t) in - let row: NSView = ToggleTitleRow( + let row: NSView = toggleTitleRow( frame: NSRect(x: 0, y: y, width: view.frame.width, height: rowHeight), title: s.name, action: #selector(self.handleSelection), @@ -103,7 +103,7 @@ internal class Settings: NSView, Settings_v { } let rowTitleView: NSView = NSView(frame: NSRect(x: 0, y: y, width: view.frame.width, height: rowHeight)) - let rowTitle: NSTextField = LabelField(frame: NSRect(x: 0, y: (rowHeight-19)/2, width: view.frame.width, height: 19), LocalizedString(typ.rawValue)) + let rowTitle: NSTextField = LabelField(frame: NSRect(x: 0, y: (rowHeight-19)/2, width: view.frame.width, height: 19), localizedString(typ.rawValue)) rowTitle.font = NSFont.systemFont(ofSize: 14, weight: .regular) rowTitle.textColor = .secondaryLabelColor rowTitle.alignment = .center @@ -127,7 +127,7 @@ internal class Settings: NSView, Settings_v { state = sender is NSButton ? (sender as! NSButton).state: nil } - Store.shared.set(key: "sensor_\(id.rawValue)", value: state! == NSControl.StateValue.on) + Store.shared.set(key: "sensor_\(id.rawValue)", value: state! == NSControl.StateValue.on) self.callback() } diff --git a/Modules/Sensors/values.swift b/Modules/Sensors/values.swift index b19feb13..9aae51d1 100644 --- a/Modules/Sensors/values.swift +++ b/Modules/Sensors/values.swift @@ -103,7 +103,7 @@ struct Sensor_t { // List of keys: https://github.com/acidanthera/VirtualSMC/blob/master/Docs/SMCSensorKeys.txt let SensorsList: [Sensor_t] = [ - /// Temperature + // Temperature Sensor_t(key: "TA%P", name: "Ambient %", group: .sensor, type: .temperature), Sensor_t(key: "Th%H", name: "Heatpipe %", group: .sensor, type: .temperature), Sensor_t(key: "TZ%C", name: "Termal zone %", group: .sensor, type: .temperature), @@ -135,7 +135,7 @@ let SensorsList: [Sensor_t] = [ Sensor_t(key: "TN0H", name: "Northbridge heatsink", group: .system, type: .temperature), Sensor_t(key: "TN0P", name: "Northbridge proximity", group: .system, type: .temperature), - /// Voltage + // Voltage Sensor_t(key: "VCAC", name: "CPU IA", group: .CPU, type: .voltage), Sensor_t(key: "VCSC", name: "CPU System Agent", group: .CPU, type: .voltage), Sensor_t(key: "VC%C", name: "CPU Core %", group: .CPU, type: .voltage), @@ -155,7 +155,7 @@ let SensorsList: [Sensor_t] = [ Sensor_t(key: "VV9S", name: "12V", group: .sensor, type: .voltage), Sensor_t(key: "VeES", name: "PCI 12V", group: .sensor, type: .voltage), - /// Power + // Power Sensor_t(key: "PC0C", name: "CPU Core", group: .CPU, type: .power), Sensor_t(key: "PCAM", name: "CPU Core (IMON)", group: .CPU, type: .power), Sensor_t(key: "PCPC", name: "CPU Package", group: .CPU, type: .power), @@ -176,6 +176,6 @@ let SensorsList: [Sensor_t] = [ Sensor_t(key: "PDTR", name: "DC In", group: .sensor, type: .power), Sensor_t(key: "PSTR", name: "System total", group: .sensor, type: .power), - /// Fans - Sensor_t(key: "F%Ac", name: "Fan #%", group: .sensor, type: .fan), + // Fans + Sensor_t(key: "F%Ac", name: "Fan #%", group: .sensor, type: .fan) ] diff --git a/Stats.xcodeproj/project.pbxproj b/Stats.xcodeproj/project.pbxproj index 4ee92057..b96cd7ad 100644 --- a/Stats.xcodeproj/project.pbxproj +++ b/Stats.xcodeproj/project.pbxproj @@ -987,6 +987,7 @@ 9AB54DAE22A19F96006192E0 /* Copy Files */, 9A6698E72326AB16001D00E1 /* Embed Frameworks */, 9AECEF3D24ACF98800DB95D4 /* Copy Files */, + 9A88E2672659002E00E2B7B0 /* ShellScript */, ); buildRules = ( ); @@ -1434,6 +1435,26 @@ }; /* End PBXResourcesBuildPhase section */ +/* Begin PBXShellScriptBuildPhase section */ + 9A88E2672659002E00E2B7B0 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "if which swiftlint >/dev/null; then\n swiftlint\nelse\n echo \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi\n"; + }; +/* End PBXShellScriptBuildPhase section */ + /* Begin PBXSourcesBuildPhase section */ 9A0C82D624460F7200FAE3D4 /* Sources */ = { isa = PBXSourcesBuildPhase; diff --git a/Stats/AppDelegate.swift b/Stats/AppDelegate.swift index b05ffda8..509048a1 100755 --- a/Stats/AppDelegate.swift +++ b/Stats/AppDelegate.swift @@ -30,7 +30,7 @@ var modules: [Module] = [ Sensors(), Fans(), Network(), - Battery(), + Battery() ] var log = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "Stats") @@ -60,6 +60,9 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele func applicationWillTerminate(_ aNotification: Notification) { modules.forEach{ $0.terminate() } + } + + deinit { NotificationCenter.default.removeObserver(self) } diff --git a/Stats/Views/AppSettings.swift b/Stats/Views/AppSettings.swift index 2f80741b..aa2b65fa 100644 --- a/Stats/Views/AppSettings.swift +++ b/Stats/Views/AppSettings.swift @@ -104,12 +104,12 @@ class ApplicationSettings: NSScrollView { let statsVersion: NSTextField = TextView(frame: NSRect(x: 0, y: 0, width: view.frame.width, height: 16)) statsVersion.alignment = .center statsVersion.font = NSFont.systemFont(ofSize: 12, weight: .regular) - statsVersion.stringValue = "\(LocalizedString("Version")) \(versionNumber)" + statsVersion.stringValue = "\(localizedString("Version")) \(versionNumber)" statsVersion.isSelectable = true statsVersion.toolTip = "Build number: \(buildNumber)" let button: NSButton = NSButton(frame: NSRect(x: (view.frame.width - 160)/2, y: 0, width: 160, height: 30)) - button.title = LocalizedString("Check for update") + button.title = localizedString("Check for update") button.bezelStyle = .rounded button.target = self button.action = #selector(updateAction) @@ -162,7 +162,7 @@ class ApplicationSettings: NSScrollView { NSLayoutConstraint.activate([ grid.centerXAnchor.constraint(equalTo: view.centerXAnchor), - grid.centerYAnchor.constraint(equalTo: view.centerYAnchor), + grid.centerYAnchor.constraint(equalTo: view.centerYAnchor) ]) return view @@ -172,8 +172,8 @@ class ApplicationSettings: NSScrollView { private func updates() -> [NSView] { return [ - self.titleView(LocalizedString("Check for updates")), - SelectView( + self.titleView(localizedString("Check for updates")), + selectView( action: #selector(self.toggleUpdateInterval), items: AppUpdateIntervals, selected: self.updateIntervalValue @@ -183,8 +183,8 @@ class ApplicationSettings: NSScrollView { private func temperature() -> [NSView] { return [ - self.titleView(LocalizedString("Temperature")), - SelectView( + self.titleView(localizedString("Temperature")), + selectView( action: #selector(self.toggleTemperatureUnits), items: TemperatureUnits, selected: self.temperatureUnitsValue @@ -194,7 +194,7 @@ class ApplicationSettings: NSScrollView { private func dockIcon() -> [NSView] { return [ - self.titleView(LocalizedString("Show icon in dock")), + self.titleView(localizedString("Show icon in dock")), self.toggleView( action: #selector(self.toggleDock), state: Store.shared.bool(key: "dockIcon", defaultValue: false) @@ -204,7 +204,7 @@ class ApplicationSettings: NSScrollView { private func startAtLogin() -> [NSView] { return [ - self.titleView(LocalizedString("Start at login")), + self.titleView(localizedString("Start at login")), self.toggleView( action: #selector(self.toggleLaunchAtLogin), state: LaunchAtLogin.isEnabled @@ -251,7 +251,7 @@ class ApplicationSettings: NSScrollView { } @objc func updateAction(_ sender: NSObject) { - updater.check() { result, error in + updater.check { result, error in if error != nil { os_log(.error, log: log, "error updater.check(): %s", "\(error!.localizedDescription)") return diff --git a/Stats/Views/Dashboard.swift b/Stats/Views/Dashboard.swift index 9f675cbc..8856d95b 100644 --- a/Stats/Views/Dashboard.swift +++ b/Stats/Views/Dashboard.swift @@ -89,7 +89,7 @@ class Dashboard: NSScrollView { let osField: NSTextField = TextView(frame: NSRect(x: 0, y: 0, width: view.frame.width, height: 18)) osField.alignment = .center osField.font = NSFont.systemFont(ofSize: 12, weight: .regular) - osField.stringValue = "macOS \(SystemKit.shared.device.os?.name ?? LocalizedString("Unknown")) (\(SystemKit.shared.device.os?.version.getFullVersion() ?? ""))" + osField.stringValue = "macOS \(SystemKit.shared.device.os?.name ?? localizedString("Unknown")) (\(SystemKit.shared.device.os?.version.getFullVersion() ?? ""))" osField.isSelectable = true container.addRow(with: [deviceImageView]) @@ -144,7 +144,7 @@ class Dashboard: NSScrollView { NSLayoutConstraint.activate([ grid.centerXAnchor.constraint(equalTo: view.centerXAnchor), - grid.centerYAnchor.constraint(equalTo: view.centerYAnchor), + grid.centerYAnchor.constraint(equalTo: view.centerYAnchor) ]) return view @@ -177,7 +177,7 @@ class Dashboard: NSScrollView { } if cpu.physicalCores != nil || cpu.logicalCores != nil { - if value.count != 0 { + if !value.isEmpty { value += "\n" } @@ -194,12 +194,12 @@ class Dashboard: NSScrollView { value += "\(mini)" } } else { - value = LocalizedString("Unknown") + value = localizedString("Unknown") } return [ - self.titleView("\(LocalizedString("Processor")):"), - self.valueView(value), + self.titleView("\(localizedString("Processor")):"), + self.valueView(value) ] } @@ -219,21 +219,21 @@ class Dashboard: NSScrollView { } if let speed = dimm.speed { - if row.count != 0 && row.last != " " { + if !row.isEmpty && row.last != " " { row += " " } row += speed } if let type = dimm.type { - if row.count != 0 && row.last != " " { + if !row.isEmpty && row.last != " " { row += " " } row += type } if dimm.bank != nil || dimm.channel != nil { - if row.count != 0 && row.last != " " { + if !row.isEmpty && row.last != " " { row += " " } @@ -250,12 +250,12 @@ class Dashboard: NSScrollView { value += "\(row)\(i == dimms.count-1 ? "" : "\n")" } } else { - value = LocalizedString("Unknown") + value = localizedString("Unknown") } return [ - self.titleView("\(LocalizedString("Memory")):"), - self.valueView("\(value)"), + self.titleView("\(localizedString("Memory")):"), + self.valueView("\(value)") ] } @@ -263,7 +263,7 @@ class Dashboard: NSScrollView { var value = "" if let gpus = SystemKit.shared.device.info.gpu { for i in 0.. [NSView] { return [ - self.titleView("\(LocalizedString("Disk")):"), - self.valueView("\(SystemKit.shared.device.info.disk?.model ?? SystemKit.shared.device.info.disk?.name ?? LocalizedString("Unknown"))"), + self.titleView("\(localizedString("Disk")):"), + self.valueView("\(SystemKit.shared.device.info.disk?.model ?? SystemKit.shared.device.info.disk?.name ?? localizedString("Unknown"))") ] } private func serialNumber() -> [NSView] { return [ - self.titleView("\(LocalizedString("Serial number")):"), - self.valueView("\(SystemKit.shared.device.serialNumber ?? LocalizedString("Unknown"))"), + self.titleView("\(localizedString("Serial number")):"), + self.valueView("\(SystemKit.shared.device.serialNumber ?? localizedString("Unknown"))") ] } @@ -301,7 +301,7 @@ class Dashboard: NSScrollView { form.unitsStyle = .full form.allowedUnits = [.day, .hour, .minute] - var value = LocalizedString("Unknown") + var value = localizedString("Unknown") if let bootDate = SystemKit.shared.device.bootDate { if let duration = form.string(from: bootDate, to: Date()) { value = duration @@ -312,8 +312,8 @@ class Dashboard: NSScrollView { self.uptimeField = valueView return [ - self.titleView("\(LocalizedString("Uptime")):"), - valueView, + self.titleView("\(localizedString("Uptime")):"), + valueView ] } diff --git a/Stats/Views/Settings.swift b/Stats/Views/Settings.swift index bdc0555a..c226701c 100644 --- a/Stats/Views/Settings.swift +++ b/Stats/Views/Settings.swift @@ -18,11 +18,11 @@ class SettingsWindow: NSWindow, NSWindowDelegate { init() { super.init( - contentRect: NSMakeRect( - NSScreen.main!.frame.width - self.viewController.view.frame.width, - NSScreen.main!.frame.height - self.viewController.view.frame.height, - self.viewController.view.frame.width, - self.viewController.view.frame.height + contentRect: NSRect( + x: NSScreen.main!.frame.width - self.viewController.view.frame.width, + y: NSScreen.main!.frame.height - self.viewController.view.frame.height, + width: self.viewController.view.frame.width, + height: self.viewController.view.frame.height ), styleMask: [.closable, .titled, .miniaturizable, .fullSizeContentView], backing: .buffered, @@ -61,7 +61,7 @@ class SettingsWindow: NSWindow, NSWindowDelegate { public func setModules() { self.viewController.setModules(modules) - if modules.filter({ $0.enabled != false && $0.available != false }).count == 0 { + if modules.filter({ $0.enabled != false && $0.available != false }).isEmpty { self.setIsVisible(true) } } @@ -123,7 +123,7 @@ private class SettingsView: NSView { NotificationCenter.default.addObserver(self, selector: #selector(menuCallback), name: .openModuleSettings, object: nil) - let sidebar = NSVisualEffectView(frame: NSMakeRect(0, 0, self.sidebarWidth, self.frame.height)) + let sidebar = NSVisualEffectView(frame: NSRect(x: 0, y: 0, width: self.sidebarWidth, height: self.frame.height)) sidebar.material = .sidebar sidebar.blendingMode = .behindWindow sidebar.state = .active @@ -141,10 +141,10 @@ private class SettingsView: NSView { self.navigationView.frame = NSRect(x: 0, y: 0, width: self.sidebarWidth, height: navigationHeight) self.navigationView.wantsLayer = true - self.navigationView.addSubview(self.makeButton(4, title: LocalizedString("Open application settings"), image: "settings", action: #selector(openSettings))) - self.navigationView.addSubview(self.makeButton(3, title: LocalizedString("Report a bug"), image: "bug", action: #selector(reportBug))) - self.navigationView.addSubview(self.makeButton(2, title: LocalizedString("Support the application"), image: "donate", action: #selector(donate))) - self.navigationView.addSubview(self.makeButton(1, title: LocalizedString("Close application"), image: "power", action: #selector(closeApp))) + self.navigationView.addSubview(self.makeButton(4, title: localizedString("Open application settings"), image: "settings", action: #selector(openSettings))) + self.navigationView.addSubview(self.makeButton(3, title: localizedString("Report a bug"), image: "bug", action: #selector(reportBug))) + self.navigationView.addSubview(self.makeButton(2, title: localizedString("Support the application"), image: "donate", action: #selector(donate))) + self.navigationView.addSubview(self.makeButton(1, title: localizedString("Close application"), image: "power", action: #selector(closeApp))) self.mainView.frame = NSRect( x: self.sidebarWidth + 1, // separation line @@ -170,8 +170,8 @@ private class SettingsView: NSView { super.draw(dirtyRect) let line = NSBezierPath() - line.move(to: NSMakePoint(self.sidebarWidth, 0)) - line.line(to: NSMakePoint(self.sidebarWidth, self.frame.height)) + line.move(to: NSPoint(x: self.sidebarWidth, y: 0)) + line.line(to: NSPoint(x: self.sidebarWidth, y: self.frame.height)) line.lineWidth = 1 NSColor.black.set() @@ -243,7 +243,12 @@ private class SettingsView: NSView { button.focusRingType = .none let rect = NSRect(x: Int(self.sidebarWidth) - (45*n), y: 0, width: 44, height: 44) - let trackingArea = NSTrackingArea(rect: rect, options: [NSTrackingArea.Options.activeAlways, NSTrackingArea.Options.mouseEnteredAndExited, NSTrackingArea.Options.activeInActiveApp], owner: self, userInfo: ["button": title]) + let trackingArea = NSTrackingArea( + rect: rect, + options: [NSTrackingArea.Options.activeAlways, NSTrackingArea.Options.mouseEnteredAndExited, NSTrackingArea.Options.activeInActiveApp], + owner: self, + userInfo: ["button": title] + ) self.addTrackingArea(trackingArea) return button @@ -281,10 +286,15 @@ private class MenuView: NSView { super.init(frame: NSRect(x: 0, y: self.height*CGFloat(n), width: width, height: self.height)) self.wantsLayer = true self.layer?.backgroundColor = .clear - self.toolTip = title == "Stats" ? LocalizedString("Open application settings") : LocalizedString("Open moduleName settings", title) + self.toolTip = title == "Stats" ? localizedString("Open application settings") : localizedString("Open moduleName settings", title) let rect = NSRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height) - let trackingArea = NSTrackingArea(rect: rect, options: [NSTrackingArea.Options.activeAlways, NSTrackingArea.Options.mouseEnteredAndExited, NSTrackingArea.Options.activeInActiveApp], owner: self, userInfo: ["menu": title]) + let trackingArea = NSTrackingArea( + rect: rect, + options: [NSTrackingArea.Options.activeAlways, NSTrackingArea.Options.mouseEnteredAndExited, NSTrackingArea.Options.activeInActiveApp], + owner: self, + userInfo: ["menu": title] + ) self.addTrackingArea(trackingArea) let imageView = NSImageView() @@ -295,7 +305,7 @@ private class MenuView: NSView { imageView.wantsLayer = true imageView.contentTintColor = .labelColor - let titleView = TextView(frame: NSMakeRect(34, (self.height - 16)/2, 100, 16)) + let titleView = TextView(frame: NSRect(x: 34, y: (self.height - 16)/2, width: 100, height: 16)) titleView.alignment = .natural titleView.textColor = .labelColor titleView.font = NSFont.systemFont(ofSize: 13, weight: .regular) diff --git a/Stats/Views/Update.swift b/Stats/Views/Update.swift index d9bd09d7..5e0b2a30 100644 --- a/Stats/Views/Update.swift +++ b/Stats/Views/Update.swift @@ -20,11 +20,11 @@ class UpdateWindow: NSWindow, NSWindowDelegate { let w = NSScreen.main!.frame.width let h = NSScreen.main!.frame.height super.init( - contentRect: NSMakeRect( - w - self.viewController.view.frame.width, - h - self.viewController.view.frame.height, - self.viewController.view.frame.width, - self.viewController.view.frame.height + contentRect: NSRect( + x: w - self.viewController.view.frame.width, + y: h - self.viewController.view.frame.height, + width: self.viewController.view.frame.width, + height: self.viewController.view.frame.height ), styleMask: [.closable, .titled, .fullSizeContentView], backing: .buffered, @@ -85,7 +85,7 @@ private class UpdateView: NSView { super.init(frame: CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.width, height: frame.height)) self.wantsLayer = true - let sidebar = NSVisualEffectView(frame: NSMakeRect(0, 0, self.frame.width, self.frame.height)) + let sidebar = NSVisualEffectView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height)) sidebar.material = .sidebar sidebar.blendingMode = .behindWindow sidebar.state = .active @@ -104,7 +104,7 @@ private class UpdateView: NSView { let title: NSTextField = TextView(frame: NSRect(x: 0, y: view.frame.height - 20, width: view.frame.width, height: 18)) title.font = NSFont.systemFont(ofSize: 14, weight: .medium) title.alignment = .center - title.stringValue = LocalizedString("New version available") + title.stringValue = localizedString("New version available") let versions: NSGridView = NSGridView(frame: NSRect(x: (view.frame.width-180)/2, y: 54, width: 180, height: 32)) versions.rowSpacing = 0 @@ -112,12 +112,12 @@ private class UpdateView: NSView { versions.xPlacement = .fill let currentVersionTitle: NSTextField = TextView(frame: NSRect(x: 0, y: 0, width: 0, height: 16)) - currentVersionTitle.stringValue = LocalizedString("Current version: ") + currentVersionTitle.stringValue = localizedString("Current version: ") let currentVersion: NSTextField = TextView(frame: NSRect(x: 0, y: 0, width: 0, height: 0)) currentVersion.stringValue = version.current let latestVersionTitle: NSTextField = TextView(frame: NSRect(x: 0, y: 0, width: 0, height: 16)) - latestVersionTitle.stringValue = LocalizedString("Latest version: ") + latestVersionTitle.stringValue = localizedString("Latest version: ") let latestVersion: NSTextField = TextView(frame: NSRect(x: 0, y: 0, width: 0, height: 0)) latestVersion.stringValue = version.latest @@ -125,19 +125,19 @@ private class UpdateView: NSView { versions.addRow(with: [latestVersionTitle, latestVersion]) let closeButton: NSButton = NSButton(frame: NSRect(x: 0, y: 0, width: view.frame.width/2, height: 26)) - closeButton.title = LocalizedString("Close") + closeButton.title = localizedString("Close") closeButton.bezelStyle = .rounded closeButton.action = #selector(self.close) closeButton.target = self let changelogButton: NSButton = NSButton(frame: NSRect(x: 0, y: 0, width: 0, height: 26)) - changelogButton.title = LocalizedString("Changelog") + changelogButton.title = localizedString("Changelog") changelogButton.bezelStyle = .rounded changelogButton.action = #selector(self.changelog) changelogButton.target = self let downloadButton: NSButton = NSButton(frame: NSRect(x: view.frame.width/2, y: 0, width: view.frame.width/2, height: 26)) - downloadButton.title = LocalizedString("Download") + downloadButton.title = localizedString("Download") downloadButton.bezelStyle = .rounded downloadButton.action = #selector(self.download) downloadButton.target = self @@ -163,10 +163,10 @@ private class UpdateView: NSView { let title: NSTextField = TextView(frame: NSRect(x: 0, y: ((view.frame.height - 18)/2), width: view.frame.width, height: 40)) title.font = NSFont.systemFont(ofSize: 14, weight: .light) title.alignment = .center - title.stringValue = LocalizedString("The latest version of Stats installed") + title.stringValue = localizedString("The latest version of Stats installed") let button: NSButton = NSButton(frame: NSRect(x: 0, y: 0, width: view.frame.width, height: 26)) - button.title = LocalizedString("Close") + button.title = localizedString("Close") button.bezelStyle = .rounded button.action = #selector(self.close) button.target = self @@ -192,7 +192,7 @@ private class UpdateView: NSView { let title: NSTextField = TextView(frame: NSRect(x: 0, y: view.frame.height - 28, width: view.frame.width, height: 18)) title.font = NSFont.systemFont(ofSize: 14, weight: .semibold) title.alignment = .center - title.stringValue = LocalizedString("Downloading...") + title.stringValue = localizedString("Downloading...") let progressBar: NSProgressIndicator = NSProgressIndicator() progressBar.frame = NSRect(x: 20, y: 64, width: view.frame.width - 40, height: 22) @@ -207,13 +207,13 @@ private class UpdateView: NSView { state.stringValue = "0%" let closeButton: NSButton = NSButton(frame: NSRect(x: 0, y: 0, width: view.frame.width, height: 26)) - closeButton.title = LocalizedString("Cancel") + closeButton.title = localizedString("Cancel") closeButton.bezelStyle = .rounded closeButton.action = #selector(self.close) closeButton.target = self let installButton: NSButton = NSButton(frame: NSRect(x: view.frame.width/2, y: 0, width: view.frame.width/2, height: 26)) - installButton.title = LocalizedString("Install") + installButton.title = localizedString("Install") installButton.bezelStyle = .rounded installButton.action = #selector(self.install) installButton.target = self diff --git a/Stats/helpers.swift b/Stats/helpers.swift index 897c13e5..dd8f56d0 100644 --- a/Stats/helpers.swift +++ b/Stats/helpers.swift @@ -66,10 +66,10 @@ extension AppDelegate { return } - if IsNewestVersion(currentVersion: prevVersion, latestVersion: currentVersion) { + if isNewestVersion(currentVersion: prevVersion, latestVersion: currentVersion) { _ = showNotification( - title: LocalizedString("Successfully updated"), - subtitle: LocalizedString("Stats was updated to v", currentVersion), + title: localizedString("Successfully updated"), + subtitle: localizedString("Stats was updated to v", currentVersion), id: "updated-from-\(prevVersion)-to-\(currentVersion)" ) } @@ -97,7 +97,7 @@ extension AppDelegate { } internal func checkForNewVersion() { - updater.check() { result, error in + updater.check { result, error in if error != nil { os_log(.error, log: log, "error updater.check(): %s", "\(error!.localizedDescription)") return @@ -113,12 +113,12 @@ extension AppDelegate { os_log(.debug, log: log, "show update window because new version of app found: %s", "\(version.latest)") self.updateNotification.identifier = "new-version-\(version.latest)" - self.updateNotification.title = LocalizedString("New version available") - self.updateNotification.subtitle = LocalizedString("Click to install the new version of Stats") + self.updateNotification.title = localizedString("New version available") + self.updateNotification.subtitle = localizedString("Click to install the new version of Stats") self.updateNotification.soundName = NSUserNotificationDefaultSoundName self.updateNotification.hasActionButton = true - self.updateNotification.actionButtonTitle = LocalizedString("Install") + self.updateNotification.actionButtonTitle = localizedString("Install") self.updateNotification.userInfo = ["url": version.url] NSUserNotificationCenter.default.delegate = self diff --git a/StatsKit/Charts.swift b/StatsKit/Charts.swift index 7643906a..513b5c50 100644 --- a/StatsKit/Charts.swift +++ b/StatsKit/Charts.swift @@ -124,6 +124,7 @@ public class NetworkChartView: NSView { fatalError("init(coder:) has not been implemented") } + // swiftlint:disable function_body_length public override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) diff --git a/StatsKit/SMC.swift b/StatsKit/SMC.swift index f8b2613e..02ada285 100644 --- a/StatsKit/SMC.swift +++ b/StatsKit/SMC.swift @@ -31,6 +31,7 @@ internal enum SMCDataType: String { case FDS = "{fds" } +// swiftlint:disable identifier_name internal enum SMCKeys: UInt8 { case KERNEL_INDEX = 2 case READ_BYTES = 5 @@ -116,21 +117,21 @@ public class SMC { let matchingDictionary: CFMutableDictionary = IOServiceMatching("AppleSMC") result = IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDictionary, &iterator) - if (result != kIOReturnSuccess) { + if result != kIOReturnSuccess { print("Error IOServiceGetMatchingServices(): " + (String(cString: mach_error_string(result), encoding: String.Encoding.ascii) ?? "unknown error")) return } device = IOIteratorNext(iterator) IOObjectRelease(iterator) - if (device == 0) { + if device == 0 { print("Error IOIteratorNext(): " + (String(cString: mach_error_string(result), encoding: String.Encoding.ascii) ?? "unknown error")) return } result = IOServiceOpen(device, mach_task_self_, 0, &conn) IOObjectRelease(device) - if (result != kIOReturnSuccess) { + if result != kIOReturnSuccess { print("Error IOServiceOpen(): " + (String(cString: mach_error_string(result), encoding: String.Encoding.ascii) ?? "unknown error")) return } @@ -138,7 +139,7 @@ public class SMC { deinit { let result = self.close() - if (result != kIOReturnSuccess) { + if result != kIOReturnSuccess { print("error close smc connection: " + (String(cString: mach_error_string(result), encoding: String.Encoding.ascii) ?? "unknown error")) } } @@ -157,7 +158,7 @@ public class SMC { return nil } - if (val.dataSize > 0) { + if val.dataSize > 0 { if val.bytes.first(where: { $0 != 0}) == nil && val.key != "FS! " { return nil } @@ -226,7 +227,7 @@ public class SMC { return nil } - if (val.dataSize > 0) { + if val.dataSize > 0 { if val.bytes.first(where: { $0 != 0}) == nil { return nil } diff --git a/StatsKit/SystemKit.swift b/StatsKit/SystemKit.swift index 9bab9b02..0ad73d2a 100644 --- a/StatsKit/SystemKit.swift +++ b/StatsKit/SystemKit.swift @@ -74,7 +74,7 @@ public struct info_s { } public struct device_s { - public var model: model_s = model_s(name: LocalizedString("Unknown"), year: Calendar.current.component(.year, from: Date()), type: .unknown) + public var model: model_s = model_s(name: localizedString("Unknown"), year: Calendar.current.component(.year, from: Date()), type: .unknown) public var modelIdentifier: String? = nil public var serialNumber: String? = nil public var bootDate: Date? = nil @@ -111,14 +111,14 @@ public class SystemKit { let procInfo = ProcessInfo() let systemVersion = procInfo.operatingSystemVersion - var build = LocalizedString("Unknown") + var build = localizedString("Unknown") let buildArr = procInfo.operatingSystemVersionString.split(separator: "(") if buildArr.indices.contains(1) { build = buildArr[1].replacingOccurrences(of: "Build ", with: "").replacingOccurrences(of: ")", with: "") } let version = systemVersion.majorVersion > 10 ? "\(systemVersion.majorVersion)" : "\(systemVersion.majorVersion).\(systemVersion.minorVersion)" - self.device.os = os_s(name: osDict[version] ?? LocalizedString("Unknown"), version: systemVersion, build: build) + self.device.os = os_s(name: osDict[version] ?? localizedString("Unknown"), version: systemVersion, build: build) self.device.info.cpu = self.getCPUInfo() self.device.info.ram = self.getRamInfo() @@ -180,7 +180,7 @@ public class SystemKit { var sizeOfName = 0 sysctlbyname("machdep.cpu.brand_string", nil, &sizeOfName, nil, 0) - var nameCharts = [CChar](repeating: 0, count: sizeOfName) + var nameCharts = [CChar](repeating: 0, count: sizeOfName) sysctlbyname("machdep.cpu.brand_string", &nameCharts, &sizeOfName, nil, 0) var name = String(cString: nameCharts) if name != "" { @@ -222,7 +222,7 @@ public class SystemKit { var list: [gpu_s] = [] do { if let json = try JSONSerialization.jsonObject(with: Data(res.utf8), options: []) as? [String: Any] { - if let arr = json["SPDisplaysDataType"] as? [[String:Any]] { + if let arr = json["SPDisplaysDataType"] as? [[String: Any]] { for obj in arr { var gpu: gpu_s = gpu_s() @@ -253,10 +253,8 @@ public class SystemKit { let keys: [URLResourceKey] = [.volumeNameKey] let paths = FileManager.default.mountedVolumeURLs(includingResourceValuesForKeys: keys)! if let session = DASessionCreate(kCFAllocatorDefault) { - for url in paths { - if url.pathComponents.count == 1 { - disk = DADiskCreateFromVolumePath(kCFAllocatorDefault, session, url as CFURL) - } + for url in paths where url.pathComponents.count == 1 { + disk = DADiskCreateFromVolumePath(kCFAllocatorDefault, session, url as CFURL) } } @@ -303,7 +301,7 @@ public class SystemKit { if let json = try JSONSerialization.jsonObject(with: Data(res.utf8), options: []) as? [String: Any] { var ram: ram_s = ram_s() - if let obj = json["SPMemoryDataType"] as? [[String:Any]], obj.count > 0 { + if let obj = json["SPMemoryDataType"] as? [[String: Any]], !obj.isEmpty { if let items = obj[0]["_items"] as? [[String: Any]] { for i in 0.. String { - let regex = try! NSRegularExpression(pattern: pattern) - let stringRange = NSRange(location: 0, length: self.utf16.count) - var line = self - - if let searchRange = regex.firstMatch(in: self, options: [], range: stringRange) { - let start = self.index(self.startIndex, offsetBy: searchRange.range.lowerBound) - let end = self.index(self.startIndex, offsetBy: searchRange.range.upperBound) - let value = String(self[start.. String { do { let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive) - let range = NSMakeRange(0, self.count) + let range = NSRange(location: 0, length: self.count) return regex.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: replaceWith) } catch { return self @@ -121,7 +124,7 @@ public extension Double { return NSString(format: "%.\(decimalPlaces)f" as NSString, self) as String } - func rounded(toPlaces places:Int) -> Double { + func rounded(toPlaces places: Int) -> Double { let divisor = pow(10.0, Double(places)) return (self * divisor).rounded() / divisor } @@ -189,7 +192,7 @@ public extension Double { func secondsToHoursMinutesSeconds() -> (Int, Int) { let mins = (self.truncatingRemainder(dividingBy: 3600)) / 60 - return (Int(self / 3600) , Int(mins)) + return (Int(self / 3600), Int(mins)) } func printSecondsToHoursMinutesSeconds(short: Bool = false) -> String { @@ -234,7 +237,7 @@ public extension NSView { } } - func ToggleTitleRow(frame: NSRect, title: String, action: Selector, state: Bool) -> NSView { + func toggleTitleRow(frame: NSRect, title: String, action: Selector, state: Bool) -> NSView { let row: NSView = NSView(frame: frame) let state: NSControl.StateValue = state ? .on : .off @@ -272,7 +275,7 @@ public extension NSView { return row } - func SelectTitleRow(frame: NSRect, title: String, action: Selector, items: [String], selected: String) -> NSView { + func selectTitleRow(frame: NSRect, title: String, action: Selector, items: [String], selected: String) -> NSView { let row: NSView = NSView(frame: frame) let rowTitle: NSTextField = LabelField(frame: NSRect(x: 0, y: (row.frame.height - 16)/2, width: row.frame.width - 52, height: 17), title) @@ -311,31 +314,14 @@ public extension NSView { return row } - func SelectColorRow(frame: NSRect, title: String, action: Selector, items: [String], selected: String) -> NSView { + func selectRow(frame: NSRect, title: String, action: Selector, items: [KeyValue_p], selected: String) -> NSView { let row: NSView = NSView(frame: frame) let rowTitle: NSTextField = LabelField(frame: NSRect(x: 0, y: (row.frame.height - 16)/2, width: row.frame.width - 52, height: 17), title) rowTitle.font = NSFont.systemFont(ofSize: 13, weight: .light) rowTitle.textColor = .textColor - let select: NSPopUpButton = NSPopUpButton(frame: NSRect(x: row.frame.width - 50, y: (row.frame.height-26)/2, width: 50, height: 26)) - select.target = self - select.action = action - - let menu = NSMenu() - items.forEach { (color: String) in - if color.contains("separator") { - menu.addItem(NSMenuItem.separator()) - } else { - let interfaceMenu = NSMenuItem(title: color, action: nil, keyEquivalent: "") - menu.addItem(interfaceMenu) - if selected == color { - interfaceMenu.state = .on - } - } - } - - select.menu = menu + let select: NSPopUpButton = selectView(action: action, items: items, selected: selected) select.sizeToFit() rowTitle.setFrameSize(NSSize(width: row.frame.width - select.frame.width, height: rowTitle.frame.height)) @@ -350,29 +336,7 @@ public extension NSView { return row } - func SelectRow(frame: NSRect, title: String, action: Selector, items: [KeyValue_p], selected: String) -> NSView { - let row: NSView = NSView(frame: frame) - - let rowTitle: NSTextField = LabelField(frame: NSRect(x: 0, y: (row.frame.height - 16)/2, width: row.frame.width - 52, height: 17), title) - rowTitle.font = NSFont.systemFont(ofSize: 13, weight: .light) - rowTitle.textColor = .textColor - - let select: NSPopUpButton = SelectView(action: action, items: items, selected: selected) - select.sizeToFit() - - rowTitle.setFrameSize(NSSize(width: row.frame.width - select.frame.width, height: rowTitle.frame.height)) - select.setFrameOrigin(NSPoint(x: row.frame.width - select.frame.width, y: select.frame.origin.y)) - - row.addSubview(select) - row.addSubview(rowTitle) - - row.widthAnchor.constraint(equalToConstant: row.bounds.width).isActive = true - row.heightAnchor.constraint(equalToConstant: row.bounds.height).isActive = true - - return row - } - - func SelectView(action: Selector, items: [KeyValue_p], selected: String) -> NSPopUpButton { + func selectView(action: Selector, items: [KeyValue_p], selected: String) -> NSPopUpButton { let select: NSPopUpButton = NSPopUpButton(frame: NSRect(x: 0, y: 0, width: 50, height: 26)) select.target = self select.action = action @@ -382,7 +346,7 @@ public extension NSView { if item.key.contains("separator") { menu.addItem(NSMenuItem.separator()) } else { - let interfaceMenu = NSMenuItem(title: LocalizedString(item.value), action: nil, keyEquivalent: "") + let interfaceMenu = NSMenuItem(title: localizedString(item.value), action: nil, keyEquivalent: "") interfaceMenu.representedObject = item.key menu.addItem(interfaceMenu) if selected == item.key { @@ -439,6 +403,7 @@ extension URL { } } +// swiftlint:disable large_tuple extension UInt32 { init(bytes: (UInt8, UInt8, UInt8, UInt8)) { self = UInt32(bytes.0) << 24 | UInt32(bytes.1) << 16 | UInt32(bytes.2) << 8 | UInt32(bytes.3) @@ -472,7 +437,7 @@ public extension NSColor { convenience init(hexString: String, alpha: CGFloat = 1.0) { let hexString: String = hexString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) let scanner = Scanner(string: hexString) - if (hexString.hasPrefix("#")) { + if hexString.hasPrefix("#") { scanner.scanLocation = 1 } var color: UInt32 = 0 @@ -484,17 +449,7 @@ public extension NSColor { let red = CGFloat(r) / 255.0 let green = CGFloat(g) / 255.0 let blue = CGFloat(b) / 255.0 - self.init(red:red, green:green, blue:blue, alpha:alpha) - } - - func toHexString() -> String { - var r:CGFloat = 0 - var g:CGFloat = 0 - var b:CGFloat = 0 - var a:CGFloat = 0 - getRed(&r, green: &g, blue: &b, alpha: &a) - let rgb:Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0 - return String(format:"#%06x", rgb) + self.init(red: red, green: green, blue: blue, alpha: alpha) } } @@ -536,7 +491,7 @@ public final class ScrollableStackView: NSView { scrollView.leftAnchor.constraint(equalTo: self.leftAnchor), scrollView.rightAnchor.constraint(equalTo: self.rightAnchor), scrollView.topAnchor.constraint(equalTo: self.topAnchor), - scrollView.bottomAnchor.constraint(equalTo: self.bottomAnchor), + scrollView.bottomAnchor.constraint(equalTo: self.bottomAnchor) ]) clipView.drawsBackground = false @@ -549,7 +504,7 @@ public final class ScrollableStackView: NSView { NSLayoutConstraint.activate([ stackView.leftAnchor.constraint(equalTo: clipView.leftAnchor), stackView.rightAnchor.constraint(equalTo: clipView.rightAnchor), - stackView.topAnchor.constraint(equalTo: clipView.topAnchor), + stackView.topAnchor.constraint(equalTo: clipView.topAnchor) ]) } @@ -567,21 +522,21 @@ extension NSTextView { if (event.modifierFlags.rawValue & NSEvent.ModifierFlags.deviceIndependentFlagsMask.rawValue) == commandKey { switch event.charactersIgnoringModifiers! { case "x": - if NSApp.sendAction(#selector(NSText.cut(_:)), to:nil, from:self) { return true } + if NSApp.sendAction(#selector(NSText.cut(_:)), to: nil, from: self) { return true } case "c": - if NSApp.sendAction(#selector(NSText.copy(_:)), to:nil, from:self) { return true } + if NSApp.sendAction(#selector(NSText.copy(_:)), to: nil, from: self) { return true } case "v": - if NSApp.sendAction(#selector(NSText.paste(_:)), to:nil, from:self) { return true } + if NSApp.sendAction(#selector(NSText.paste(_:)), to: nil, from: self) { return true } case "z": - if NSApp.sendAction(Selector(("undo:")), to:nil, from:self) { return true } + if NSApp.sendAction(Selector(("undo:")), to: nil, from: self) { return true } case "a": - if NSApp.sendAction(#selector(NSResponder.selectAll(_:)), to:nil, from:self) { return true } + if NSApp.sendAction(#selector(NSResponder.selectAll(_:)), to: nil, from: self) { return true } default: break } } else if (event.modifierFlags.rawValue & NSEvent.ModifierFlags.deviceIndependentFlagsMask.rawValue) == commandShiftKey { if event.charactersIgnoringModifiers == "Z" { - if NSApp.sendAction(Selector(("redo:")), to:nil, from:self) { return true } + if NSApp.sendAction(Selector(("redo:")), to: nil, from: self) { return true } } } } diff --git a/StatsKit/helpers.swift b/StatsKit/helpers.swift index 7716333e..b424dc21 100644 --- a/StatsKit/helpers.swift +++ b/StatsKit/helpers.swift @@ -8,6 +8,7 @@ // // Copyright © 2020 Serhiy Mytrovtsiy. All rights reserved. // +// swiftlint:disable file_length import Cocoa import os.log @@ -196,8 +197,14 @@ public extension NSBezierPath { self.line(to: end) let startEndAngle = atan((end.y - start.y) / (end.x - start.x)) + ((end.x - start.x) < 0 ? CGFloat(Double.pi) : 0) - let arrowLine1 = CGPoint(x: end.x + pointerLineLength * cos(CGFloat(Double.pi) - startEndAngle + arrowAngle), y: end.y - pointerLineLength * sin(CGFloat(Double.pi) - startEndAngle + arrowAngle)) - let arrowLine2 = CGPoint(x: end.x + pointerLineLength * cos(CGFloat(Double.pi) - startEndAngle - arrowAngle), y: end.y - pointerLineLength * sin(CGFloat(Double.pi) - startEndAngle - arrowAngle)) + let arrowLine1 = CGPoint( + x: end.x + pointerLineLength * cos(CGFloat(Double.pi) - startEndAngle + arrowAngle), + y: end.y - pointerLineLength * sin(CGFloat(Double.pi) - startEndAngle + arrowAngle) + ) + let arrowLine2 = CGPoint( + x: end.x + pointerLineLength * cos(CGFloat(Double.pi) - startEndAngle - arrowAngle), + y: end.y - pointerLineLength * sin(CGFloat(Double.pi) - startEndAngle - arrowAngle) + ) self.line(to: arrowLine1) self.move(to: end) @@ -205,7 +212,7 @@ public extension NSBezierPath { } } -public func SeparatorView(_ title: String, origin: NSPoint, width: CGFloat) -> NSView { +public func separatorView(_ title: String, origin: NSPoint, width: CGFloat) -> NSView { let view: NSView = NSView(frame: NSRect(x: origin.x, y: origin.y, width: width, height: 30)) view.heightAnchor.constraint(equalToConstant: view.bounds.height).isActive = true @@ -220,7 +227,7 @@ public func SeparatorView(_ title: String, origin: NSPoint, width: CGFloat) -> N return view } -public func PopupRow(_ view: NSView, n: CGFloat = 0, title: String, value: String) -> (LabelField, ValueField) { +public func popupRow(_ view: NSView, n: CGFloat = 0, title: String, value: String) -> (LabelField, ValueField) { let rowView: NSView = NSView(frame: NSRect(x: 0, y: 22*n, width: view.frame.width, height: 22)) let labelWidth = title.widthOfString(usingFont: .systemFont(ofSize: 13, weight: .regular)) + 4 @@ -240,7 +247,7 @@ public func PopupRow(_ view: NSView, n: CGFloat = 0, title: String, value: Strin return (labelView, valueView) } -public func PopupWithColorRow(_ view: NSView, color: NSColor, n: CGFloat, title: String, value: String) -> ValueField { +public func popupWithColorRow(_ view: NSView, color: NSColor, n: CGFloat, title: String, value: String) -> ValueField { let rowView: NSView = NSView(frame: NSRect(x: 0, y: 22*n, width: view.frame.width, height: 22)) let colorView: NSView = NSView(frame: NSRect(x: 2, y: 5, width: 12, height: 12)) @@ -265,7 +272,7 @@ public func PopupWithColorRow(_ view: NSView, color: NSColor, n: CGFloat, title: return valueView } -public extension Array where Element : Equatable { +public extension Array where Element: Equatable { func allEqual() -> Bool { if let firstElem = first { return !dropFirst().contains { $0 != firstElem } @@ -274,7 +281,7 @@ public extension Array where Element : Equatable { } } -public extension Array where Element : Hashable { +public extension Array where Element: Hashable { func difference(from other: [Element]) -> [Element] { let thisSet = Set(self) let otherSet = Set(other) @@ -282,19 +289,19 @@ public extension Array where Element : Hashable { } } -public func FindAndToggleNSControlState(_ view: NSView?, state: NSControl.StateValue) { +public func findAndToggleNSControlState(_ view: NSView?, state: NSControl.StateValue) { if let control = view?.subviews.first(where: { $0 is NSControl }) { - ToggleNSControlState(control as? NSControl, state: state) + toggleNSControlState(control as? NSControl, state: state) } } -public func FindAndToggleEnableNSControlState(_ view: NSView?, state: Bool) { +public func findAndToggleEnableNSControlState(_ view: NSView?, state: Bool) { if let control = view?.subviews.first(where: { $0 is NSControl }) { - ToggleEnableNSControlState(control as? NSControl, state: state) + toggleEnableNSControlState(control as? NSControl, state: state) } } -public func ToggleNSControlState(_ control: NSControl?, state: NSControl.StateValue) { +public func toggleNSControlState(_ control: NSControl?, state: NSControl.StateValue) { if #available(OSX 10.15, *) { if let checkbox = control as? NSSwitch { checkbox.state = state @@ -306,7 +313,7 @@ public func ToggleNSControlState(_ control: NSControl?, state: NSControl.StateVa } } -public func ToggleEnableNSControlState(_ control: NSControl?, state: Bool) { +public func toggleEnableNSControlState(_ control: NSControl?, state: Bool) { if #available(OSX 10.15, *) { if let checkbox = control as? NSSwitch { checkbox.isEnabled = state @@ -353,7 +360,7 @@ public func syncShell(_ args: String) -> String { return output } -public func IsNewestVersion(currentVersion: String, latestVersion: String) -> Bool { +public func isNewestVersion(currentVersion: String, latestVersion: String) -> Bool { let currentNumber = currentVersion.replacingOccurrences(of: "v", with: "") let latestNumber = latestVersion.replacingOccurrences(of: "v", with: "") @@ -477,7 +484,7 @@ public func getIOParent(_ obj: io_registry_entry_t) -> io_registry_entry_t? { return nil } - if (IOObjectConformsTo(parent, "IOBlockStorageDriver") == 0) { + if IOObjectConformsTo(parent, "IOBlockStorageDriver") == 0 { IOObjectRelease(parent) return nil } @@ -564,7 +571,7 @@ public struct Log: TextOutputStream { } } -public func LocalizedString(_ key: String, _ params: String..., comment: String = "") -> String { +public func localizedString(_ key: String, _ params: String..., comment: String = "") -> String { var string = NSLocalizedString(key, comment: comment) if !params.isEmpty { for (index, param) in params.enumerated() { @@ -582,6 +589,7 @@ extension UnitTemperature { } } +// swiftlint:disable identifier_name public func Temperature(_ value: Double) -> String { let stringUnit: String = Store.shared.string(key: "temperature_units", defaultValue: "system") let formatter = MeasurementFormatter() @@ -603,7 +611,7 @@ public func Temperature(_ value: Double) -> String { return formatter.string(from: measurement) } -public func SysctlByName(_ name: String) -> Int64 { +public func sysctlByName(_ name: String) -> Int64 { var num: Int64 = 0 var size = MemoryLayout.size diff --git a/StatsKit/launchAtLogin.swift b/StatsKit/launchAtLogin.swift index d70e8494..a895334f 100644 --- a/StatsKit/launchAtLogin.swift +++ b/StatsKit/launchAtLogin.swift @@ -20,9 +20,9 @@ public struct LaunchAtLogin { guard let jobs = (SMCopyAllJobDictionaries(kSMDomainUserLaunchd).takeRetainedValue() as? [[String: AnyObject]]) else { return false } - + let job = jobs.first { $0["Label"] as! String == id } - + return job?["OnDemand"] as? Bool ?? false } set { diff --git a/StatsKit/types.swift b/StatsKit/types.swift index 12cacdb6..3e774ba5 100644 --- a/StatsKit/types.swift +++ b/StatsKit/types.swift @@ -13,11 +13,11 @@ import Cocoa public enum AppUpdateInterval: String { case atStart = "At start" - case separator_1 = "separator_1" + case separator1 = "separator_1" case oncePerDay = "Once per day" case oncePerWeek = "Once per week" case oncePerMonth = "Once per month" - case separator_2 = "separator_2" + case separator2 = "separator_2" case never = "Never" } public let AppUpdateIntervals: [KeyValue_t] = [ @@ -38,8 +38,8 @@ public let TemperatureUnits: [KeyValue_t] = [ ] public enum DataSizeBase: String { - case bit = "bit" - case byte = "byte" + case bit + case byte } public let SpeedBase: [KeyValue_t] = [ KeyValue_t(key: "bit", value: "Bit", additional: DataSizeBase.bit), @@ -50,7 +50,7 @@ public let SensorsWidgetMode: [KeyValue_t] = [ KeyValue_t(key: "automatic", value: "Automatic"), KeyValue_t(key: "separator", value: "separator"), KeyValue_t(key: "oneRow", value: "One row"), - KeyValue_t(key: "twoRows", value: "Two rows"), + KeyValue_t(key: "twoRows", value: "Two rows") ] public let SpeedPictogram: [KeyValue_t] = [ @@ -58,7 +58,7 @@ public let SpeedPictogram: [KeyValue_t] = [ KeyValue_t(key: "separator", value: "separator"), KeyValue_t(key: "dots", value: "Dots"), KeyValue_t(key: "arrows", value: "Arrows"), - KeyValue_t(key: "chars", value: "Characters"), + KeyValue_t(key: "chars", value: "Characters") ] public let BatteryAdditionals: [KeyValue_t] = [ @@ -67,12 +67,12 @@ public let BatteryAdditionals: [KeyValue_t] = [ KeyValue_t(key: "percentage", value: "Percentage"), KeyValue_t(key: "time", value: "Time"), KeyValue_t(key: "percentageAndTime", value: "Percentage and time"), - KeyValue_t(key: "timeAndPercentage", value: "Time and percentage"), + KeyValue_t(key: "timeAndPercentage", value: "Time and percentage") ] public let ShortLong: [KeyValue_t] = [ KeyValue_t(key: "short", value: "Short"), - KeyValue_t(key: "long", value: "Long"), + KeyValue_t(key: "long", value: "Long") ] public let ReaderUpdateIntervals: [Int] = [1, 2, 3, 5, 10, 15, 30] @@ -81,7 +81,7 @@ public let NumbersOfProcesses: [Int] = [0, 3, 5, 8, 10, 15] public typealias Bandwidth = (upload: Int64, download: Int64) public let NetworkReaders: [KeyValue_t] = [ KeyValue_t(key: "interface", value: "Interface based"), - KeyValue_t(key: "process", value: "Processes based"), + KeyValue_t(key: "process", value: "Processes based") ] public struct Color: KeyValue_p, Equatable { @@ -98,12 +98,12 @@ extension Color: CaseIterable { public static var utilization: Color { return Color(key: "utilization", value: "Based on utilization", additional: NSColor.black) } public static var pressure: Color { return Color(key: "pressure", value: "Based on pressure", additional: NSColor.black) } - public static var separator_1: Color { return Color(key: "separator_1", value: "separator_1", additional: NSColor.black) } + public static var separator1: Color { return Color(key: "separator_1", value: "separator_1", additional: NSColor.black) } public static var systemAccent: Color { return Color(key: "system", value: "System accent", additional: NSColor.black) } public static var monochrome: Color { return Color(key: "monochrome", value: "Monochrome accent", additional: NSColor.black) } - public static var separator_2: Color { return Color(key: "separator_2", value: "separator_2", additional: NSColor.black) } + public static var separator2: Color { return Color(key: "separator_2", value: "separator_2", additional: NSColor.black) } public static var clear: Color { return Color(key: "clear", value: "Clear", additional: NSColor.clear) } public static var white: Color { return Color(key: "white", value: "White", additional: NSColor.white) } @@ -137,8 +137,8 @@ extension Color: CaseIterable { } } public static var allCases: [Color] { - return [.utilization, .pressure, separator_1, - .systemAccent, .monochrome, separator_2, + return [.utilization, .pressure, separator1, + .systemAccent, .monochrome, separator2, .clear, .white, .black, .gray, .secondGray, .darkGray, .lightGray, .red, .secondRed, .green, .secondGreen, .blue, .secondBlue, .yellow, .secondYellow, .orange, .secondOrange, .purple, .secondPurple, .brown, .secondBrown, diff --git a/StatsKit/updater.swift b/StatsKit/updater.swift index dd259633..a6b11c3d 100644 --- a/StatsKit/updater.swift +++ b/StatsKit/updater.swift @@ -63,7 +63,7 @@ public class macAppUpdater { return } - fetchLastVersion() { result, error in + fetchLastVersion { result, error in guard error == nil else { completionHandler(nil, error) return @@ -76,7 +76,7 @@ public class macAppUpdater { let downloadURL: String = result![1] let lastVersion: String = result![0] - let newVersion: Bool = IsNewestVersion(currentVersion: self.currentVersion, latestVersion: lastVersion) + let newVersion: Bool = isNewestVersion(currentVersion: self.currentVersion, latestVersion: lastVersion) self.latest = version_s(current: self.currentVersion, latest: lastVersion, newest: newVersion, url: downloadURL) completionHandler(self.latest, nil) @@ -89,7 +89,7 @@ public class macAppUpdater { return } - URLSession.shared.dataTask(with: url) { data, response, error in + URLSession.shared.dataTask(with: url) { data, _, error in guard let data = data, error == nil else { return } do { @@ -115,7 +115,7 @@ public class macAppUpdater { } public func download(_ url: URL, progressHandler: @escaping (_ progress: Progress) -> Void = {_ in }, doneHandler: @escaping (_ path: String) -> Void = {_ in }) { - let downloadTask = URLSession.shared.downloadTask(with: url) { urlOrNil, responseOrNil, errorOrNil in + let downloadTask = URLSession.shared.downloadTask(with: url) { urlOrNil, _, _ in guard let fileURL = urlOrNil else { return } do { let downloadsURL = try FileManager.default.url(for: .downloadsDirectory, in: .userDomainMask, appropriateFor: nil, create: false) @@ -123,14 +123,14 @@ public class macAppUpdater { self.copyFile(from: fileURL, to: destinationURL) { (path, error) in if error != nil { - print ("copy file error: \(error ?? "copy error")") + print("copy file error: \(error ?? "copy error")") return } doneHandler(path) } } catch { - print ("file error: \(error)") + print("file error: \(error)") } } @@ -176,8 +176,8 @@ public class macAppUpdater { var toPath = to let fileName = (URL(fileURLWithPath: to.absoluteString)).lastPathComponent let fileExt = (URL(fileURLWithPath: to.absoluteString)).pathExtension - var fileNameWithotSuffix : String! - var newFileName : String! + var fileNameWithotSuffix: String! + var newFileName: String! var counter = 0 if fileName.hasSuffix(fileExt) {