feat: initialized swiftlint and fixed warnings and errors

This commit is contained in:
Serhiy Mytrovtsiy
2021-05-22 14:58:20 +02:00
parent e768a42e12
commit 0c7f5699ed
59 changed files with 657 additions and 563 deletions

44
.swiftlint.yml Normal file
View File

@@ -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

View File

@@ -77,7 +77,7 @@ public class BarChart: WidgetWrapper {
} }
if preview { if preview {
if self.value.count == 0 { if self.value.isEmpty {
self.value = [0.72, 0.38] self.value = [0.72, 0.38]
} }
self.setFrameSize(NSSize(width: 36, height: self.frame.size.height)) 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") fatalError("init(coder:) has not been implemented")
} }
// swiftlint:disable function_body_length
public override func draw(_ dirtyRect: NSRect) { public override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect) super.draw(dirtyRect)
@@ -100,28 +101,20 @@ public class BarChart: WidgetWrapper {
switch self.value.count { switch self.value.count {
case 0, 1: case 0, 1:
width += 10 + (offset*2) width += 10 + (offset*2)
break
case 2: case 2:
width += 22 width += 22
break
case 3...4: // 3,4 case 3...4: // 3,4
width += 30 width += 30
break
case 5...8: // 5,6,7,8 case 5...8: // 5,6,7,8
width += 40 width += 40
break
case 9...12: // 9..12 case 9...12: // 9..12
width += 50 width += 50
break
case 13...16: // 13..16 case 13...16: // 13..16
width += 76 width += 76
break
case 17...32: // 17..32 case 17...32: // 17..32
width += 84 width += 84
break
default: // > 32 default: // > 32
width += 118 width += 118
break
} }
if self.labelState { if self.labelState {
@@ -144,7 +137,7 @@ public class BarChart: WidgetWrapper {
yMargin += letterHeight yMargin += letterHeight
} }
width = width + letterWidth + Constants.Widget.spacing width += letterWidth + Constants.Widget.spacing
x = letterWidth + Constants.Widget.spacing x = letterWidth + Constants.Widget.spacing
} }
@@ -248,32 +241,32 @@ public class BarChart: WidgetWrapper {
height: height height: height
)) ))
view.addSubview(ToggleTitleRow( view.addSubview(toggleTitleRow(
frame: NSRect(x: 0, y: (rowHeight + Constants.Settings.margin) * 3, width: view.frame.width, height: rowHeight), 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), action: #selector(toggleLabel),
state: self.labelState 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), 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), action: #selector(toggleBox),
state: self.boxState state: self.boxState
) )
view.addSubview(self.boxSettingsView!) 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), 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), action: #selector(toggleFrame),
state: self.frameState state: self.frameState
) )
view.addSubview(self.frameSettingsView!) 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), 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), action: #selector(toggleColor),
items: self.colors, items: self.colors,
selected: self.colorState.key 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) Store.shared.set(key: "\(self.title)_\(self.type.rawValue)_box", value: self.boxState)
if self.frameState { if self.frameState {
FindAndToggleNSControlState(self.frameSettingsView, state: .off) findAndToggleNSControlState(self.frameSettingsView, state: .off)
self.frameState = false self.frameState = false
Store.shared.set(key: "\(self.title)_\(self.type.rawValue)_frame", value: self.frameState) 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) Store.shared.set(key: "\(self.title)_\(self.type.rawValue)_frame", value: self.frameState)
if self.boxState { if self.boxState {
FindAndToggleNSControlState(self.boxSettingsView, state: .off) findAndToggleNSControlState(self.boxSettingsView, state: .off)
self.boxState = false self.boxState = false
Store.shared.set(key: "\(self.title)_\(self.type.rawValue)_box", value: self.boxState) Store.shared.set(key: "\(self.title)_\(self.type.rawValue)_box", value: self.boxState)
} }

View File

@@ -56,6 +56,7 @@ public class BatterykWidget: WidgetWrapper {
fatalError("init(coder:) has not been implemented") fatalError("init(coder:) has not been implemented")
} }
// swiftlint:disable function_body_length
public override func draw(_ dirtyRect: NSRect) { public override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect) 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+1, y: batteryCenter.y+1.5),
CGPoint(x: batteryCenter.x+3, y: max.y), // top CGPoint(x: batteryCenter.x+3, y: max.y), // top
CGPoint(x: min.x, y: batteryCenter.y-1.5), 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 { } else {
let iconSize: CGSize = CGSize(width: 9, height: batterySize.height + 2) 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-4, y: batteryCenter.y + 0.5),
CGPoint(x: batteryCenter.x-1.5, y: batteryCenter.y - 2.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 height: height
)) ))
view.addSubview(SelectRow( view.addSubview(selectRow(
frame: NSRect(x: 0, y: (rowHeight + Constants.Settings.margin) * 2, width: view.frame.width, height: rowHeight), 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), action: #selector(toggleAdditional),
items: BatteryAdditionals, items: BatteryAdditionals,
selected: self.additional 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), 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), action: #selector(toggleHideAdditionalWhenFull),
state: self.hideAdditionalWhenFull 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), 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), action: #selector(toggleColor),
state: self.colorState state: self.colorState
)) ))

View File

@@ -96,6 +96,7 @@ public class LineChart: WidgetWrapper {
fatalError("init(coder:) has not been implemented") fatalError("init(coder:) has not been implemented")
} }
// swiftlint:disable function_body_length
public override func draw(_ dirtyRect: NSRect) { public override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect) super.draw(dirtyRect)
@@ -140,7 +141,7 @@ public class LineChart: WidgetWrapper {
str.draw(with: rect) str.draw(with: rect)
yMargin += letterHeight yMargin += letterHeight
} }
width = width + letterWidth + Constants.Widget.spacing width += letterWidth + Constants.Widget.spacing
x = letterWidth + Constants.Widget.spacing x = letterWidth + Constants.Widget.spacing
} }
@@ -208,10 +209,10 @@ public class LineChart: WidgetWrapper {
} }
public override func setValues(_ values: [value_t]) { 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 let end = self.chart.points.count
if historyValues.count != 0 { if !historyValues.isEmpty {
self.chart.points.replaceSubrange(end-historyValues.count...end-1, with: historyValues) self.chart.points.replaceSubrange(end-historyValues.count...end-1, with: historyValues)
} }
@@ -255,47 +256,47 @@ public class LineChart: WidgetWrapper {
height: height height: height
)) ))
view.addSubview(ToggleTitleRow( view.addSubview(toggleTitleRow(
frame: NSRect(x: 0, y: (rowHeight + Constants.Settings.margin) * 5, width: view.frame.width, height: rowHeight), 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), action: #selector(toggleLabel),
state: self.labelState 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), 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), action: #selector(toggleValue),
state: self.valueState 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), 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), action: #selector(toggleBox),
state: self.boxState state: self.boxState
) )
view.addSubview(self.boxSettingsView!) 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), 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), action: #selector(toggleFrame),
state: self.frameState state: self.frameState
) )
view.addSubview(self.frameSettingsView!) 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), 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), action: #selector(toggleColor),
items: self.colors, items: self.colors,
selected: self.colorState.key 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), 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), action: #selector(toggleValueColor),
state: self.valueColorState state: self.valueColorState
)) ))
@@ -326,7 +327,7 @@ public class LineChart: WidgetWrapper {
Store.shared.set(key: "\(self.title)_\(self.type.rawValue)_box", value: self.boxState) Store.shared.set(key: "\(self.title)_\(self.type.rawValue)_box", value: self.boxState)
if self.frameState { if self.frameState {
FindAndToggleNSControlState(self.frameSettingsView, state: .off) findAndToggleNSControlState(self.frameSettingsView, state: .off)
self.frameState = false self.frameState = false
Store.shared.set(key: "\(self.title)_\(self.type.rawValue)_frame", value: self.frameState) 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) Store.shared.set(key: "\(self.title)_\(self.type.rawValue)_frame", value: self.frameState)
if self.boxState { if self.boxState {
FindAndToggleNSControlState(self.boxSettingsView, state: .off) findAndToggleNSControlState(self.boxSettingsView, state: .off)
self.boxState = false self.boxState = false
Store.shared.set(key: "\(self.title)_\(self.type.rawValue)_box", value: self.boxState) Store.shared.set(key: "\(self.title)_\(self.type.rawValue)_box", value: self.boxState)
} }

View File

@@ -110,9 +110,9 @@ public class MemoryWidget: WidgetWrapper {
height: height height: height
)) ))
view.addSubview(ToggleTitleRow( view.addSubview(toggleTitleRow(
frame: NSRect(x: 0, y: (rowHeight + Constants.Settings.margin) * 0, width: view.frame.width, height: rowHeight), 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), action: #selector(toggleOrder),
state: self.orderReversedState state: self.orderReversedState
)) ))

View File

@@ -177,16 +177,16 @@ public class Mini: WidgetWrapper {
height: height height: height
)) ))
view.addSubview(ToggleTitleRow( view.addSubview(toggleTitleRow(
frame: NSRect(x: 0, y: rowHeight + Constants.Settings.margin, width: view.frame.width, height: rowHeight), frame: NSRect(x: 0, y: rowHeight + Constants.Settings.margin, width: view.frame.width, height: rowHeight),
title: LocalizedString("Label"), title: localizedString("Label"),
action: #selector(toggleLabel), action: #selector(toggleLabel),
state: self.labelState 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), 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), action: #selector(toggleColor),
items: self.colors, items: self.colors,
selected: self.colorState.key selected: self.colorState.key

View File

@@ -128,17 +128,17 @@ public class NetworkChart: WidgetWrapper {
height: height height: height
)) ))
self.boxSettingsView = ToggleTitleRow( self.boxSettingsView = toggleTitleRow(
frame: NSRect(x: 0, y: (rowHeight + Constants.Settings.margin) * 1, width: view.frame.width, height: rowHeight), 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), action: #selector(toggleBox),
state: self.boxState state: self.boxState
) )
view.addSubview(self.boxSettingsView!) 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), 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), action: #selector(toggleFrame),
state: self.frameState state: self.frameState
) )
@@ -158,7 +158,7 @@ public class NetworkChart: WidgetWrapper {
Store.shared.set(key: "\(self.title)_\(self.type.rawValue)_box", value: self.boxState) Store.shared.set(key: "\(self.title)_\(self.type.rawValue)_box", value: self.boxState)
if self.frameState { if self.frameState {
FindAndToggleNSControlState(self.frameSettingsView, state: .off) findAndToggleNSControlState(self.frameSettingsView, state: .off)
self.frameState = false self.frameState = false
Store.shared.set(key: "\(self.title)_\(self.type.rawValue)_frame", value: self.frameState) 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) Store.shared.set(key: "\(self.title)_\(self.type.rawValue)_frame", value: self.frameState)
if self.boxState { if self.boxState {
FindAndToggleNSControlState(self.boxSettingsView, state: .off) findAndToggleNSControlState(self.boxSettingsView, state: .off)
self.boxState = false self.boxState = false
Store.shared.set(key: "\(self.title)_\(self.type.rawValue)_box", value: self.boxState) Store.shared.set(key: "\(self.title)_\(self.type.rawValue)_box", value: self.boxState)
} }

View File

@@ -105,9 +105,9 @@ public class PieChart: WidgetWrapper {
height: height height: height
)) ))
view.addSubview(ToggleTitleRow( view.addSubview(toggleTitleRow(
frame: NSRect(x: 0, y: 0, width: view.frame.width, height: rowHeight), frame: NSRect(x: 0, y: 0, width: view.frame.width, height: rowHeight),
title: LocalizedString("Label"), title: localizedString("Label"),
action: #selector(toggleLabel), action: #selector(toggleLabel),
state: self.labelState state: self.labelState
)) ))

View File

@@ -63,7 +63,7 @@ public class SensorsWidget: WidgetWrapper {
public override func draw(_ dirtyRect: NSRect) { public override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect) super.draw(dirtyRect)
guard self.values.count != 0 else { guard !self.values.isEmpty else {
self.setWidth(1) self.setWidth(1)
return return
} }
@@ -186,17 +186,17 @@ public class SensorsWidget: WidgetWrapper {
public override func settings(width: CGFloat) -> NSView { public override func settings(width: CGFloat) -> NSView {
let view = SettingsContainerView(width: width) 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), 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), action: #selector(changeMode),
items: SensorsWidgetMode, items: SensorsWidgetMode,
selected: self.modeState selected: self.modeState
)) ))
view.addArrangedSubview(ToggleTitleRow( view.addArrangedSubview(toggleTitleRow(
frame: NSRect(x: 0, y: 0, width: view.frame.width, height: Constants.Settings.row), 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), action: #selector(toggleSize),
state: self.fixedSizeState state: self.fixedSizeState
)) ))

View File

@@ -84,7 +84,6 @@ public class SpeedWidget: WidgetWrapper {
default: default:
x = 0 x = 0
width = 0 width = 0
break
} }
if self.valueState { if self.valueState {
@@ -197,7 +196,7 @@ public class SpeedWidget: WidgetWrapper {
str.draw(with: rect) str.draw(with: rect)
} }
if self.symbols.count > 0 { if !self.symbols.isEmpty {
let uploadAttributes = [ let uploadAttributes = [
NSAttributedString.Key.font: NSFont.systemFont(ofSize: 9, weight: .regular), NSAttributedString.Key.font: NSFont.systemFont(ofSize: 9, weight: .regular),
NSAttributedString.Key.foregroundColor: uploadValue >= 1_024 ? NSColor.red : NSColor.textColor, NSAttributedString.Key.foregroundColor: uploadValue >= 1_024 ? NSColor.red : NSColor.textColor,
@@ -220,25 +219,25 @@ public class SpeedWidget: WidgetWrapper {
height: height height: height
)) ))
view.addSubview(SelectRow( view.addSubview(selectRow(
frame: NSRect(x: 0, y: (rowHeight+Constants.Settings.margin) * 2, width: view.frame.width, height: rowHeight), 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), action: #selector(toggleIcon),
items: SpeedPictogram, items: SpeedPictogram,
selected: self.icon selected: self.icon
)) ))
view.addSubview(SelectRow( view.addSubview(selectRow(
frame: NSRect(x: 0, y: rowHeight + Constants.Settings.margin, width: view.frame.width, height: rowHeight), frame: NSRect(x: 0, y: rowHeight + Constants.Settings.margin, width: view.frame.width, height: rowHeight),
title: LocalizedString("Base"), title: localizedString("Base"),
action: #selector(toggleBase), action: #selector(toggleBase),
items: SpeedBase, items: SpeedBase,
selected: self.baseValue selected: self.baseValue
)) ))
view.addSubview(ToggleTitleRow( view.addSubview(toggleTitleRow(
frame: NSRect(x: 0, y: 0, width: view.frame.width, height: rowHeight), frame: NSRect(x: 0, y: 0, width: view.frame.width, height: rowHeight),
title: LocalizedString("Value"), title: localizedString("Value"),
action: #selector(toggleValue), action: #selector(toggleValue),
state: self.valueState state: self.valueState
)) ))

View File

@@ -24,7 +24,7 @@ public protocol Module_p {
public struct module_c { public struct module_c {
public var name: String = "" public var name: String = ""
public var icon: NSImage? = nil public var icon: NSImage?
var defaultState: Bool = false var defaultState: Bool = false
var defaultWidget: widget_t = .unknown var defaultWidget: widget_t = .unknown
@@ -43,7 +43,7 @@ public struct module_c {
} }
if let widgetsDict = dict["Widgets"] as? NSDictionary { if let widgetsDict = dict["Widgets"] as? NSDictionary {
var list: [String : Int] = [:] var list: [String: Int] = [:]
self.widgetsConfig = widgetsDict self.widgetsConfig = widgetsDict
for widgetName in widgetsDict.allKeys { 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(listenForPopupToggle), name: .togglePopup, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(listenForToggleWidget), name: .toggleWidget, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(listenForToggleWidget), name: .toggleWidget, object: nil)
// swiftlint:disable empty_count
if self.config.widgetsConfig.count != 0 { if self.config.widgetsConfig.count != 0 {
self.initWidgets() self.initWidgets()
} else { } else {
@@ -303,12 +304,12 @@ open class Module: Module_p {
guard let name = notification.userInfo?["module"] as? String, name == self.config.name else { guard let name = notification.userInfo?["module"] as? String, name == self.config.name else {
return return
} }
let count = self.widgets.filter({ $0.isActive }).count let isEmpty = self.widgets.filter({ $0.isActive }).isEmpty
var state = self.enabled var state = self.enabled
if count == 0 && self.enabled { if isEmpty && self.enabled {
state = false state = false
} else if count != 0 && !self.enabled { } else if !isEmpty && !self.enabled {
state = true state = true
} }

View File

@@ -25,7 +25,12 @@ internal class PopupWindow: NSWindow, NSWindowDelegate {
self.viewController.visibilityCallback = visibilityCallback self.viewController.visibilityCallback = visibilityCallback
super.init( 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], styleMask: [.titled, .fullSizeContentView],
backing: .buffered, backing: .buffered,
defer: true defer: true
@@ -240,7 +245,7 @@ internal class HeaderView: NSStackView {
activity.isBordered = false activity.isBordered = false
activity.action = #selector(openActivityMonitor) activity.action = #selector(openActivityMonitor)
activity.target = self activity.target = self
activity.toolTip = LocalizedString("Open Activity Monitor") activity.toolTip = localizedString("Open Activity Monitor")
activity.focusRingType = .none activity.focusRingType = .none
self.activityButton = activity self.activityButton = activity
@@ -268,7 +273,7 @@ internal class HeaderView: NSStackView {
settings.isBordered = false settings.isBordered = false
settings.action = #selector(openSettings) settings.action = #selector(openSettings)
settings.target = self settings.target = self
settings.toolTip = LocalizedString("Open module settings") settings.toolTip = localizedString("Open module settings")
settings.focusRingType = .none settings.focusRingType = .none
self.settingsButton = settings self.settingsButton = settings
@@ -279,7 +284,7 @@ internal class HeaderView: NSStackView {
NSLayoutConstraint.activate([ NSLayoutConstraint.activate([
title.widthAnchor.constraint( title.widthAnchor.constraint(
equalToConstant: self.frame.width - activity.intrinsicContentSize.width - settings.intrinsicContentSize.width equalToConstant: self.frame.width - activity.intrinsicContentSize.width - settings.intrinsicContentSize.width
), )
]) ])
} }
@@ -296,8 +301,8 @@ internal class HeaderView: NSStackView {
NSColor.gridColor.set() NSColor.gridColor.set()
let line = NSBezierPath() let line = NSBezierPath()
line.move(to: NSMakePoint(0, 0)) line.move(to: NSPoint(x: 0, y: 0))
line.line(to: NSMakePoint(self.frame.width, 0)) line.line(to: NSPoint(x: self.frame.width, y: 0))
line.lineWidth = 1 line.lineWidth = 1
line.stroke() line.stroke()
} }
@@ -326,11 +331,11 @@ internal class HeaderView: NSStackView {
public func setCloseButton(_ state: Bool) { public func setCloseButton(_ state: Bool) {
if state && !self.isCloseAction { if state && !self.isCloseAction {
self.activityButton?.image = Bundle(for: type(of: self)).image(forResource: "close")! 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 self.isCloseAction = true
} else if !state && self.isCloseAction { } else if !state && self.isCloseAction {
self.activityButton?.image = Bundle(for: type(of: self)).image(forResource: "chart")! 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 self.isCloseAction = false
} }
} }

View File

@@ -15,36 +15,36 @@ import os.log
import StatsKit import StatsKit
public protocol value_t { public protocol value_t {
var widget_value: Double { get } var widgetValue: Double { get }
} }
public protocol Reader_p { public protocol Reader_p {
var optional: Bool { get } var optional: Bool { get }
var popup: Bool { get } var popup: Bool { get }
func setup() -> Void func setup()
func read() -> Void func read()
func terminate() -> Void func terminate()
func getValue<T>() -> T func getValue<T>() -> T
func getHistory() -> [value_t] func getHistory() -> [value_t]
func start() -> Void func start()
func pause() -> Void func pause()
func stop() -> Void func stop()
func lock() -> Void func lock()
func unlock() -> Void func unlock()
func initStoreValues(title: String) -> Void func initStoreValues(title: String)
func setInterval(_ value: Int) -> Void func setInterval(_ value: Int)
} }
public protocol ReaderInternal_p { public protocol ReaderInternal_p {
associatedtype T associatedtype T
var value: T? { get } var value: T? { get }
func read() -> Void func read()
} }
open class Reader<T>: ReaderInternal_p { open class Reader<T>: ReaderInternal_p {

View File

@@ -13,7 +13,7 @@ import Cocoa
import StatsKit import StatsKit
public protocol Settings_p: NSView { public protocol Settings_p: NSView {
var toggleCallback: () -> () { get set } var toggleCallback: () -> Void { get set }
} }
public protocol Settings_v: NSView { public protocol Settings_v: NSView {
@@ -22,7 +22,7 @@ public protocol Settings_v: NSView {
} }
open class Settings: NSView, Settings_p { open class Settings: NSView, Settings_p {
public var toggleCallback: () -> () = {} public var toggleCallback: () -> Void = {}
private let headerHeight: CGFloat = 42 private let headerHeight: CGFloat = 42
@@ -177,7 +177,7 @@ open class Settings: NSView, Settings_p {
NSLayoutConstraint.activate([ NSLayoutConstraint.activate([
container.heightAnchor.constraint(equalToConstant: container.frame.height), 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([ 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([ 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 let name = notification.userInfo?["module"] as? String {
if name == self.config.pointee.name { if name == self.config.pointee.name {
if let state = notification.userInfo?["state"] as? Bool { 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) self.moduleSettingsContainer?.addSubview(settingsView)
NSLayoutConstraint.activate([ 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?.cornerRadius = 2
self.layer?.borderColor = self.widget.pointee.isActive ? NSColor.systemBlue.cgColor : NSColor(hexString: "#dddddd").cgColor self.layer?.borderColor = self.widget.pointee.isActive ? NSColor.systemBlue.cgColor : NSColor(hexString: "#dddddd").cgColor
self.layer?.borderWidth = 1 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.orientation = .horizontal
self.distribution = .fillProportionally 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 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) self?.addTrackingArea(trackingArea)
} }
@@ -350,7 +355,7 @@ internal class WidgetPreview: NSStackView {
)) ))
NSLayoutConstraint.activate([ 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) 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 { private func initButton() -> NSView {
let size: CGFloat = Constants.Widget.height let size: CGFloat = Constants.Widget.height
let button = NSButton(frame: NSRect(x: 0, y: 0, width: size, height: size)) let button = NSButton(frame: NSRect(x: 0, y: 0, width: size, height: size))
button.title = LocalizedString("Open widget settings") button.title = localizedString("Open widget settings")
button.toolTip = LocalizedString("Open widget settings") button.toolTip = localizedString("Open widget settings")
button.bezelStyle = .regularSquare button.bezelStyle = .regularSquare
if let image = Bundle(for: type(of: self)).image(forResource: "widget_settings") { if let image = Bundle(for: type(of: self)).image(forResource: "widget_settings") {
button.image = image button.image = image
@@ -374,7 +379,7 @@ internal class WidgetPreview: NSStackView {
button.focusRingType = .none button.focusRingType = .none
NSLayoutConstraint.activate([ NSLayoutConstraint.activate([
button.widthAnchor.constraint(equalToConstant: button.frame.width), button.widthAnchor.constraint(equalToConstant: button.frame.width)
]) ])
return button return button
@@ -387,7 +392,7 @@ internal class WidgetPreview: NSStackView {
separator.layer?.backgroundColor = NSColor(hexString: "#dddddd").cgColor separator.layer?.backgroundColor = NSColor(hexString: "#dddddd").cgColor
NSLayoutConstraint.activate([ NSLayoutConstraint.activate([
separator.heightAnchor.constraint(equalToConstant: Constants.Widget.height), separator.heightAnchor.constraint(equalToConstant: Constants.Widget.height)
]) ])
return separator return separator

View File

@@ -37,43 +37,33 @@ public enum widget_t: String {
case .mini: case .mini:
preview = Mini(title: module, config: widgetConfig, preview: true) preview = Mini(title: module, config: widgetConfig, preview: true)
item = Mini(title: module, config: widgetConfig, preview: false) item = Mini(title: module, config: widgetConfig, preview: false)
break
case .lineChart: case .lineChart:
preview = LineChart(title: module, config: widgetConfig, preview: true) preview = LineChart(title: module, config: widgetConfig, preview: true)
item = LineChart(title: module, config: widgetConfig, preview: false) item = LineChart(title: module, config: widgetConfig, preview: false)
break
case .barChart: case .barChart:
preview = BarChart(title: module, config: widgetConfig, preview: true) preview = BarChart(title: module, config: widgetConfig, preview: true)
item = BarChart(title: module, config: widgetConfig, preview: false) item = BarChart(title: module, config: widgetConfig, preview: false)
break
case .pieChart: case .pieChart:
preview = PieChart(title: module, config: widgetConfig, preview: true) preview = PieChart(title: module, config: widgetConfig, preview: true)
item = PieChart(title: module, config: widgetConfig, preview: false) item = PieChart(title: module, config: widgetConfig, preview: false)
break
case .networkChart: case .networkChart:
preview = NetworkChart(title: module, config: widgetConfig, preview: true) preview = NetworkChart(title: module, config: widgetConfig, preview: true)
item = NetworkChart(title: module, config: widgetConfig, preview: false) item = NetworkChart(title: module, config: widgetConfig, preview: false)
break
case .speed: case .speed:
preview = SpeedWidget(title: module, config: widgetConfig, preview: true) preview = SpeedWidget(title: module, config: widgetConfig, preview: true)
item = SpeedWidget(title: module, config: widgetConfig, preview: false) item = SpeedWidget(title: module, config: widgetConfig, preview: false)
break
case .battery: case .battery:
preview = BatterykWidget(title: module, config: widgetConfig, preview: true) preview = BatterykWidget(title: module, config: widgetConfig, preview: true)
item = BatterykWidget(title: module, config: widgetConfig, preview: false) item = BatterykWidget(title: module, config: widgetConfig, preview: false)
break
case .sensors: case .sensors:
preview = SensorsWidget(title: module, config: widgetConfig, preview: true) preview = SensorsWidget(title: module, config: widgetConfig, preview: true)
item = SensorsWidget(title: module, config: widgetConfig, preview: false) item = SensorsWidget(title: module, config: widgetConfig, preview: false)
break
case .memory: case .memory:
preview = MemoryWidget(title: module, config: widgetConfig, preview: true) preview = MemoryWidget(title: module, config: widgetConfig, preview: true)
item = MemoryWidget(title: module, config: widgetConfig, preview: false) item = MemoryWidget(title: module, config: widgetConfig, preview: false)
break
case .label: case .label:
preview = Label(title: module, config: widgetConfig, preview: true) preview = Label(title: module, config: widgetConfig, preview: true)
item = Label(title: module, config: widgetConfig, preview: false) item = Label(title: module, config: widgetConfig, preview: false)
break
default: break default: break
} }
@@ -86,17 +76,17 @@ public enum widget_t: String {
public func name() -> String { public func name() -> String {
switch self { switch self {
case .mini: return LocalizedString("Mini widget") case .mini: return localizedString("Mini widget")
case .lineChart: return LocalizedString("Line chart widget") case .lineChart: return localizedString("Line chart widget")
case .barChart: return LocalizedString("Bar chart widget") case .barChart: return localizedString("Bar chart widget")
case .pieChart: return LocalizedString("Pie chart widget") case .pieChart: return localizedString("Pie chart widget")
case .networkChart: return LocalizedString("Network chart widget") case .networkChart: return localizedString("Network chart widget")
case .speed: return LocalizedString("Speed widget") case .speed: return localizedString("Speed widget")
case .battery: return LocalizedString("Battery widget") case .battery: return localizedString("Battery widget")
case .sensors: return LocalizedString("Text widget") case .sensors: return localizedString("Text widget")
case .memory: return LocalizedString("Memory widget") case .memory: return localizedString("Memory widget")
case .label: return LocalizedString("Label widget") case .label: return localizedString("Label widget")
default: return "" default: return ""
} }
} }
} }
@@ -247,7 +237,7 @@ public class Widget {
NotificationCenter.default.post(name: .togglePopup, object: nil, userInfo: [ NotificationCenter.default.post(name: .togglePopup, object: nil, userInfo: [
"module": self.module, "module": self.module,
"origin": window.frame.origin, "origin": window.frame.origin,
"center": window.frame.width/2, "center": window.frame.width/2
]) ])
} }
} }

View File

@@ -33,7 +33,7 @@ struct Battery_Usage: value_t {
var timeToCharge: Int = 0 var timeToCharge: Int = 0
var timeOnACPower: Date? = nil var timeOnACPower: Date? = nil
public var widget_value: Double { public var widgetValue: Double {
get { get {
return self.level return self.level
} }
@@ -98,7 +98,7 @@ public class Battery: Module {
public override func isAvailable() -> Bool { public override func isAvailable() -> Bool {
let snapshot = IOPSCopyPowerSourcesInfo().takeRetainedValue() let snapshot = IOPSCopyPowerSourcesInfo().takeRetainedValue()
let sources = IOPSCopyPowerSourcesList(snapshot).takeRetainedValue() as Array let sources = IOPSCopyPowerSourcesList(snapshot).takeRetainedValue() as Array
return sources.count > 0 return !sources.isEmpty
} }
private func usageCallback(_ raw: Battery_Usage?) { private func usageCallback(_ raw: Battery_Usage?) {
@@ -149,13 +149,13 @@ public class Battery: Module {
} }
if value.level <= notificationLevel && self.lowNotification == nil { 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 { if value.timeToEmpty > 0 {
subtitle += " (\(Double(value.timeToEmpty*60).printSecondsToHoursMinutesSeconds()))" subtitle += " (\(Double(value.timeToEmpty*60).printSecondsToHoursMinutesSeconds()))"
} }
self.lowNotification = showNotification( self.lowNotification = showNotification(
title: LocalizedString("Low battery"), title: localizedString("Low battery"),
subtitle: subtitle, subtitle: subtitle,
id: "battery-level", id: "battery-level",
icon: NSImage(named: NSImage.Name("low-battery"))! icon: NSImage(named: NSImage.Name("low-battery"))!
@@ -186,13 +186,13 @@ public class Battery: Module {
} }
if value.level >= notificationLevel && self.highNotification == nil { 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 { if value.timeToCharge > 0 {
subtitle += " (\(Double(value.timeToCharge*60).printSecondsToHoursMinutesSeconds()))" subtitle += " (\(Double(value.timeToCharge*60).printSecondsToHoursMinutesSeconds()))"
} }
self.highNotification = showNotification( self.highNotification = showNotification(
title: LocalizedString("High battery"), title: localizedString("High battery"),
subtitle: subtitle, subtitle: subtitle,
id: "battery-level2", id: "battery-level2",
icon: NSImage(named: NSImage.Name("high-battery"))! icon: NSImage(named: NSImage.Name("high-battery"))!

View File

@@ -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 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)) 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!) container.addSubview(self.dashboardBatteryView!)
view.addSubview(container) view.addSubview(container)
@@ -139,17 +144,17 @@ internal class Popup: NSView, Popup_p {
private func initDetails() -> NSView { private func initDetails() -> NSView {
let view: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: self.detailsHeight)) 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)) 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.levelField = popupRow(container, n: 5, title: "\(localizedString("Level")):", value: "").1
self.sourceField = PopupRow(container, n: 4, title: "\(LocalizedString("Source")):", value: "").1 self.sourceField = popupRow(container, n: 4, title: "\(localizedString("Source")):", value: "").1
let t = self.labelValue(container, n: 3, title: "\(LocalizedString("Time")):", value: "") let t = self.labelValue(container, n: 3, title: "\(localizedString("Time")):", value: "")
self.timeLabelField = t.0 self.timeLabelField = t.0
self.timeField = t.1 self.timeField = t.1
self.healthField = PopupRow(container, n: 2, title: "\(LocalizedString("Health")):", 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.cyclesField = popupRow(container, n: 1, title: "\(localizedString("Cycles")):", value: "").1
self.lastChargeField = PopupRow(container, n: 0, title: "\(LocalizedString("Last charge")):", value: "").1 self.lastChargeField = popupRow(container, n: 0, title: "\(localizedString("Last charge")):", value: "").1
view.addSubview(separator) view.addSubview(separator)
view.addSubview(container) view.addSubview(container)
@@ -159,13 +164,13 @@ internal class Popup: NSView, Popup_p {
private func initBattery() -> NSView { private func initBattery() -> NSView {
let view: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: self.batteryHeight)) 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)) 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.amperageField = popupRow(container, n: 3, title: "\(localizedString("Amperage")):", value: "").1
self.voltageField = PopupRow(container, n: 2, title: "\(LocalizedString("Voltage")):", 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.batteryPowerField = popupRow(container, n: 1, title: "\(localizedString("Power")):", value: "").1
self.temperatureField = PopupRow(container, n: 0, title: "\(LocalizedString("Temperature")):", value: "").1 self.temperatureField = popupRow(container, n: 0, title: "\(localizedString("Temperature")):", value: "").1
view.addSubview(separator) view.addSubview(separator)
view.addSubview(container) view.addSubview(container)
@@ -175,11 +180,11 @@ internal class Popup: NSView, Popup_p {
private func initAdapter() -> NSView { private func initAdapter() -> NSView {
let view: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: self.adapterHeight)) 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)) 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.powerField = popupRow(container, n: 1, title: "\(localizedString("Power")):", value: "").1
self.chargingStateField = PopupRow(container, n: 0, title: "\(LocalizedString("Is charging")):", value: "").1 self.chargingStateField = popupRow(container, n: 0, title: "\(localizedString("Is charging")):", value: "").1
self.adapterView = view self.adapterView = view
@@ -191,7 +196,7 @@ internal class Popup: NSView, Popup_p {
private func initProcesses() -> NSView { private func initProcesses() -> NSView {
let view: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: self.processesHeight)) 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)) let container: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: separator.frame.origin.y))
for i in 0..<self.numberOfProcesses { for i in 0..<self.numberOfProcesses {
@@ -224,31 +229,31 @@ internal class Popup: NSView, Popup_p {
self.dashboardBatteryView?.setValue(abs(value.level)) self.dashboardBatteryView?.setValue(abs(value.level))
self.levelField?.stringValue = "\(Int(abs(value.level) * 100)) %" self.levelField?.stringValue = "\(Int(abs(value.level) * 100)) %"
self.sourceField?.stringValue = LocalizedString(value.powerSource) self.sourceField?.stringValue = localizedString(value.powerSource)
self.timeField?.stringValue = "" self.timeField?.stringValue = ""
if value.powerSource == "Battery Power" { if value.powerSource == "Battery Power" {
self.timeLabelField?.stringValue = "\(LocalizedString("Time to discharge")):" self.timeLabelField?.stringValue = "\(localizedString("Time to discharge")):"
if value.timeToEmpty != -1 && value.timeToEmpty != 0 { if value.timeToEmpty != -1 && value.timeToEmpty != 0 {
self.timeField?.stringValue = Double(value.timeToEmpty*60).printSecondsToHoursMinutesSeconds(short: self.timeFormat == "short") self.timeField?.stringValue = Double(value.timeToEmpty*60).printSecondsToHoursMinutesSeconds(short: self.timeFormat == "short")
} else { } else {
self.timeField?.stringValue = LocalizedString("Unknown") self.timeField?.stringValue = localizedString("Unknown")
} }
} else { } else {
self.timeLabelField?.stringValue = "\(LocalizedString("Time to charge")):" self.timeLabelField?.stringValue = "\(localizedString("Time to charge")):"
if value.timeToCharge != -1 && value.timeToCharge != 0 { if value.timeToCharge != -1 && value.timeToCharge != 0 {
self.timeField?.stringValue = Double(value.timeToCharge*60).printSecondsToHoursMinutesSeconds(short: self.timeFormat == "short") self.timeField?.stringValue = Double(value.timeToCharge*60).printSecondsToHoursMinutesSeconds(short: self.timeFormat == "short")
} else { } else {
self.timeField?.stringValue = LocalizedString("Unknown") self.timeField?.stringValue = localizedString("Unknown")
} }
} }
if value.timeToEmpty == -1 || value.timeToCharge == -1 { if value.timeToEmpty == -1 || value.timeToCharge == -1 {
self.timeField?.stringValue = LocalizedString("Calculating") self.timeField?.stringValue = localizedString("Calculating")
} }
if value.isCharged { if value.isCharged {
self.timeField?.stringValue = LocalizedString("Fully charged") self.timeField?.stringValue = localizedString("Fully charged")
} }
self.healthField?.stringValue = "\(value.health)%" self.healthField?.stringValue = "\(value.health)%"
@@ -270,12 +275,12 @@ internal class Popup: NSView, Popup_p {
self.lastChargeField?.stringValue = duration self.lastChargeField?.stringValue = duration
self.lastChargeField?.toolTip = formatter.string(from: timestamp) self.lastChargeField?.toolTip = formatter.string(from: timestamp)
} else { } else {
self.lastChargeField?.stringValue = LocalizedString("Unknown") self.lastChargeField?.stringValue = localizedString("Unknown")
self.lastChargeField?.toolTip = LocalizedString("Unknown") self.lastChargeField?.toolTip = localizedString("Unknown")
} }
} else { } else {
self.lastChargeField?.stringValue = LocalizedString("Unknown") self.lastChargeField?.stringValue = localizedString("Unknown")
self.lastChargeField?.toolTip = LocalizedString("Unknown") self.lastChargeField?.toolTip = localizedString("Unknown")
} }
self.amperageField?.stringValue = "\(abs(value.amperage)) mA" self.amperageField?.stringValue = "\(abs(value.amperage)) mA"
@@ -284,8 +289,8 @@ internal class Popup: NSView, Popup_p {
self.batteryPowerField?.stringValue = "\(batteryPower.roundTo(decimalPlaces: 2)) W" self.batteryPowerField?.stringValue = "\(batteryPower.roundTo(decimalPlaces: 2)) W"
self.temperatureField?.stringValue = "\(value.temperature) °C" self.temperatureField?.stringValue = "\(value.temperature) °C"
self.powerField?.stringValue = value.powerSource == "Battery Power" ? LocalizedString("Not connected") : "\(value.ACwatts) W" self.powerField?.stringValue = value.powerSource == "Battery Power" ? localizedString("Not connected") : "\(value.ACwatts) W"
self.chargingStateField?.stringValue = value.isCharging ? LocalizedString("Yes") : LocalizedString("No") self.chargingStateField?.stringValue = value.isCharging ? localizedString("Yes") : localizedString("No")
}) })
} }

View File

@@ -56,12 +56,12 @@ internal class UsageReader: Reader<Battery_Usage> {
let psInfo = IOPSCopyPowerSourcesInfo().takeRetainedValue() let psInfo = IOPSCopyPowerSourcesInfo().takeRetainedValue()
let psList = IOPSCopyPowerSourcesList(psInfo).takeRetainedValue() as [CFTypeRef] let psList = IOPSCopyPowerSourcesList(psInfo).takeRetainedValue() as [CFTypeRef]
if psList.count == 0 { if psList.isEmpty {
return return
} }
for ps in psList { for ps in psList {
if let list = IOPSGetPowerSourceDescription(psInfo, ps).takeUnretainedValue() as? Dictionary<String, Any> { if let list = IOPSGetPowerSourceDescription(psInfo, ps).takeUnretainedValue() as? [String: Any] {
self.usage.powerSource = list[kIOPSPowerSourceStateKey] as? String ?? "AC Power" self.usage.powerSource = list[kIOPSPowerSourceStateKey] as? String ?? "AC Power"
self.usage.isCharged = list[kIOPSIsChargedKey] as? Bool ?? false self.usage.isCharged = list[kIOPSIsChargedKey] as? Bool ?? false
self.usage.isCharging = self.getBoolValue("IsCharging" as CFString) ?? false self.usage.isCharging = self.getBoolValue("IsCharging" as CFString) ?? false
@@ -95,7 +95,7 @@ internal class UsageReader: Reader<Battery_Usage> {
var ACwatts: Int = 0 var ACwatts: Int = 0
if let ACDetails = IOPSCopyExternalPowerAdapterDetails() { if let ACDetails = IOPSCopyExternalPowerAdapterDetails() {
if let ACList = ACDetails.takeRetainedValue() as? Dictionary<String, Any> { if let ACList = ACDetails.takeRetainedValue() as? [String: Any] {
guard let watts = ACList[kIOPSPowerAdapterWattsKey] else { guard let watts = ACList[kIOPSPowerAdapterWattsKey] else {
return return
} }
@@ -171,7 +171,7 @@ public class ProcessReader: Reader<[TopProcess]> {
let output = String(decoding: fileHandle.availableData, as: UTF8.self) let output = String(decoding: fileHandle.availableData, as: UTF8.self)
var processes: [TopProcess] = [] var processes: [TopProcess] = []
output.enumerateLines { (line, _) -> () in output.enumerateLines { (line, _) -> Void in
if line.matches("^\\d* +.+ \\d*.?\\d*$") { if line.matches("^\\d* +.+ \\d*.?\\d*$") {
var str = line.trimmingCharacters(in: .whitespaces) 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()) self.callback(processes.prefix(self.numberOfProcesses).reversed().reversed())
} }
} }

View File

@@ -76,54 +76,54 @@ internal class Settings: NSView, Settings_v {
return v return v
} }
self.addSubview(SelectTitleRow( self.addSubview(selectTitleRow(
frame: NSRect( frame: NSRect(
x: Constants.Settings.margin, x: Constants.Settings.margin,
y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * (num-1), y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * (num-1),
width: self.frame.width - (Constants.Settings.margin*2), width: self.frame.width - (Constants.Settings.margin*2),
height: rowHeight height: rowHeight
), ),
title: LocalizedString("Low level notification"), title: localizedString("Low level notification"),
action: #selector(changeUpdateIntervalLow), action: #selector(changeUpdateIntervalLow),
items: lowLevels, items: lowLevels,
selected: self.lowLevelNotification == "Disabled" ? self.lowLevelNotification : "\(Int((Double(self.lowLevelNotification) ?? 0)*100))%" selected: self.lowLevelNotification == "Disabled" ? self.lowLevelNotification : "\(Int((Double(self.lowLevelNotification) ?? 0)*100))%"
)) ))
self.addSubview(SelectTitleRow( self.addSubview(selectTitleRow(
frame: NSRect( frame: NSRect(
x: Constants.Settings.margin, x: Constants.Settings.margin,
y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * (num-2), y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * (num-2),
width: self.frame.width - (Constants.Settings.margin*2), width: self.frame.width - (Constants.Settings.margin*2),
height: rowHeight height: rowHeight
), ),
title: LocalizedString("High level notification"), title: localizedString("High level notification"),
action: #selector(changeUpdateIntervalHigh), action: #selector(changeUpdateIntervalHigh),
items: highLevels, items: highLevels,
selected: self.highLevelNotification == "Disabled" ? self.highLevelNotification : "\(Int((Double(self.highLevelNotification) ?? 0)*100))%" selected: self.highLevelNotification == "Disabled" ? self.highLevelNotification : "\(Int((Double(self.highLevelNotification) ?? 0)*100))%"
)) ))
self.addSubview(SelectTitleRow( self.addSubview(selectTitleRow(
frame: NSRect( frame: NSRect(
x: Constants.Settings.margin, x: Constants.Settings.margin,
y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * (num-3), y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * (num-3),
width: self.frame.width - (Constants.Settings.margin*2), width: self.frame.width - (Constants.Settings.margin*2),
height: rowHeight height: rowHeight
), ),
title: LocalizedString("Number of top processes"), title: localizedString("Number of top processes"),
action: #selector(changeNumberOfProcesses), action: #selector(changeNumberOfProcesses),
items: NumbersOfProcesses.map{ "\($0)" }, items: NumbersOfProcesses.map{ "\($0)" },
selected: "\(self.numberOfProcesses)" selected: "\(self.numberOfProcesses)"
)) ))
if !widgets.filter({ $0 == .battery }).isEmpty { if !widgets.filter({ $0 == .battery }).isEmpty {
self.addSubview(SelectRow( self.addSubview(selectRow(
frame: NSRect( frame: NSRect(
x: Constants.Settings.margin, x: Constants.Settings.margin,
y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * 0, y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * 0,
width: self.frame.width - (Constants.Settings.margin*2), width: self.frame.width - (Constants.Settings.margin*2),
height: rowHeight height: rowHeight
), ),
title: LocalizedString("Time format"), title: localizedString("Time format"),
action: #selector(toggleTimeFormat), action: #selector(toggleTimeFormat),
items: ShortLong, items: ShortLong,
selected: self.timeFormat selected: self.timeFormat

View File

@@ -18,7 +18,7 @@ public struct CPU_Load: value_t {
var userLoad: Double = 0 var userLoad: Double = 0
var idleLoad: Double = 0 var idleLoad: Double = 0
public var widget_value: Double { public var widgetValue: Double {
get { get {
return self.totalUsage return self.totalUsage
} }

View File

@@ -123,17 +123,17 @@ internal class Popup: NSView, Popup_p {
width: container.frame.height, width: container.frame.height,
height: container.frame.height height: container.frame.height
), segments: [], drawValue: true) ), segments: [], drawValue: true)
self.circle!.toolTip = LocalizedString("CPU usage") self.circle!.toolTip = localizedString("CPU usage")
container.addSubview(self.circle!) container.addSubview(self.circle!)
let centralWidth: CGFloat = self.dashboardHeight-20 let centralWidth: CGFloat = self.dashboardHeight-20
let sideWidth: CGFloat = (view.frame.width - centralWidth - (Constants.Popup.margins*2))/2 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 = 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.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 = 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 (self.frequencyCircle! as NSView).isHidden = true
view.addSubview(self.temperatureCircle!) view.addSubview(self.temperatureCircle!)
@@ -145,7 +145,7 @@ internal class Popup: NSView, Popup_p {
private func initChart() -> NSView { private func initChart() -> NSView {
let view: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: self.chartHeight)) 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)) let container: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: separator.frame.origin.y))
container.wantsLayer = true container.wantsLayer = true
container.layer?.backgroundColor = NSColor.lightGray.withAlphaComponent(0.1).cgColor container.layer?.backgroundColor = NSColor.lightGray.withAlphaComponent(0.1).cgColor
@@ -162,12 +162,12 @@ internal class Popup: NSView, Popup_p {
private func initDetails() -> NSView { private func initDetails() -> NSView {
let view: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: self.detailsHeight)) 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)) 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.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.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.idleField = popupWithColorRow(container, color: NSColor.lightGray.withAlphaComponent(0.5), n: 0, title: "\(localizedString("Idle")):", value: "")
view.addSubview(separator) view.addSubview(separator)
view.addSubview(container) view.addSubview(container)
@@ -177,7 +177,7 @@ internal class Popup: NSView, Popup_p {
private func initProcesses() -> NSView { private func initProcesses() -> NSView {
let view: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: self.processesHeight)) 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)) let container: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: separator.frame.origin.y))
for i in 0..<self.numberOfProcesses { for i in 0..<self.numberOfProcesses {
@@ -206,7 +206,7 @@ internal class Popup: NSView, Popup_p {
self.circle?.setValue(value.totalUsage) self.circle?.setValue(value.totalUsage)
self.circle?.setSegments([ self.circle?.setSegments([
circle_segment(value: value.systemLoad, color: NSColor.systemRed), circle_segment(value: value.systemLoad, color: NSColor.systemRed),
circle_segment(value: value.userLoad, color: NSColor.systemBlue), circle_segment(value: value.userLoad, color: NSColor.systemBlue)
]) ])
} }
self.chart?.addValue(value.totalUsage) self.chart?.addValue(value.totalUsage)

View File

@@ -29,8 +29,8 @@ internal class LoadReader: Reader<CPU_Load> {
private var usagePerCore: [Double] = [] private var usagePerCore: [Double] = []
public override func setup() { public override func setup() {
self.hasHyperthreadingCores = SysctlByName("hw.physicalcpu") != SysctlByName("hw.logicalcpu") self.hasHyperthreadingCores = sysctlByName("hw.physicalcpu") != sysctlByName("hw.logicalcpu")
[CTL_HW, HW_NCPU].withUnsafeBufferPointer() { mib in [CTL_HW, HW_NCPU].withUnsafeBufferPointer { mib in
var sizeOfNumCPUs: size_t = MemoryLayout<uint>.size var sizeOfNumCPUs: size_t = MemoryLayout<uint>.size
let status = sysctl(processor_info_array_t(mutating: mib.baseAddress), 2, &numCPUs, &sizeOfNumCPUs, nil, 0) let status = sysctl(processor_info_array_t(mutating: mib.baseAddress), 2, &numCPUs, &sizeOfNumCPUs, nil, 0)
if status != 0 { if status != 0 {
@@ -39,6 +39,7 @@ internal class LoadReader: Reader<CPU_Load> {
} }
} }
// swiftlint:disable function_body_length
public override func read() { 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) 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 { if result == KERN_SUCCESS {
@@ -133,12 +134,12 @@ internal class LoadReader: Reader<CPU_Load> {
} }
private func hostCPULoadInfo() -> host_cpu_load_info? { private func hostCPULoadInfo() -> host_cpu_load_info? {
let HOST_CPU_LOAD_INFO_COUNT = MemoryLayout<host_cpu_load_info>.stride/MemoryLayout<integer_t>.stride let count = MemoryLayout<host_cpu_load_info>.stride/MemoryLayout<integer_t>.stride
var size = mach_msg_type_number_t(HOST_CPU_LOAD_INFO_COUNT) var size = mach_msg_type_number_t(count)
var cpuLoadInfo = host_cpu_load_info() var cpuLoadInfo = host_cpu_load_info()
let result: kern_return_t = withUnsafeMutablePointer(to: &cpuLoadInfo) { 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) host_statistics(mach_host_self(), HOST_CPU_LOAD_INFO, $0, &size)
} }
} }
@@ -202,7 +203,7 @@ public class ProcessReader: Reader<[TopProcess]> {
var index = 0 var index = 0
var processes: [TopProcess] = [] var processes: [TopProcess] = []
output.enumerateLines { (line, stop) -> () in output.enumerateLines { (line, stop) -> Void in
if index != 0 { if index != 0 {
var str = line.trimmingCharacters(in: .whitespaces) var str = line.trimmingCharacters(in: .whitespaces)
let pidString = str.findAndCrop(pattern: "^\\d+") let pidString = str.findAndCrop(pattern: "^\\d+")
@@ -250,6 +251,7 @@ public class TemperatureReader: Reader<Double> {
} }
} }
// swiftlint:disable identifier_name
public class FrequencyReader: Reader<Double> { public class FrequencyReader: Reader<Double> {
private typealias PGSample = UInt64 private typealias PGSample = UInt64
private typealias UDouble = UnsafeMutablePointer<Double> private typealias UDouble = UnsafeMutablePointer<Double>

View File

@@ -40,7 +40,7 @@ internal class Settings: NSView, Settings_v {
if !self.usagePerCoreState { if !self.usagePerCoreState {
self.hyperthreadState = false self.hyperthreadState = false
} }
self.hasHyperthreadingCores = SysctlByName("hw.physicalcpu") != SysctlByName("hw.logicalcpu") self.hasHyperthreadingCores = sysctlByName("hw.physicalcpu") != sysctlByName("hw.logicalcpu")
super.init(frame: CGRect( super.init(frame: CGRect(
x: 0, x: 0,
@@ -57,9 +57,10 @@ internal class Settings: NSView, Settings_v {
fatalError("init(coder:) has not been implemented") fatalError("init(coder:) has not been implemented")
} }
// swiftlint:disable function_body_length
public func load(widgets: [widget_t]) { public func load(widgets: [widget_t]) {
self.subviews.forEach{ $0.removeFromSuperview() } self.subviews.forEach{ $0.removeFromSuperview() }
var hasIPG = false var hasIPG = false
#if arch(x86_64) #if arch(x86_64)
@@ -74,49 +75,69 @@ internal class Settings: NSView, Settings_v {
num += 1 num += 1
} }
self.addSubview(SelectTitleRow( 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), frame: NSRect(
title: LocalizedString("Update interval"), 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), action: #selector(changeUpdateInterval),
items: ReaderUpdateIntervals.map{ "\($0) sec" }, items: ReaderUpdateIntervals.map{ "\($0) sec" },
selected: "\(self.updateIntervalValue) sec" selected: "\(self.updateIntervalValue) sec"
)) ))
if !widgets.filter({ $0 == .barChart }).isEmpty { if !widgets.filter({ $0 == .barChart }).isEmpty {
self.addSubview(ToggleTitleRow( 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), frame: NSRect(
title: LocalizedString("Show usage per core"), 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), action: #selector(toggleUsagePerCore),
state: self.usagePerCoreState state: self.usagePerCoreState
)) ))
if self.hasHyperthreadingCores { if self.hasHyperthreadingCores {
self.hyperthreadView = ToggleTitleRow( 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), frame: NSRect(
title: LocalizedString("Show hyper-threading cores"), 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), action: #selector(toggleMultithreading),
state: self.hyperthreadState state: self.hyperthreadState
) )
if !self.usagePerCoreState { if !self.usagePerCoreState {
FindAndToggleEnableNSControlState(self.hyperthreadView, state: false) findAndToggleEnableNSControlState(self.hyperthreadView, state: false)
FindAndToggleNSControlState(self.hyperthreadView, state: .off) findAndToggleNSControlState(self.hyperthreadView, state: .off)
} }
self.addSubview(self.hyperthreadView!) self.addSubview(self.hyperthreadView!)
} }
} }
if hasIPG { if hasIPG {
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), frame: NSRect(
title: "\(LocalizedString("CPU frequency")) (IPG)", 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), action: #selector(toggleIPG),
state: self.IPGState 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), 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), action: #selector(changeNumberOfProcesses),
items: NumbersOfProcesses.map{ "\($0)" }, items: NumbersOfProcesses.map{ "\($0)" },
selected: "\(self.numberOfProcesses)" selected: "\(self.numberOfProcesses)"
@@ -153,11 +174,11 @@ internal class Settings: NSView, Settings_v {
Store.shared.set(key: "\(self.title)_usagePerCore", value: self.usagePerCoreState) Store.shared.set(key: "\(self.title)_usagePerCore", value: self.usagePerCoreState)
self.callback() self.callback()
FindAndToggleEnableNSControlState(self.hyperthreadView, state: self.usagePerCoreState) findAndToggleEnableNSControlState(self.hyperthreadView, state: self.usagePerCoreState)
if !self.usagePerCoreState { if !self.usagePerCoreState {
self.hyperthreadState = false self.hyperthreadState = false
Store.shared.set(key: "\(self.title)_hyperhreading", value: self.hyperthreadState) Store.shared.set(key: "\(self.title)_hyperhreading", value: self.hyperthreadState)
FindAndToggleNSControlState(self.hyperthreadView, state: .off) findAndToggleNSControlState(self.hyperthreadView, state: .off)
} }
} }

View File

@@ -28,7 +28,7 @@ internal class Popup: NSView, Popup_p {
} }
internal func capacityCallback(_ value: Disks) { 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.subviews.forEach{ $0.removeFromSuperview() }
self.list = [:] self.list = [:]
} }
@@ -138,7 +138,7 @@ internal class DiskNameAndBarView: NSView {
self.uri = path self.uri = path
super.init(frame: frame) super.init(frame: frame)
self.toolTip = LocalizedString("Open disk") self.toolTip = localizedString("Open disk")
self.addName(name: name) self.addName(name: name)
self.addHorizontalBar(size: size, free: free) self.addHorizontalBar(size: size, free: free)
@@ -274,7 +274,7 @@ internal class DiskLegendView: NSView {
self.free = free self.free = free
super.init(frame: frame) super.init(frame: frame)
self.toolTip = LocalizedString("Switch view") self.toolTip = localizedString("Switch view")
let height: CGFloat = 14 let height: CGFloat = 14
let view: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height)) 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 { if usedSpace < 0 {
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 { } 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 return value

View File

@@ -53,9 +53,14 @@ internal class Settings: NSView, Settings_v {
let rowHeight: CGFloat = 30 let rowHeight: CGFloat = 30
let num: CGFloat = 3 let num: CGFloat = 3
self.intervalSelectView = SelectTitleRow( 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), frame: NSRect(
title: LocalizedString("Update interval"), 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), action: #selector(changeUpdateInterval),
items: ReaderUpdateIntervals.map{ "\($0) sec" }, items: ReaderUpdateIntervals.map{ "\($0) sec" },
selected: "\(self.updateIntervalValue) sec" selected: "\(self.updateIntervalValue) sec"
@@ -64,9 +69,14 @@ internal class Settings: NSView, Settings_v {
self.addDiskSelector() self.addDiskSelector()
self.addSubview(ToggleTitleRow( 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), frame: NSRect(
title: LocalizedString("Show removable disks"), 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), action: #selector(toggleRemovable),
state: self.removableState state: self.removableState
)) ))
@@ -82,7 +92,7 @@ internal class Settings: NSView, Settings_v {
height: 30 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.font = NSFont.systemFont(ofSize: 13, weight: .light)
rowTitle.textColor = .textColor rowTitle.textColor = .textColor

View File

@@ -76,7 +76,7 @@ public class Fans: Module {
} }
private func checkIfNoSensorsEnabled() { 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]) NotificationCenter.default.post(name: .toggleModule, object: nil, userInfo: ["module": self.config.name, "state": false])
} }
} }

View File

@@ -242,7 +242,7 @@ internal class FanView: NSStackView {
let minField: NSTextField = TextView(frame: NSRect(x: 0, y: 0, width: 80, height: levels.frame.height)) 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.font = NSFont.systemFont(ofSize: 11, weight: .light)
minField.textColor = .secondaryLabelColor minField.textColor = .secondaryLabelColor
minField.stringValue = "\(LocalizedString("Min")): \(Int(self.fan.minSpeed))" minField.stringValue = "\(localizedString("Min")): \(Int(self.fan.minSpeed))"
minField.alignment = .left minField.alignment = .left
let valueField: NSTextField = TextView(frame: NSRect(x: 80, y: 0, width: levels.frame.width - 160, height: levels.frame.height)) 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)) 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.font = NSFont.systemFont(ofSize: 11, weight: .light)
maxField.textColor = .secondaryLabelColor maxField.textColor = .secondaryLabelColor
maxField.stringValue = "\(LocalizedString("Max")): \(Int(self.fan.maxSpeed))" maxField.stringValue = "\(localizedString("Max")): \(Int(self.fan.maxSpeed))"
maxField.alignment = .right maxField.alignment = .right
controls.addArrangedSubview(slider) controls.addArrangedSubview(slider)
@@ -340,8 +340,8 @@ internal class FanView: NSStackView {
private class ModeButtons: NSStackView { private class ModeButtons: NSStackView {
public var callback: (FanMode) -> Void = {_ in } public var callback: (FanMode) -> Void = {_ in }
private var autoBtn: NSButton = NSButton(title: LocalizedString("Automatic"), target: nil, action: #selector(autoMode)) 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 manualBtn: NSButton = NSButton(title: localizedString("Manual"), target: nil, action: #selector(manualMode))
public init(frame: NSRect, mode: FanMode) { public init(frame: NSRect, mode: FanMode) {
super.init(frame: frame) super.init(frame: frame)

View File

@@ -60,27 +60,27 @@ internal class Settings: NSStackView, Settings_v {
} }
self.subviews.forEach{ $0.removeFromSuperview() } self.subviews.forEach{ $0.removeFromSuperview() }
self.addArrangedSubview(SelectTitleRow( self.addArrangedSubview(selectTitleRow(
frame: NSRect( frame: NSRect(
x: Constants.Settings.margin, x: Constants.Settings.margin,
y: 0, y: 0,
width: self.frame.width - (Constants.Settings.margin*2), width: self.frame.width - (Constants.Settings.margin*2),
height: Constants.Settings.row height: Constants.Settings.row
), ),
title: LocalizedString("Update interval"), title: localizedString("Update interval"),
action: #selector(changeUpdateInterval), action: #selector(changeUpdateInterval),
items: ReaderUpdateIntervals.map{ "\($0) sec" }, items: ReaderUpdateIntervals.map{ "\($0) sec" },
selected: "\(self.updateIntervalValue) sec" selected: "\(self.updateIntervalValue) sec"
)) ))
self.addArrangedSubview(ToggleTitleRow( self.addArrangedSubview(toggleTitleRow(
frame: NSRect( frame: NSRect(
x: Constants.Settings.margin, x: Constants.Settings.margin,
y: 0, y: 0,
width: self.frame.width - (Constants.Settings.margin*2), width: self.frame.width - (Constants.Settings.margin*2),
height: Constants.Settings.row height: Constants.Settings.row
), ),
title: LocalizedString("Label"), title: localizedString("Label"),
action: #selector(toggleLabelState), action: #selector(toggleLabelState),
state: self.labelState state: self.labelState
)) ))
@@ -95,7 +95,7 @@ internal class Settings: NSStackView, Settings_v {
view.distribution = .gravityAreas view.distribution = .gravityAreas
view.spacing = Constants.Settings.margin 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.font = NSFont.systemFont(ofSize: 14, weight: .regular)
title.textColor = .secondaryLabelColor title.textColor = .secondaryLabelColor
title.alignment = .center title.alignment = .center
@@ -103,7 +103,7 @@ internal class Settings: NSStackView, Settings_v {
view.addArrangedSubview(title) view.addArrangedSubview(title)
self.list.pointee.reversed().forEach { (f: Fan) in 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), frame: NSRect(x: 0, y: 0, width: view.frame.width, height: Constants.Settings.row),
title: f.name, title: f.name,
action: #selector(self.handleSelection), action: #selector(self.handleSelection),
@@ -119,7 +119,7 @@ internal class Settings: NSStackView, Settings_v {
view.setFrameSize(NSSize(width: view.frame.width, height: listHeight)) view.setFrameSize(NSSize(width: view.frame.width, height: listHeight))
NSLayoutConstraint.activate([ NSLayoutConstraint.activate([
view.heightAnchor.constraint(equalToConstant: listHeight), view.heightAnchor.constraint(equalToConstant: listHeight),
view.widthAnchor.constraint(equalToConstant: view.bounds.width), view.widthAnchor.constraint(equalToConstant: view.bounds.width)
]) ])
self.addArrangedSubview(view) self.addArrangedSubview(view)
@@ -140,7 +140,7 @@ internal class Settings: NSStackView, Settings_v {
state = sender is NSButton ? (sender as! NSButton).state: nil 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() self.callback()
} }

View File

@@ -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 } 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 { get {
return list.isEmpty ? 0 : (list[0].utilization ?? 0) return list.isEmpty ? 0 : (list[0].utilization ?? 0)
} }

View File

@@ -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)) let stateView: NSView = NSView(frame: NSRect(x: width - 8, y: (view.frame.height-7)/2, width: 6, height: 6))
stateView.wantsLayer = true stateView.wantsLayer = true
stateView.layer?.backgroundColor = (self.value.state ? NSColor.systemGreen : NSColor.systemRed).cgColor 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 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 w = details.widthOfString(usingFont: NSFont.systemFont(ofSize: 9, weight: .regular)) + 8
let button = NSButtonWithPadding() let button = NSButtonWithPadding()
button.frame = CGRect(x: view.frame.width - w, y: 2, width: w, height: view.frame.height-2) 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.isBordered = false
button.action = #selector(self.showDetails) button.action = #selector(self.showDetails)
button.target = self button.target = self
button.toolTip = LocalizedString("Details") button.toolTip = localizedString("Details")
button.title = details button.title = details
button.font = NSFont.systemFont(ofSize: 9, weight: .regular) button.font = NSFont.systemFont(ofSize: 9, weight: .regular)
@@ -194,7 +194,7 @@ private class GPUView: NSStackView {
} else { } else {
circle = HalfCircleGraphView(frame: NSRect(x: 0, y: 0, width: circleSize, height: circleSize)) circle = HalfCircleGraphView(frame: NSRect(x: 0, y: 0, width: circleSize, height: circleSize))
circle.id = id circle.id = id
circle.toolTip = LocalizedString("GPU \(id)") circle.toolTip = localizedString("GPU \(id)")
if let row = self.circleRow { if let row = self.circleRow {
row.setFrameSize(NSSize(width: row.frame.width, height: self.circleSize + 20)) row.setFrameSize(NSSize(width: row.frame.width, height: self.circleSize + 20))
row.edgeInsets = NSEdgeInsets(top: 10, left: 0, bottom: 0, right: 0) 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?.backgroundColor = NSColor.lightGray.withAlphaComponent(0.1).cgColor
chart.layer?.cornerRadius = 3 chart.layer?.cornerRadius = 3
chart.id = id chart.id = id
chart.toolTip = LocalizedString("GPU \(id)") chart.toolTip = localizedString("GPU \(id)")
if let row = self.chartRow { if let row = self.chartRow {
row.setFrameSize(NSSize(width: row.frame.width, height: self.chartSize + 20)) row.setFrameSize(NSSize(width: row.frame.width, height: self.chartSize + 20))
row.spacing = Constants.Popup.margins row.spacing = Constants.Popup.margins
@@ -246,9 +246,9 @@ private class GPUView: NSStackView {
public func update(_ gpu: GPU_Info) { public func update(_ gpu: GPU_Info) {
self.detailsView.update(gpu) 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?.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: "temperature", gpu.temperature)
self.addStats(id: "utilization", gpu.utilization) self.addStats(id: "utilization", gpu.utilization)
@@ -306,44 +306,44 @@ private class GPUDetails: NSView {
var num: CGFloat = 2 var num: CGFloat = 2
if let value = value.vendor { if let value = value.vendor {
grid.addRow(with: keyValueRow("\(LocalizedString("Vendor")):", value)) grid.addRow(with: keyValueRow("\(localizedString("Vendor")):", value))
num += 1 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 state: String = value.state ? localizedString("Active") : localizedString("Non active")
let arr = keyValueRow("\(LocalizedString("Status")):", state) let arr = keyValueRow("\(localizedString("Status")):", state)
self.status = arr.last self.status = arr.last
grid.addRow(with: arr) grid.addRow(with: arr)
if let value = value.fanSpeed { if let value = value.fanSpeed {
let arr = keyValueRow("\(LocalizedString("Fan speed")):", "\(value)%") let arr = keyValueRow("\(localizedString("Fan speed")):", "\(value)%")
self.fanSpeed = arr.last self.fanSpeed = arr.last
grid.addRow(with: arr) grid.addRow(with: arr)
num += 1 num += 1
} }
if let value = value.coreClock { 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 self.coreClock = arr.last
grid.addRow(with: arr) grid.addRow(with: arr)
num += 1 num += 1
} }
if let value = value.memoryClock { 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 self.memoryClock = arr.last
grid.addRow(with: arr) grid.addRow(with: arr)
num += 1 num += 1
} }
if let value = value.temperature { 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 self.temperature = arr.last
grid.addRow(with: arr) grid.addRow(with: arr)
num += 1 num += 1
} }
if let value = value.utilization { 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 self.utilization = arr.last
grid.addRow(with: arr) grid.addRow(with: arr)
num += 1 num += 1
@@ -366,7 +366,7 @@ private class GPUDetails: NSView {
} }
public func update(_ gpu: GPU_Info) { 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 { if let value = gpu.fanSpeed {
self.fanSpeed?.stringValue = "\(value)%" self.fanSpeed?.stringValue = "\(value)%"

View File

@@ -63,6 +63,7 @@ internal class InfoReader: Reader<GPUs> {
} }
} }
// swiftlint:disable function_body_length
public override func read() { public override func read() {
guard let accelerators = fetchIOService(kIOAcceleratorClassName) else { guard let accelerators = fetchIOService(kIOAcceleratorClassName) else {
return return
@@ -75,7 +76,7 @@ internal class InfoReader: Reader<GPUs> {
return 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") os_log(.error, log: log, "PerformanceStatistics not found")
return return
} }
@@ -154,7 +155,7 @@ internal class InfoReader: Reader<GPUs> {
return 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 self.gpus.list[idx].state = state == 0
} }

View File

@@ -54,28 +54,28 @@ internal class Settings: NSView, Settings_v {
let rowHeight: CGFloat = 30 let rowHeight: CGFloat = 30
let num: CGFloat = widgets.filter{ $0 == .mini }.isEmpty ? 2 : 3 let num: CGFloat = widgets.filter{ $0 == .mini }.isEmpty ? 2 : 3
self.addSubview(SelectTitleRow( self.addSubview(selectTitleRow(
frame: NSRect( frame: NSRect(
x: Constants.Settings.margin, x: Constants.Settings.margin,
y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * (num-1), y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * (num-1),
width: self.frame.width - (Constants.Settings.margin*2), width: self.frame.width - (Constants.Settings.margin*2),
height: rowHeight height: rowHeight
), ),
title: LocalizedString("Update interval"), title: localizedString("Update interval"),
action: #selector(changeUpdateInterval), action: #selector(changeUpdateInterval),
items: ReaderUpdateIntervals.map{ "\($0) sec" }, items: ReaderUpdateIntervals.map{ "\($0) sec" },
selected: "\(self.updateIntervalValue) sec" selected: "\(self.updateIntervalValue) sec"
)) ))
if !widgets.filter({ $0 == .mini }).isEmpty { if !widgets.filter({ $0 == .mini }).isEmpty {
self.addSubview(ToggleTitleRow( self.addSubview(toggleTitleRow(
frame: NSRect( frame: NSRect(
x: Constants.Settings.margin, x: Constants.Settings.margin,
y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * 1, y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * 1,
width: self.frame.width - (Constants.Settings.margin*2), width: self.frame.width - (Constants.Settings.margin*2),
height: rowHeight height: rowHeight
), ),
title: LocalizedString("Show GPU type"), title: localizedString("Show GPU type"),
action: #selector(toggleShowType), action: #selector(toggleShowType),
state: self.showTypeValue state: self.showTypeValue
)) ))
@@ -95,7 +95,7 @@ internal class Settings: NSView, Settings_v {
let view: NSGridView = NSGridView(frame: frame) let view: NSGridView = NSGridView(frame: frame)
view.yPlacement = .center 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.font = NSFont.systemFont(ofSize: 13, weight: .light)
title.textColor = .textColor title.textColor = .textColor
@@ -116,7 +116,7 @@ internal class Settings: NSView, Settings_v {
internal func setList(_ gpus: GPUs) { internal func setList(_ gpus: GPUs) {
var list: [KeyValue_t] = [ var list: [KeyValue_t] = [
KeyValue_t(key: "automatic", value: "Automatic"), 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)) } 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") { if item.key.contains("separator") {
menu.addItem(NSMenuItem.separator()) menu.addItem(NSMenuItem.separator())
} else { } 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 interfaceMenu.representedObject = item.key
menu.addItem(interfaceMenu) menu.addItem(interfaceMenu)
if self.selectedGPU == item.key { if self.selectedGPU == item.key {

View File

@@ -58,7 +58,7 @@ public struct Network_Usage: value_t {
self.ssid = nil self.ssid = nil
} }
public var widget_value: Double = 0 public var widgetValue: Double = 0
} }
public struct Network_Process { public struct Network_Process {
@@ -130,7 +130,7 @@ public class Network: Module {
list.append(displayName as String) list.append(displayName as String)
} }
} }
return list.count > 0 return !list.isEmpty
} }
private func usageCallback(_ raw: Network_Usage?) { private func usageCallback(_ raw: Network_Usage?) {

View File

@@ -8,11 +8,13 @@
// //
// Copyright © 2020 Serhiy Mytrovtsiy. All rights reserved. // Copyright © 2020 Serhiy Mytrovtsiy. All rights reserved.
// //
// swiftlint:disable file_length
import Cocoa import Cocoa
import ModuleKit import ModuleKit
import StatsKit import StatsKit
// swiftlint:disable type_body_length
internal class Popup: NSStackView, Popup_p { internal class Popup: NSStackView, Popup_p {
public var sizeCallback: ((NSSize) -> Void)? = nil 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 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 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.uploadView = uploadFields.0
self.uploadValueField = uploadFields.1 self.uploadValueField = uploadFields.1
self.uploadUnitField = uploadFields.2 self.uploadUnitField = uploadFields.2
self.uploadStateView = uploadFields.3 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 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.downloadView = downloadFields.0
self.downloadValueField = downloadFields.1 self.downloadValueField = downloadFields.1
self.downloadUnitField = downloadFields.2 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)) 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 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)) let container: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: separator.frame.origin.y))
container.wantsLayer = true container.wantsLayer = true
container.layer?.backgroundColor = NSColor.lightGray.withAlphaComponent(0.1).cgColor container.layer?.backgroundColor = NSColor.lightGray.withAlphaComponent(0.1).cgColor
@@ -168,21 +170,21 @@ internal class Popup: NSStackView, Popup_p {
button.contentTintColor = .lightGray button.contentTintColor = .lightGray
button.action = #selector(self.resetTotalNetworkUsage) button.action = #selector(self.resetTotalNetworkUsage)
button.target = self button.target = self
button.toolTip = LocalizedString("Reset") button.toolTip = localizedString("Reset")
button.image = Bundle(for: Module.self).image(forResource: "refresh")! 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) row.addSubview(button)
container.addArrangedSubview(row) container.addArrangedSubview(row)
self.totalUploadField = PopupWithColorRow(container, color: NSColor.systemRed, n: 5, title: "\(LocalizedString("Total upload")):", 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.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.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.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.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 = popupRow(container, n: 0, title: "\(localizedString("Local IP")):", value: localizedString("Unknown")).1
self.localIPField?.isSelectable = true self.localIPField?.isSelectable = true
self.macAdressField?.isSelectable = true self.macAdressField?.isSelectable = true
@@ -214,16 +216,16 @@ internal class Popup: NSStackView, Popup_p {
button.contentTintColor = .lightGray button.contentTintColor = .lightGray
button.action = #selector(self.refreshPublicIP) button.action = #selector(self.refreshPublicIP)
button.target = self button.target = self
button.toolTip = LocalizedString("Refresh") button.toolTip = localizedString("Refresh")
button.image = Bundle(for: Module.self).image(forResource: "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) row.addSubview(button)
container.addArrangedSubview(row) container.addArrangedSubview(row)
self.publicIPv4Field = PopupRow(container, title: "\(LocalizedString("v4")):", 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.publicIPv6Field = popupRow(container, title: "\(localizedString("v6")):", value: localizedString("Unknown")).1
self.publicIPv4Field?.isSelectable = true self.publicIPv4Field?.isSelectable = true
if let valueView = self.publicIPv6Field { if let valueView = self.publicIPv6Field {
@@ -247,7 +249,7 @@ internal class Popup: NSStackView, Popup_p {
private func initProcesses() -> NSView { private func initProcesses() -> NSView {
let view: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: self.processesHeight)) 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)) let container: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: separator.frame.origin.y))
for i in 0..<self.numberOfProcesses { for i in 0..<self.numberOfProcesses {
@@ -297,33 +299,33 @@ internal class Popup: NSStackView, Popup_p {
self.interfaceField?.stringValue = "\(interface.displayName) (\(interface.BSDName))" self.interfaceField?.stringValue = "\(interface.displayName) (\(interface.BSDName))"
self.macAdressField?.stringValue = interface.address self.macAdressField?.stringValue = interface.address
} else { } else {
self.interfaceField?.stringValue = LocalizedString("Unknown") self.interfaceField?.stringValue = localizedString("Unknown")
self.macAdressField?.stringValue = LocalizedString("Unknown") self.macAdressField?.stringValue = localizedString("Unknown")
} }
if value.connectionType == .wifi { if value.connectionType == .wifi {
self.ssidField?.stringValue = value.ssid ?? "Unknown" self.ssidField?.stringValue = value.ssid ?? "Unknown"
} else { } else {
self.ssidField?.stringValue = LocalizedString("Unavailable") self.ssidField?.stringValue = localizedString("Unavailable")
} }
if let view = self.publicIPv4Field, view.stringValue != value.raddr.v4 { if let view = self.publicIPv4Field, view.stringValue != value.raddr.v4 {
if let addr = value.raddr.v4 { if let addr = value.raddr.v4 {
view.stringValue = (value.countryCode != nil) ? "\(addr) (\(value.countryCode!))" : addr view.stringValue = (value.countryCode != nil) ? "\(addr) (\(value.countryCode!))" : addr
} else { } else {
view.stringValue = LocalizedString("Unknown") view.stringValue = localizedString("Unknown")
} }
} }
if let view = self.publicIPv6Field, view.stringValue != value.raddr.v6 { if let view = self.publicIPv6Field, view.stringValue != value.raddr.v6 {
if let addr = value.raddr.v6 { if let addr = value.raddr.v6 {
view.stringValue = addr view.stringValue = addr
} else { } else {
view.stringValue = LocalizedString("Unknown") view.stringValue = localizedString("Unknown")
} }
} }
if self.localIPField?.stringValue != value.laddr { if self.localIPField?.stringValue != value.laddr {
self.localIPField?.stringValue = value.laddr ?? LocalizedString("Unknown") self.localIPField?.stringValue = value.laddr ?? localizedString("Unknown")
} }
self.initialized = true self.initialized = true
@@ -364,6 +366,7 @@ internal class Popup: NSStackView, Popup_p {
// MARK: - helpers // MARK: - helpers
// swiftlint:disable large_tuple
private func topValueView(_ view: NSView, title: String, color: NSColor) -> (NSView, NSTextField, NSTextField, ColorView) { private func topValueView(_ view: NSView, title: String, color: NSColor) -> (NSView, NSTextField, NSTextField, ColorView) {
let topHeight: CGFloat = 30 let topHeight: CGFloat = 30
let titleHeight: CGFloat = 15 let titleHeight: CGFloat = 15

View File

@@ -163,7 +163,7 @@ internal class UsageReader: Reader<Network_Usage> {
var totalUpload: Int64 = 0 var totalUpload: Int64 = 0
var totalDownload: Int64 = 0 var totalDownload: Int64 = 0
var firstLine = false var firstLine = false
output.enumerateLines { (line, _) -> () in output.enumerateLines { (line, _) -> Void in
if !firstLine { if !firstLine {
firstLine = true firstLine = true
return return
@@ -297,6 +297,7 @@ public class ProcessReader: Reader<[Network_Process]> {
self.popup = true self.popup = true
} }
// swiftlint:disable function_body_length
public override func read() { public override func read() {
if self.numberOfProcesses == 0 { if self.numberOfProcesses == 0 {
return return
@@ -335,7 +336,7 @@ public class ProcessReader: Reader<[Network_Process]> {
var list: [Network_Process] = [] var list: [Network_Process] = []
var firstLine = false var firstLine = false
output.enumerateLines { (line, _) -> () in output.enumerateLines { (line, _) -> Void in
if !firstLine { if !firstLine {
firstLine = true firstLine = true
return return
@@ -371,7 +372,7 @@ public class ProcessReader: Reader<[Network_Process]> {
} }
var processes: [Network_Process] = [] var processes: [Network_Process] = []
if self.previous.count == 0 { if self.previous.isEmpty {
self.previous = list self.previous = list
processes = list processes = list
} else { } else {
@@ -391,7 +392,7 @@ public class ProcessReader: Reader<[Network_Process]> {
upload = 0 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 self.previous = list

View File

@@ -58,17 +58,27 @@ internal class Settings: NSView, Settings_v {
let rowHeight: CGFloat = 30 let rowHeight: CGFloat = 30
let num: CGFloat = 2 let num: CGFloat = 2
self.addSubview(SelectTitleRow( 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), frame: NSRect(
title: LocalizedString("Number of top processes"), 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), action: #selector(changeNumberOfProcesses),
items: NumbersOfProcesses.map{ "\($0)" }, items: NumbersOfProcesses.map{ "\($0)" },
selected: "\(self.numberOfProcesses)" selected: "\(self.numberOfProcesses)"
)) ))
self.addSubview(SelectRow( 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), frame: NSRect(
title: LocalizedString("Reader type"), 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), action: #selector(changeReaderType),
items: NetworkReaders, items: NetworkReaders,
selected: self.readerType selected: self.readerType
@@ -82,7 +92,7 @@ internal class Settings: NSView, Settings_v {
private func addInterfaceSelector() { private func addInterfaceSelector() {
let view: NSView = NSView(frame: NSRect(x: Constants.Settings.margin, y: Constants.Settings.margin, width: self.frame.width, height: 30)) 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.font = NSFont.systemFont(ofSize: 13, weight: .light)
rowTitle.textColor = .textColor rowTitle.textColor = .textColor

View File

@@ -30,7 +30,7 @@ public struct RAM_Usage: value_t {
var pressureLevel: Int var pressureLevel: Int
var swap: Swap var swap: Swap
public var widget_value: Double { public var widgetValue: Double {
get { get {
return self.usage return self.usage
} }

View File

@@ -122,13 +122,13 @@ internal class Popup: NSView, Popup_p {
width: container.frame.height, width: container.frame.height,
height: container.frame.height height: container.frame.height
), segments: [], drawValue: true) ), segments: [], drawValue: true)
self.circle!.toolTip = LocalizedString("Memory usage") self.circle!.toolTip = localizedString("Memory usage")
container.addSubview(self.circle!) container.addSubview(self.circle!)
let centralWidth: CGFloat = self.dashboardHeight-20 let centralWidth: CGFloat = self.dashboardHeight-20
let sideWidth: CGFloat = (view.frame.width - centralWidth - (Constants.Popup.margins*2))/2 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 = 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(self.level!)
view.addSubview(container) view.addSubview(container)
@@ -138,7 +138,7 @@ internal class Popup: NSView, Popup_p {
private func initChart() -> NSView { private func initChart() -> NSView {
let view: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: self.chartHeight)) 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)) let container: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: separator.frame.origin.y))
container.wantsLayer = true container.wantsLayer = true
container.layer?.backgroundColor = NSColor.lightGray.withAlphaComponent(0.1).cgColor container.layer?.backgroundColor = NSColor.lightGray.withAlphaComponent(0.1).cgColor
@@ -155,15 +155,15 @@ internal class Popup: NSView, Popup_p {
private func initDetails() -> NSView { private func initDetails() -> NSView {
let view: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: self.detailsHeight)) 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)) 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.usedField = popupRow(container, n: 5, title: "\(localizedString("Used")):", value: "").1
self.appField = PopupWithColorRow(container, color: NSColor.systemBlue, n: 4, title: "\(LocalizedString("App")):", value: "") 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.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.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.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.swapField = popupRow(container, n: 0, title: "\(localizedString("Swap")):", value: "").1
view.addSubview(separator) view.addSubview(separator)
view.addSubview(container) view.addSubview(container)
@@ -173,7 +173,7 @@ internal class Popup: NSView, Popup_p {
private func initProcesses() -> NSView { private func initProcesses() -> NSView {
let view: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: self.processesHeight)) 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)) let container: NSView = NSView(frame: NSRect(x: 0, y: 0, width: self.frame.width, height: separator.frame.origin.y))
for i in 0..<self.numberOfProcesses { for i in 0..<self.numberOfProcesses {
@@ -263,7 +263,7 @@ public class PressureView: NSView {
private let segments: [circle_segment] = [ private let segments: [circle_segment] = [
circle_segment(value: 1/3, color: NSColor.systemGreen), circle_segment(value: 1/3, color: NSColor.systemGreen),
circle_segment(value: 1/3, color: NSColor.systemYellow), circle_segment(value: 1/3, color: NSColor.systemYellow),
circle_segment(value: 1/3, color: NSColor.systemRed), circle_segment(value: 1/3, color: NSColor.systemRed)
] ]
private var level: Int = 1 private var level: Int = 1
@@ -305,7 +305,7 @@ public class PressureView: NSView {
switch self.level { switch self.level {
case 1: // NORMAL case 1: // NORMAL
needlePath.move(to: CGPoint(x: self.bounds.width * 0.15, y: self.bounds.width * 0.40)) needlePath.move(to: CGPoint(x: self.bounds.width * 0.15, y: self.bounds.width * 0.40))
needlePath.line(to: CGPoint(x: self.bounds.width/2 , y: self.bounds.height/2 - needleEndSize)) needlePath.line(to: CGPoint(x: self.bounds.width/2, y: self.bounds.height/2 - needleEndSize))
needlePath.line(to: CGPoint(x: self.bounds.width/2, y: self.bounds.height/2 + needleEndSize)) needlePath.line(to: CGPoint(x: self.bounds.width/2, y: self.bounds.height/2 + needleEndSize))
case 2: // WARN case 2: // WARN
needlePath.move(to: CGPoint(x: self.bounds.width/2, y: self.bounds.width * 0.85)) needlePath.move(to: CGPoint(x: self.bounds.width/2, y: self.bounds.width * 0.85))
@@ -313,7 +313,7 @@ public class PressureView: NSView {
needlePath.line(to: CGPoint(x: self.bounds.width/2 + needleEndSize, y: self.bounds.height/2)) needlePath.line(to: CGPoint(x: self.bounds.width/2 + needleEndSize, y: self.bounds.height/2))
case 4: // CRITICAL case 4: // CRITICAL
needlePath.move(to: CGPoint(x: self.bounds.width * 0.85, y: self.bounds.width * 0.40)) needlePath.move(to: CGPoint(x: self.bounds.width * 0.85, y: self.bounds.width * 0.40))
needlePath.line(to: CGPoint(x: self.bounds.width/2 , y: self.bounds.height/2 - needleEndSize)) needlePath.line(to: CGPoint(x: self.bounds.width/2, y: self.bounds.height/2 - needleEndSize))
needlePath.line(to: CGPoint(x: self.bounds.width/2, y: self.bounds.height/2 + needleEndSize)) needlePath.line(to: CGPoint(x: self.bounds.width/2, y: self.bounds.height/2 + needleEndSize))
default: break default: break
} }

View File

@@ -58,13 +58,13 @@ internal class UsageReader: Reader<RAM_Usage> {
let used = active + inactive + speculative + wired + compressed - purgeable - external let used = active + inactive + speculative + wired + compressed - purgeable - external
let free = self.totalSize - used let free = self.totalSize - used
var int_size: size_t = MemoryLayout<uint>.size var intSize: size_t = MemoryLayout<uint>.size
var pressureLevel: Int = 0 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<xsw_usage>.size var stringSize: size_t = MemoryLayout<xsw_usage>.size
var swap: xsw_usage = xsw_usage() 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( self.callback(RAM_Usage(
total: self.totalSize, total: self.totalSize,
@@ -145,7 +145,7 @@ public class ProcessReader: Reader<[TopProcess]> {
} }
var processes: [TopProcess] = [] var processes: [TopProcess] = []
output.enumerateLines { (line, _) -> () in output.enumerateLines { (line, _) -> Void in
if line.matches("^\\d+ +.* +\\d+[A-Z]*\\+?\\-? *$") { if line.matches("^\\d+ +.* +\\d+[A-Z]*\\+?\\-? *$") {
var str = line.trimmingCharacters(in: .whitespaces) var str = line.trimmingCharacters(in: .whitespaces)
let pidString = str.findAndCrop(pattern: "^\\d+") let pidString = str.findAndCrop(pattern: "^\\d+")
@@ -154,7 +154,7 @@ public class ProcessReader: Reader<[TopProcess]> {
command = command.replacingOccurrences(of: usageString, with: "") command = command.replacingOccurrences(of: usageString, with: "")
if let regex = try? NSRegularExpression(pattern: " (\\+|\\-)*$", options: .caseInsensitive) { 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 let pid = Int(pidString.filter("01234567890.".contains)) ?? 0

View File

@@ -49,17 +49,22 @@ internal class Settings: NSView, Settings_v {
let rowHeight: CGFloat = 30 let rowHeight: CGFloat = 30
let num: CGFloat = 1 let num: CGFloat = 1
self.addSubview(SelectTitleRow( 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), frame: NSRect(
title: LocalizedString("Update interval"), 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), action: #selector(changeUpdateInterval),
items: ReaderUpdateIntervals.map{ "\($0) sec" }, items: ReaderUpdateIntervals.map{ "\($0) sec" },
selected: "\(self.updateIntervalValue) 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), 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), action: #selector(changeNumberOfProcesses),
items: NumbersOfProcesses.map{ "\($0)" }, items: NumbersOfProcesses.map{ "\($0)" },
selected: "\(self.numberOfProcesses)" selected: "\(self.numberOfProcesses)"

View File

@@ -58,7 +58,7 @@ public class Sensors: Module {
} }
private func checkIfNoSensorsEnabled() { 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]) NotificationCenter.default.post(name: .toggleModule, object: nil, userInfo: ["module": self.config.name, "state": false])
} }
} }

View File

@@ -54,13 +54,13 @@ internal class Popup: NSView, Popup_p {
let height: CGFloat = CGFloat((22*filtered.count)) + Constants.Popup.separatorHeight 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 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) view.addSubview(separator)
var i: CGFloat = 0 var i: CGFloat = 0
groups.reversed().forEach { (group: SensorGroup) in groups.reversed().forEach { (group: SensorGroup) in
filtered.reversed().filter{ $0.group == group }.forEach { (s: Sensor_t) 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 key.toolTip = s.key
self.list[s.key] = value self.list[s.key] = value
i += 1 i += 1
@@ -77,7 +77,7 @@ internal class Popup: NSView, Popup_p {
internal func usageCallback(_ values: [Sensor_t]) { internal func usageCallback(_ values: [Sensor_t]) {
DispatchQueue.main.async(execute: { DispatchQueue.main.async(execute: {
if (self.window?.isVisible ?? false) { if self.window?.isVisible ?? false {
values.forEach { (s: Sensor_t) in values.forEach { (s: Sensor_t) in
if self.list[s.key] != nil { if self.list[s.key] != nil {
self.list[s.key]?.stringValue = s.formattedValue self.list[s.key]?.stringValue = s.formattedValue

View File

@@ -68,9 +68,9 @@ internal class Settings: NSView, Settings_v {
height: height height: height
)) ))
self.addSubview(SelectTitleRow( self.addSubview(selectTitleRow(
frame: NSRect(x: Constants.Settings.margin, y: height - rowHeight, width: view.frame.width, height: rowHeight), 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), action: #selector(changeUpdateInterval),
items: ReaderUpdateIntervals.map{ "\($0) sec" }, items: ReaderUpdateIntervals.map{ "\($0) sec" },
selected: "\(self.updateIntervalValue) sec" selected: "\(self.updateIntervalValue) sec"
@@ -88,7 +88,7 @@ internal class Settings: NSView, Settings_v {
groups.reversed().forEach { (group: SensorGroup) in groups.reversed().forEach { (group: SensorGroup) in
filtered.reversed().filter{ $0.group == group }.forEach { (s: Sensor_t) 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), frame: NSRect(x: 0, y: y, width: view.frame.width, height: rowHeight),
title: s.name, title: s.name,
action: #selector(self.handleSelection), 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 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.font = NSFont.systemFont(ofSize: 14, weight: .regular)
rowTitle.textColor = .secondaryLabelColor rowTitle.textColor = .secondaryLabelColor
rowTitle.alignment = .center rowTitle.alignment = .center
@@ -127,7 +127,7 @@ internal class Settings: NSView, Settings_v {
state = sender is NSButton ? (sender as! NSButton).state: nil 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() self.callback()
} }

View File

@@ -103,7 +103,7 @@ struct Sensor_t {
// List of keys: https://github.com/acidanthera/VirtualSMC/blob/master/Docs/SMCSensorKeys.txt // List of keys: https://github.com/acidanthera/VirtualSMC/blob/master/Docs/SMCSensorKeys.txt
let SensorsList: [Sensor_t] = [ let SensorsList: [Sensor_t] = [
/// Temperature // Temperature
Sensor_t(key: "TA%P", name: "Ambient %", group: .sensor, type: .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: "Th%H", name: "Heatpipe %", group: .sensor, type: .temperature),
Sensor_t(key: "TZ%C", name: "Termal zone %", 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: "TN0H", name: "Northbridge heatsink", group: .system, type: .temperature),
Sensor_t(key: "TN0P", name: "Northbridge proximity", 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: "VCAC", name: "CPU IA", group: .CPU, type: .voltage),
Sensor_t(key: "VCSC", name: "CPU System Agent", 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), 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: "VV9S", name: "12V", group: .sensor, type: .voltage),
Sensor_t(key: "VeES", name: "PCI 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: "PC0C", name: "CPU Core", group: .CPU, type: .power),
Sensor_t(key: "PCAM", name: "CPU Core (IMON)", 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), 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: "PDTR", name: "DC In", group: .sensor, type: .power),
Sensor_t(key: "PSTR", name: "System total", group: .sensor, type: .power), Sensor_t(key: "PSTR", name: "System total", group: .sensor, type: .power),
/// Fans // Fans
Sensor_t(key: "F%Ac", name: "Fan #%", group: .sensor, type: .fan), Sensor_t(key: "F%Ac", name: "Fan #%", group: .sensor, type: .fan)
] ]

View File

@@ -987,6 +987,7 @@
9AB54DAE22A19F96006192E0 /* Copy Files */, 9AB54DAE22A19F96006192E0 /* Copy Files */,
9A6698E72326AB16001D00E1 /* Embed Frameworks */, 9A6698E72326AB16001D00E1 /* Embed Frameworks */,
9AECEF3D24ACF98800DB95D4 /* Copy Files */, 9AECEF3D24ACF98800DB95D4 /* Copy Files */,
9A88E2672659002E00E2B7B0 /* ShellScript */,
); );
buildRules = ( buildRules = (
); );
@@ -1434,6 +1435,26 @@
}; };
/* End PBXResourcesBuildPhase section */ /* 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 */ /* Begin PBXSourcesBuildPhase section */
9A0C82D624460F7200FAE3D4 /* Sources */ = { 9A0C82D624460F7200FAE3D4 /* Sources */ = {
isa = PBXSourcesBuildPhase; isa = PBXSourcesBuildPhase;

View File

@@ -30,7 +30,7 @@ var modules: [Module] = [
Sensors(), Sensors(),
Fans(), Fans(),
Network(), Network(),
Battery(), Battery()
] ]
var log = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "Stats") var log = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "Stats")
@@ -60,6 +60,9 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele
func applicationWillTerminate(_ aNotification: Notification) { func applicationWillTerminate(_ aNotification: Notification) {
modules.forEach{ $0.terminate() } modules.forEach{ $0.terminate() }
}
deinit {
NotificationCenter.default.removeObserver(self) NotificationCenter.default.removeObserver(self)
} }

View File

@@ -104,12 +104,12 @@ class ApplicationSettings: NSScrollView {
let statsVersion: NSTextField = TextView(frame: NSRect(x: 0, y: 0, width: view.frame.width, height: 16)) let statsVersion: NSTextField = TextView(frame: NSRect(x: 0, y: 0, width: view.frame.width, height: 16))
statsVersion.alignment = .center statsVersion.alignment = .center
statsVersion.font = NSFont.systemFont(ofSize: 12, weight: .regular) statsVersion.font = NSFont.systemFont(ofSize: 12, weight: .regular)
statsVersion.stringValue = "\(LocalizedString("Version")) \(versionNumber)" statsVersion.stringValue = "\(localizedString("Version")) \(versionNumber)"
statsVersion.isSelectable = true statsVersion.isSelectable = true
statsVersion.toolTip = "Build number: \(buildNumber)" statsVersion.toolTip = "Build number: \(buildNumber)"
let button: NSButton = NSButton(frame: NSRect(x: (view.frame.width - 160)/2, y: 0, width: 160, height: 30)) 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.bezelStyle = .rounded
button.target = self button.target = self
button.action = #selector(updateAction) button.action = #selector(updateAction)
@@ -162,7 +162,7 @@ class ApplicationSettings: NSScrollView {
NSLayoutConstraint.activate([ NSLayoutConstraint.activate([
grid.centerXAnchor.constraint(equalTo: view.centerXAnchor), grid.centerXAnchor.constraint(equalTo: view.centerXAnchor),
grid.centerYAnchor.constraint(equalTo: view.centerYAnchor), grid.centerYAnchor.constraint(equalTo: view.centerYAnchor)
]) ])
return view return view
@@ -172,8 +172,8 @@ class ApplicationSettings: NSScrollView {
private func updates() -> [NSView] { private func updates() -> [NSView] {
return [ return [
self.titleView(LocalizedString("Check for updates")), self.titleView(localizedString("Check for updates")),
SelectView( selectView(
action: #selector(self.toggleUpdateInterval), action: #selector(self.toggleUpdateInterval),
items: AppUpdateIntervals, items: AppUpdateIntervals,
selected: self.updateIntervalValue selected: self.updateIntervalValue
@@ -183,8 +183,8 @@ class ApplicationSettings: NSScrollView {
private func temperature() -> [NSView] { private func temperature() -> [NSView] {
return [ return [
self.titleView(LocalizedString("Temperature")), self.titleView(localizedString("Temperature")),
SelectView( selectView(
action: #selector(self.toggleTemperatureUnits), action: #selector(self.toggleTemperatureUnits),
items: TemperatureUnits, items: TemperatureUnits,
selected: self.temperatureUnitsValue selected: self.temperatureUnitsValue
@@ -194,7 +194,7 @@ class ApplicationSettings: NSScrollView {
private func dockIcon() -> [NSView] { private func dockIcon() -> [NSView] {
return [ return [
self.titleView(LocalizedString("Show icon in dock")), self.titleView(localizedString("Show icon in dock")),
self.toggleView( self.toggleView(
action: #selector(self.toggleDock), action: #selector(self.toggleDock),
state: Store.shared.bool(key: "dockIcon", defaultValue: false) state: Store.shared.bool(key: "dockIcon", defaultValue: false)
@@ -204,7 +204,7 @@ class ApplicationSettings: NSScrollView {
private func startAtLogin() -> [NSView] { private func startAtLogin() -> [NSView] {
return [ return [
self.titleView(LocalizedString("Start at login")), self.titleView(localizedString("Start at login")),
self.toggleView( self.toggleView(
action: #selector(self.toggleLaunchAtLogin), action: #selector(self.toggleLaunchAtLogin),
state: LaunchAtLogin.isEnabled state: LaunchAtLogin.isEnabled
@@ -251,7 +251,7 @@ class ApplicationSettings: NSScrollView {
} }
@objc func updateAction(_ sender: NSObject) { @objc func updateAction(_ sender: NSObject) {
updater.check() { result, error in updater.check { result, error in
if error != nil { if error != nil {
os_log(.error, log: log, "error updater.check(): %s", "\(error!.localizedDescription)") os_log(.error, log: log, "error updater.check(): %s", "\(error!.localizedDescription)")
return return

View File

@@ -89,7 +89,7 @@ class Dashboard: NSScrollView {
let osField: NSTextField = TextView(frame: NSRect(x: 0, y: 0, width: view.frame.width, height: 18)) let osField: NSTextField = TextView(frame: NSRect(x: 0, y: 0, width: view.frame.width, height: 18))
osField.alignment = .center osField.alignment = .center
osField.font = NSFont.systemFont(ofSize: 12, weight: .regular) 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 osField.isSelectable = true
container.addRow(with: [deviceImageView]) container.addRow(with: [deviceImageView])
@@ -144,7 +144,7 @@ class Dashboard: NSScrollView {
NSLayoutConstraint.activate([ NSLayoutConstraint.activate([
grid.centerXAnchor.constraint(equalTo: view.centerXAnchor), grid.centerXAnchor.constraint(equalTo: view.centerXAnchor),
grid.centerYAnchor.constraint(equalTo: view.centerYAnchor), grid.centerYAnchor.constraint(equalTo: view.centerYAnchor)
]) ])
return view return view
@@ -177,7 +177,7 @@ class Dashboard: NSScrollView {
} }
if cpu.physicalCores != nil || cpu.logicalCores != nil { if cpu.physicalCores != nil || cpu.logicalCores != nil {
if value.count != 0 { if !value.isEmpty {
value += "\n" value += "\n"
} }
@@ -194,12 +194,12 @@ class Dashboard: NSScrollView {
value += "\(mini)" value += "\(mini)"
} }
} else { } else {
value = LocalizedString("Unknown") value = localizedString("Unknown")
} }
return [ return [
self.titleView("\(LocalizedString("Processor")):"), self.titleView("\(localizedString("Processor")):"),
self.valueView(value), self.valueView(value)
] ]
} }
@@ -219,21 +219,21 @@ class Dashboard: NSScrollView {
} }
if let speed = dimm.speed { if let speed = dimm.speed {
if row.count != 0 && row.last != " " { if !row.isEmpty && row.last != " " {
row += " " row += " "
} }
row += speed row += speed
} }
if let type = dimm.type { if let type = dimm.type {
if row.count != 0 && row.last != " " { if !row.isEmpty && row.last != " " {
row += " " row += " "
} }
row += type row += type
} }
if dimm.bank != nil || dimm.channel != nil { if dimm.bank != nil || dimm.channel != nil {
if row.count != 0 && row.last != " " { if !row.isEmpty && row.last != " " {
row += " " row += " "
} }
@@ -250,12 +250,12 @@ class Dashboard: NSScrollView {
value += "\(row)\(i == dimms.count-1 ? "" : "\n")" value += "\(row)\(i == dimms.count-1 ? "" : "\n")"
} }
} else { } else {
value = LocalizedString("Unknown") value = localizedString("Unknown")
} }
return [ return [
self.titleView("\(LocalizedString("Memory")):"), self.titleView("\(localizedString("Memory")):"),
self.valueView("\(value)"), self.valueView("\(value)")
] ]
} }
@@ -263,7 +263,7 @@ class Dashboard: NSScrollView {
var value = "" var value = ""
if let gpus = SystemKit.shared.device.info.gpu { if let gpus = SystemKit.shared.device.info.gpu {
for i in 0..<gpus.count { for i in 0..<gpus.count {
var row = gpus[i].name != nil ? gpus[i].name! : LocalizedString("Unknown") var row = gpus[i].name != nil ? gpus[i].name! : localizedString("Unknown")
if let size = gpus[i].vram { if let size = gpus[i].vram {
row += " (\(size))" row += " (\(size))"
@@ -272,26 +272,26 @@ class Dashboard: NSScrollView {
value += "\(row)\(i == gpus.count-1 ? "" : "\n")" value += "\(row)\(i == gpus.count-1 ? "" : "\n")"
} }
} else { } else {
value = LocalizedString("Unknown") value = localizedString("Unknown")
} }
return [ return [
self.titleView("\(LocalizedString("Graphics")):"), self.titleView("\(localizedString("Graphics")):"),
self.valueView(value), self.valueView(value)
] ]
} }
private func disk() -> [NSView] { private func disk() -> [NSView] {
return [ return [
self.titleView("\(LocalizedString("Disk")):"), self.titleView("\(localizedString("Disk")):"),
self.valueView("\(SystemKit.shared.device.info.disk?.model ?? SystemKit.shared.device.info.disk?.name ?? LocalizedString("Unknown"))"), self.valueView("\(SystemKit.shared.device.info.disk?.model ?? SystemKit.shared.device.info.disk?.name ?? localizedString("Unknown"))")
] ]
} }
private func serialNumber() -> [NSView] { private func serialNumber() -> [NSView] {
return [ return [
self.titleView("\(LocalizedString("Serial number")):"), self.titleView("\(localizedString("Serial number")):"),
self.valueView("\(SystemKit.shared.device.serialNumber ?? LocalizedString("Unknown"))"), self.valueView("\(SystemKit.shared.device.serialNumber ?? localizedString("Unknown"))")
] ]
} }
@@ -301,7 +301,7 @@ class Dashboard: NSScrollView {
form.unitsStyle = .full form.unitsStyle = .full
form.allowedUnits = [.day, .hour, .minute] form.allowedUnits = [.day, .hour, .minute]
var value = LocalizedString("Unknown") var value = localizedString("Unknown")
if let bootDate = SystemKit.shared.device.bootDate { if let bootDate = SystemKit.shared.device.bootDate {
if let duration = form.string(from: bootDate, to: Date()) { if let duration = form.string(from: bootDate, to: Date()) {
value = duration value = duration
@@ -312,8 +312,8 @@ class Dashboard: NSScrollView {
self.uptimeField = valueView self.uptimeField = valueView
return [ return [
self.titleView("\(LocalizedString("Uptime")):"), self.titleView("\(localizedString("Uptime")):"),
valueView, valueView
] ]
} }

View File

@@ -18,11 +18,11 @@ class SettingsWindow: NSWindow, NSWindowDelegate {
init() { init() {
super.init( super.init(
contentRect: NSMakeRect( contentRect: NSRect(
NSScreen.main!.frame.width - self.viewController.view.frame.width, x: NSScreen.main!.frame.width - self.viewController.view.frame.width,
NSScreen.main!.frame.height - self.viewController.view.frame.height, y: NSScreen.main!.frame.height - self.viewController.view.frame.height,
self.viewController.view.frame.width, width: self.viewController.view.frame.width,
self.viewController.view.frame.height height: self.viewController.view.frame.height
), ),
styleMask: [.closable, .titled, .miniaturizable, .fullSizeContentView], styleMask: [.closable, .titled, .miniaturizable, .fullSizeContentView],
backing: .buffered, backing: .buffered,
@@ -61,7 +61,7 @@ class SettingsWindow: NSWindow, NSWindowDelegate {
public func setModules() { public func setModules() {
self.viewController.setModules(modules) 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) self.setIsVisible(true)
} }
} }
@@ -123,7 +123,7 @@ private class SettingsView: NSView {
NotificationCenter.default.addObserver(self, selector: #selector(menuCallback), name: .openModuleSettings, object: nil) 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.material = .sidebar
sidebar.blendingMode = .behindWindow sidebar.blendingMode = .behindWindow
sidebar.state = .active 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.frame = NSRect(x: 0, y: 0, width: self.sidebarWidth, height: navigationHeight)
self.navigationView.wantsLayer = true 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(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(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(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(1, title: localizedString("Close application"), image: "power", action: #selector(closeApp)))
self.mainView.frame = NSRect( self.mainView.frame = NSRect(
x: self.sidebarWidth + 1, // separation line x: self.sidebarWidth + 1, // separation line
@@ -170,8 +170,8 @@ private class SettingsView: NSView {
super.draw(dirtyRect) super.draw(dirtyRect)
let line = NSBezierPath() let line = NSBezierPath()
line.move(to: NSMakePoint(self.sidebarWidth, 0)) line.move(to: NSPoint(x: self.sidebarWidth, y: 0))
line.line(to: NSMakePoint(self.sidebarWidth, self.frame.height)) line.line(to: NSPoint(x: self.sidebarWidth, y: self.frame.height))
line.lineWidth = 1 line.lineWidth = 1
NSColor.black.set() NSColor.black.set()
@@ -243,7 +243,12 @@ private class SettingsView: NSView {
button.focusRingType = .none button.focusRingType = .none
let rect = NSRect(x: Int(self.sidebarWidth) - (45*n), y: 0, width: 44, height: 44) 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) self.addTrackingArea(trackingArea)
return button 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)) super.init(frame: NSRect(x: 0, y: self.height*CGFloat(n), width: width, height: self.height))
self.wantsLayer = true self.wantsLayer = true
self.layer?.backgroundColor = .clear 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 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) self.addTrackingArea(trackingArea)
let imageView = NSImageView() let imageView = NSImageView()
@@ -295,7 +305,7 @@ private class MenuView: NSView {
imageView.wantsLayer = true imageView.wantsLayer = true
imageView.contentTintColor = .labelColor 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.alignment = .natural
titleView.textColor = .labelColor titleView.textColor = .labelColor
titleView.font = NSFont.systemFont(ofSize: 13, weight: .regular) titleView.font = NSFont.systemFont(ofSize: 13, weight: .regular)

View File

@@ -20,11 +20,11 @@ class UpdateWindow: NSWindow, NSWindowDelegate {
let w = NSScreen.main!.frame.width let w = NSScreen.main!.frame.width
let h = NSScreen.main!.frame.height let h = NSScreen.main!.frame.height
super.init( super.init(
contentRect: NSMakeRect( contentRect: NSRect(
w - self.viewController.view.frame.width, x: w - self.viewController.view.frame.width,
h - self.viewController.view.frame.height, y: h - self.viewController.view.frame.height,
self.viewController.view.frame.width, width: self.viewController.view.frame.width,
self.viewController.view.frame.height height: self.viewController.view.frame.height
), ),
styleMask: [.closable, .titled, .fullSizeContentView], styleMask: [.closable, .titled, .fullSizeContentView],
backing: .buffered, 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)) super.init(frame: CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.width, height: frame.height))
self.wantsLayer = true 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.material = .sidebar
sidebar.blendingMode = .behindWindow sidebar.blendingMode = .behindWindow
sidebar.state = .active 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)) 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.font = NSFont.systemFont(ofSize: 14, weight: .medium)
title.alignment = .center 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)) let versions: NSGridView = NSGridView(frame: NSRect(x: (view.frame.width-180)/2, y: 54, width: 180, height: 32))
versions.rowSpacing = 0 versions.rowSpacing = 0
@@ -112,12 +112,12 @@ private class UpdateView: NSView {
versions.xPlacement = .fill versions.xPlacement = .fill
let currentVersionTitle: NSTextField = TextView(frame: NSRect(x: 0, y: 0, width: 0, height: 16)) 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)) let currentVersion: NSTextField = TextView(frame: NSRect(x: 0, y: 0, width: 0, height: 0))
currentVersion.stringValue = version.current currentVersion.stringValue = version.current
let latestVersionTitle: NSTextField = TextView(frame: NSRect(x: 0, y: 0, width: 0, height: 16)) 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)) let latestVersion: NSTextField = TextView(frame: NSRect(x: 0, y: 0, width: 0, height: 0))
latestVersion.stringValue = version.latest latestVersion.stringValue = version.latest
@@ -125,19 +125,19 @@ private class UpdateView: NSView {
versions.addRow(with: [latestVersionTitle, latestVersion]) versions.addRow(with: [latestVersionTitle, latestVersion])
let closeButton: NSButton = NSButton(frame: NSRect(x: 0, y: 0, width: view.frame.width/2, height: 26)) 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.bezelStyle = .rounded
closeButton.action = #selector(self.close) closeButton.action = #selector(self.close)
closeButton.target = self closeButton.target = self
let changelogButton: NSButton = NSButton(frame: NSRect(x: 0, y: 0, width: 0, height: 26)) 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.bezelStyle = .rounded
changelogButton.action = #selector(self.changelog) changelogButton.action = #selector(self.changelog)
changelogButton.target = self changelogButton.target = self
let downloadButton: NSButton = NSButton(frame: NSRect(x: view.frame.width/2, y: 0, width: view.frame.width/2, height: 26)) 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.bezelStyle = .rounded
downloadButton.action = #selector(self.download) downloadButton.action = #selector(self.download)
downloadButton.target = self 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)) 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.font = NSFont.systemFont(ofSize: 14, weight: .light)
title.alignment = .center 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)) 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.bezelStyle = .rounded
button.action = #selector(self.close) button.action = #selector(self.close)
button.target = self 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)) 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.font = NSFont.systemFont(ofSize: 14, weight: .semibold)
title.alignment = .center title.alignment = .center
title.stringValue = LocalizedString("Downloading...") title.stringValue = localizedString("Downloading...")
let progressBar: NSProgressIndicator = NSProgressIndicator() let progressBar: NSProgressIndicator = NSProgressIndicator()
progressBar.frame = NSRect(x: 20, y: 64, width: view.frame.width - 40, height: 22) 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%" state.stringValue = "0%"
let closeButton: NSButton = NSButton(frame: NSRect(x: 0, y: 0, width: view.frame.width, height: 26)) 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.bezelStyle = .rounded
closeButton.action = #selector(self.close) closeButton.action = #selector(self.close)
closeButton.target = self closeButton.target = self
let installButton: NSButton = NSButton(frame: NSRect(x: view.frame.width/2, y: 0, width: view.frame.width/2, height: 26)) 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.bezelStyle = .rounded
installButton.action = #selector(self.install) installButton.action = #selector(self.install)
installButton.target = self installButton.target = self

View File

@@ -66,10 +66,10 @@ extension AppDelegate {
return return
} }
if IsNewestVersion(currentVersion: prevVersion, latestVersion: currentVersion) { if isNewestVersion(currentVersion: prevVersion, latestVersion: currentVersion) {
_ = showNotification( _ = showNotification(
title: LocalizedString("Successfully updated"), title: localizedString("Successfully updated"),
subtitle: LocalizedString("Stats was updated to v", currentVersion), subtitle: localizedString("Stats was updated to v", currentVersion),
id: "updated-from-\(prevVersion)-to-\(currentVersion)" id: "updated-from-\(prevVersion)-to-\(currentVersion)"
) )
} }
@@ -97,7 +97,7 @@ extension AppDelegate {
} }
internal func checkForNewVersion() { internal func checkForNewVersion() {
updater.check() { result, error in updater.check { result, error in
if error != nil { if error != nil {
os_log(.error, log: log, "error updater.check(): %s", "\(error!.localizedDescription)") os_log(.error, log: log, "error updater.check(): %s", "\(error!.localizedDescription)")
return return
@@ -113,12 +113,12 @@ extension AppDelegate {
os_log(.debug, log: log, "show update window because new version of app found: %s", "\(version.latest)") 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.identifier = "new-version-\(version.latest)"
self.updateNotification.title = LocalizedString("New version available") self.updateNotification.title = localizedString("New version available")
self.updateNotification.subtitle = LocalizedString("Click to install the new version of Stats") self.updateNotification.subtitle = localizedString("Click to install the new version of Stats")
self.updateNotification.soundName = NSUserNotificationDefaultSoundName self.updateNotification.soundName = NSUserNotificationDefaultSoundName
self.updateNotification.hasActionButton = true self.updateNotification.hasActionButton = true
self.updateNotification.actionButtonTitle = LocalizedString("Install") self.updateNotification.actionButtonTitle = localizedString("Install")
self.updateNotification.userInfo = ["url": version.url] self.updateNotification.userInfo = ["url": version.url]
NSUserNotificationCenter.default.delegate = self NSUserNotificationCenter.default.delegate = self

View File

@@ -124,6 +124,7 @@ public class NetworkChartView: NSView {
fatalError("init(coder:) has not been implemented") fatalError("init(coder:) has not been implemented")
} }
// swiftlint:disable function_body_length
public override func draw(_ dirtyRect: NSRect) { public override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect) super.draw(dirtyRect)

View File

@@ -31,6 +31,7 @@ internal enum SMCDataType: String {
case FDS = "{fds" case FDS = "{fds"
} }
// swiftlint:disable identifier_name
internal enum SMCKeys: UInt8 { internal enum SMCKeys: UInt8 {
case KERNEL_INDEX = 2 case KERNEL_INDEX = 2
case READ_BYTES = 5 case READ_BYTES = 5
@@ -116,21 +117,21 @@ public class SMC {
let matchingDictionary: CFMutableDictionary = IOServiceMatching("AppleSMC") let matchingDictionary: CFMutableDictionary = IOServiceMatching("AppleSMC")
result = IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDictionary, &iterator) 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")) print("Error IOServiceGetMatchingServices(): " + (String(cString: mach_error_string(result), encoding: String.Encoding.ascii) ?? "unknown error"))
return return
} }
device = IOIteratorNext(iterator) device = IOIteratorNext(iterator)
IOObjectRelease(iterator) IOObjectRelease(iterator)
if (device == 0) { if device == 0 {
print("Error IOIteratorNext(): " + (String(cString: mach_error_string(result), encoding: String.Encoding.ascii) ?? "unknown error")) print("Error IOIteratorNext(): " + (String(cString: mach_error_string(result), encoding: String.Encoding.ascii) ?? "unknown error"))
return return
} }
result = IOServiceOpen(device, mach_task_self_, 0, &conn) result = IOServiceOpen(device, mach_task_self_, 0, &conn)
IOObjectRelease(device) IOObjectRelease(device)
if (result != kIOReturnSuccess) { if result != kIOReturnSuccess {
print("Error IOServiceOpen(): " + (String(cString: mach_error_string(result), encoding: String.Encoding.ascii) ?? "unknown error")) print("Error IOServiceOpen(): " + (String(cString: mach_error_string(result), encoding: String.Encoding.ascii) ?? "unknown error"))
return return
} }
@@ -138,7 +139,7 @@ public class SMC {
deinit { deinit {
let result = self.close() 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")) 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 return nil
} }
if (val.dataSize > 0) { if val.dataSize > 0 {
if val.bytes.first(where: { $0 != 0}) == nil && val.key != "FS! " { if val.bytes.first(where: { $0 != 0}) == nil && val.key != "FS! " {
return nil return nil
} }
@@ -226,7 +227,7 @@ public class SMC {
return nil return nil
} }
if (val.dataSize > 0) { if val.dataSize > 0 {
if val.bytes.first(where: { $0 != 0}) == nil { if val.bytes.first(where: { $0 != 0}) == nil {
return nil return nil
} }

View File

@@ -74,7 +74,7 @@ public struct info_s {
} }
public struct device_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 modelIdentifier: String? = nil
public var serialNumber: String? = nil public var serialNumber: String? = nil
public var bootDate: Date? = nil public var bootDate: Date? = nil
@@ -111,14 +111,14 @@ public class SystemKit {
let procInfo = ProcessInfo() let procInfo = ProcessInfo()
let systemVersion = procInfo.operatingSystemVersion let systemVersion = procInfo.operatingSystemVersion
var build = LocalizedString("Unknown") var build = localizedString("Unknown")
let buildArr = procInfo.operatingSystemVersionString.split(separator: "(") let buildArr = procInfo.operatingSystemVersionString.split(separator: "(")
if buildArr.indices.contains(1) { if buildArr.indices.contains(1) {
build = buildArr[1].replacingOccurrences(of: "Build ", with: "").replacingOccurrences(of: ")", with: "") build = buildArr[1].replacingOccurrences(of: "Build ", with: "").replacingOccurrences(of: ")", with: "")
} }
let version = systemVersion.majorVersion > 10 ? "\(systemVersion.majorVersion)" : "\(systemVersion.majorVersion).\(systemVersion.minorVersion)" 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.cpu = self.getCPUInfo()
self.device.info.ram = self.getRamInfo() self.device.info.ram = self.getRamInfo()
@@ -180,7 +180,7 @@ public class SystemKit {
var sizeOfName = 0 var sizeOfName = 0
sysctlbyname("machdep.cpu.brand_string", nil, &sizeOfName, nil, 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) sysctlbyname("machdep.cpu.brand_string", &nameCharts, &sizeOfName, nil, 0)
var name = String(cString: nameCharts) var name = String(cString: nameCharts)
if name != "" { if name != "" {
@@ -222,7 +222,7 @@ public class SystemKit {
var list: [gpu_s] = [] var list: [gpu_s] = []
do { do {
if let json = try JSONSerialization.jsonObject(with: Data(res.utf8), options: []) as? [String: Any] { 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 { for obj in arr {
var gpu: gpu_s = gpu_s() var gpu: gpu_s = gpu_s()
@@ -253,10 +253,8 @@ public class SystemKit {
let keys: [URLResourceKey] = [.volumeNameKey] let keys: [URLResourceKey] = [.volumeNameKey]
let paths = FileManager.default.mountedVolumeURLs(includingResourceValuesForKeys: keys)! let paths = FileManager.default.mountedVolumeURLs(includingResourceValuesForKeys: keys)!
if let session = DASessionCreate(kCFAllocatorDefault) { if let session = DASessionCreate(kCFAllocatorDefault) {
for url in paths { for url in paths where url.pathComponents.count == 1 {
if url.pathComponents.count == 1 { disk = DADiskCreateFromVolumePath(kCFAllocatorDefault, session, url as CFURL)
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] { if let json = try JSONSerialization.jsonObject(with: Data(res.utf8), options: []) as? [String: Any] {
var ram: ram_s = ram_s() 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]] { if let items = obj[0]["_items"] as? [[String: Any]] {
for i in 0..<items.count { for i in 0..<items.count {
let item = items[i] let item = items[i]
@@ -436,11 +434,11 @@ let deviceDict: [String: model_s] = [
"MacBookPro16,1": model_s(name: "MacBook Pro 16\" (Late 2019)", year: 2019, type: .macbookPro), "MacBookPro16,1": model_s(name: "MacBook Pro 16\" (Late 2019)", year: 2019, type: .macbookPro),
"MacBookPro16,2": model_s(name: "MacBook Pro 13\" (Mid 2020)", year: 2019, type: .macbookPro), "MacBookPro16,2": model_s(name: "MacBook Pro 13\" (Mid 2020)", year: 2019, type: .macbookPro),
"MacBookPro16,3": model_s(name: "MacBook Pro 13\" (Mid 2020)", year: 2020, type: .macbookPro), "MacBookPro16,3": model_s(name: "MacBook Pro 13\" (Mid 2020)", year: 2020, type: .macbookPro),
"MacBookPro17,1": model_s(name: "MacBook Pro 13\" (M1, 2020)", year: 2020, type: .macbookPro), "MacBookPro17,1": model_s(name: "MacBook Pro 13\" (M1, 2020)", year: 2020, type: .macbookPro)
] ]
let osDict: [String: String] = [ let osDict: [String: String] = [
"10.14": "Mojave", "10.14": "Mojave",
"10.15": "Catalina", "10.15": "Catalina",
"11": "Big Sur", "11": "Big Sur"
] ]

View File

@@ -8,6 +8,7 @@
// //
// Copyright © 2020 Serhiy Mytrovtsiy. All rights reserved. // Copyright © 2020 Serhiy Mytrovtsiy. All rights reserved.
// //
// swiftlint:disable file_length
import Cocoa import Cocoa
@@ -37,22 +38,24 @@ extension String: LocalizedError {
} }
public mutating func findAndCrop(pattern: String) -> String { public mutating func findAndCrop(pattern: String) -> String {
let regex = try! NSRegularExpression(pattern: pattern) do {
let stringRange = NSRange(location: 0, length: self.utf16.count) let regex = try NSRegularExpression(pattern: pattern)
var line = self 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) if let searchRange = regex.firstMatch(in: self, options: [], range: stringRange) {
let end = self.index(self.startIndex, offsetBy: searchRange.range.upperBound) let start = self.index(self.startIndex, offsetBy: searchRange.range.lowerBound)
let value = String(self[start..<end]).trimmingCharacters(in: .whitespaces) let end = self.index(self.startIndex, offsetBy: searchRange.range.upperBound)
line = self.replacingOccurrences( let value = String(self[start..<end]).trimmingCharacters(in: .whitespaces)
of: value, line = self.replacingOccurrences(
with: "", of: value,
options: .regularExpression with: "",
) options: .regularExpression
self = line.trimmingCharacters(in: .whitespaces) )
return value.trimmingCharacters(in: .whitespaces) self = line.trimmingCharacters(in: .whitespaces)
} return value.trimmingCharacters(in: .whitespaces)
}
} catch {}
return "" return ""
} }
@@ -81,7 +84,7 @@ extension String: LocalizedError {
public func removedRegexMatches(pattern: String, replaceWith: String = "") -> String { public func removedRegexMatches(pattern: String, replaceWith: String = "") -> String {
do { do {
let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive) 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) return regex.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: replaceWith)
} catch { } catch {
return self return self
@@ -121,7 +124,7 @@ public extension Double {
return NSString(format: "%.\(decimalPlaces)f" as NSString, self) as String 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)) let divisor = pow(10.0, Double(places))
return (self * divisor).rounded() / divisor return (self * divisor).rounded() / divisor
} }
@@ -189,7 +192,7 @@ public extension Double {
func secondsToHoursMinutesSeconds() -> (Int, Int) { func secondsToHoursMinutesSeconds() -> (Int, Int) {
let mins = (self.truncatingRemainder(dividingBy: 3600)) / 60 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 { 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 row: NSView = NSView(frame: frame)
let state: NSControl.StateValue = state ? .on : .off let state: NSControl.StateValue = state ? .on : .off
@@ -272,7 +275,7 @@ public extension NSView {
return row 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 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) 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 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 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) 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.font = NSFont.systemFont(ofSize: 13, weight: .light)
rowTitle.textColor = .textColor rowTitle.textColor = .textColor
let select: NSPopUpButton = NSPopUpButton(frame: NSRect(x: row.frame.width - 50, y: (row.frame.height-26)/2, width: 50, height: 26)) let select: NSPopUpButton = selectView(action: action, items: items, selected: selected)
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
select.sizeToFit() select.sizeToFit()
rowTitle.setFrameSize(NSSize(width: row.frame.width - select.frame.width, height: rowTitle.frame.height)) rowTitle.setFrameSize(NSSize(width: row.frame.width - select.frame.width, height: rowTitle.frame.height))
@@ -350,29 +336,7 @@ public extension NSView {
return row return row
} }
func SelectRow(frame: NSRect, title: String, action: Selector, items: [KeyValue_p], selected: String) -> NSView { func selectView(action: Selector, items: [KeyValue_p], selected: String) -> NSPopUpButton {
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 {
let select: NSPopUpButton = NSPopUpButton(frame: NSRect(x: 0, y: 0, width: 50, height: 26)) let select: NSPopUpButton = NSPopUpButton(frame: NSRect(x: 0, y: 0, width: 50, height: 26))
select.target = self select.target = self
select.action = action select.action = action
@@ -382,7 +346,7 @@ public extension NSView {
if item.key.contains("separator") { if item.key.contains("separator") {
menu.addItem(NSMenuItem.separator()) menu.addItem(NSMenuItem.separator())
} else { } 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 interfaceMenu.representedObject = item.key
menu.addItem(interfaceMenu) menu.addItem(interfaceMenu)
if selected == item.key { if selected == item.key {
@@ -439,6 +403,7 @@ extension URL {
} }
} }
// swiftlint:disable large_tuple
extension UInt32 { extension UInt32 {
init(bytes: (UInt8, UInt8, UInt8, UInt8)) { init(bytes: (UInt8, UInt8, UInt8, UInt8)) {
self = UInt32(bytes.0) << 24 | UInt32(bytes.1) << 16 | UInt32(bytes.2) << 8 | UInt32(bytes.3) 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) { convenience init(hexString: String, alpha: CGFloat = 1.0) {
let hexString: String = hexString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) let hexString: String = hexString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
let scanner = Scanner(string: hexString) let scanner = Scanner(string: hexString)
if (hexString.hasPrefix("#")) { if hexString.hasPrefix("#") {
scanner.scanLocation = 1 scanner.scanLocation = 1
} }
var color: UInt32 = 0 var color: UInt32 = 0
@@ -484,17 +449,7 @@ public extension NSColor {
let red = CGFloat(r) / 255.0 let red = CGFloat(r) / 255.0
let green = CGFloat(g) / 255.0 let green = CGFloat(g) / 255.0
let blue = CGFloat(b) / 255.0 let blue = CGFloat(b) / 255.0
self.init(red:red, green:green, blue:blue, alpha:alpha) 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)
} }
} }
@@ -536,7 +491,7 @@ public final class ScrollableStackView: NSView {
scrollView.leftAnchor.constraint(equalTo: self.leftAnchor), scrollView.leftAnchor.constraint(equalTo: self.leftAnchor),
scrollView.rightAnchor.constraint(equalTo: self.rightAnchor), scrollView.rightAnchor.constraint(equalTo: self.rightAnchor),
scrollView.topAnchor.constraint(equalTo: self.topAnchor), scrollView.topAnchor.constraint(equalTo: self.topAnchor),
scrollView.bottomAnchor.constraint(equalTo: self.bottomAnchor), scrollView.bottomAnchor.constraint(equalTo: self.bottomAnchor)
]) ])
clipView.drawsBackground = false clipView.drawsBackground = false
@@ -549,7 +504,7 @@ public final class ScrollableStackView: NSView {
NSLayoutConstraint.activate([ NSLayoutConstraint.activate([
stackView.leftAnchor.constraint(equalTo: clipView.leftAnchor), stackView.leftAnchor.constraint(equalTo: clipView.leftAnchor),
stackView.rightAnchor.constraint(equalTo: clipView.rightAnchor), 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 { if (event.modifierFlags.rawValue & NSEvent.ModifierFlags.deviceIndependentFlagsMask.rawValue) == commandKey {
switch event.charactersIgnoringModifiers! { switch event.charactersIgnoringModifiers! {
case "x": 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": 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": 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": 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": 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: default:
break break
} }
} else if (event.modifierFlags.rawValue & NSEvent.ModifierFlags.deviceIndependentFlagsMask.rawValue) == commandShiftKey { } else if (event.modifierFlags.rawValue & NSEvent.ModifierFlags.deviceIndependentFlagsMask.rawValue) == commandShiftKey {
if event.charactersIgnoringModifiers == "Z" { 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 }
} }
} }
} }

View File

@@ -8,6 +8,7 @@
// //
// Copyright © 2020 Serhiy Mytrovtsiy. All rights reserved. // Copyright © 2020 Serhiy Mytrovtsiy. All rights reserved.
// //
// swiftlint:disable file_length
import Cocoa import Cocoa
import os.log import os.log
@@ -196,8 +197,14 @@ public extension NSBezierPath {
self.line(to: end) 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 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 arrowLine1 = CGPoint(
let arrowLine2 = CGPoint(x: end.x + pointerLineLength * cos(CGFloat(Double.pi) - startEndAngle - arrowAngle), y: end.y - pointerLineLength * sin(CGFloat(Double.pi) - startEndAngle - arrowAngle)) 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.line(to: arrowLine1)
self.move(to: end) 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)) 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 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 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 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 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) 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 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)) 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 return valueView
} }
public extension Array where Element : Equatable { public extension Array where Element: Equatable {
func allEqual() -> Bool { func allEqual() -> Bool {
if let firstElem = first { if let firstElem = first {
return !dropFirst().contains { $0 != firstElem } 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] { func difference(from other: [Element]) -> [Element] {
let thisSet = Set(self) let thisSet = Set(self)
let otherSet = Set(other) 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 }) { 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 }) { 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 #available(OSX 10.15, *) {
if let checkbox = control as? NSSwitch { if let checkbox = control as? NSSwitch {
checkbox.state = state 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 #available(OSX 10.15, *) {
if let checkbox = control as? NSSwitch { if let checkbox = control as? NSSwitch {
checkbox.isEnabled = state checkbox.isEnabled = state
@@ -353,7 +360,7 @@ public func syncShell(_ args: String) -> String {
return output 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 currentNumber = currentVersion.replacingOccurrences(of: "v", with: "")
let latestNumber = latestVersion.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 return nil
} }
if (IOObjectConformsTo(parent, "IOBlockStorageDriver") == 0) { if IOObjectConformsTo(parent, "IOBlockStorageDriver") == 0 {
IOObjectRelease(parent) IOObjectRelease(parent)
return nil 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) var string = NSLocalizedString(key, comment: comment)
if !params.isEmpty { if !params.isEmpty {
for (index, param) in params.enumerated() { for (index, param) in params.enumerated() {
@@ -582,6 +589,7 @@ extension UnitTemperature {
} }
} }
// swiftlint:disable identifier_name
public func Temperature(_ value: Double) -> String { public func Temperature(_ value: Double) -> String {
let stringUnit: String = Store.shared.string(key: "temperature_units", defaultValue: "system") let stringUnit: String = Store.shared.string(key: "temperature_units", defaultValue: "system")
let formatter = MeasurementFormatter() let formatter = MeasurementFormatter()
@@ -603,7 +611,7 @@ public func Temperature(_ value: Double) -> String {
return formatter.string(from: measurement) return formatter.string(from: measurement)
} }
public func SysctlByName(_ name: String) -> Int64 { public func sysctlByName(_ name: String) -> Int64 {
var num: Int64 = 0 var num: Int64 = 0
var size = MemoryLayout<Int64>.size var size = MemoryLayout<Int64>.size

View File

@@ -20,9 +20,9 @@ public struct LaunchAtLogin {
guard let jobs = (SMCopyAllJobDictionaries(kSMDomainUserLaunchd).takeRetainedValue() as? [[String: AnyObject]]) else { guard let jobs = (SMCopyAllJobDictionaries(kSMDomainUserLaunchd).takeRetainedValue() as? [[String: AnyObject]]) else {
return false return false
} }
let job = jobs.first { $0["Label"] as! String == id } let job = jobs.first { $0["Label"] as! String == id }
return job?["OnDemand"] as? Bool ?? false return job?["OnDemand"] as? Bool ?? false
} }
set { set {

View File

@@ -13,11 +13,11 @@ import Cocoa
public enum AppUpdateInterval: String { public enum AppUpdateInterval: String {
case atStart = "At start" case atStart = "At start"
case separator_1 = "separator_1" case separator1 = "separator_1"
case oncePerDay = "Once per day" case oncePerDay = "Once per day"
case oncePerWeek = "Once per week" case oncePerWeek = "Once per week"
case oncePerMonth = "Once per month" case oncePerMonth = "Once per month"
case separator_2 = "separator_2" case separator2 = "separator_2"
case never = "Never" case never = "Never"
} }
public let AppUpdateIntervals: [KeyValue_t] = [ public let AppUpdateIntervals: [KeyValue_t] = [
@@ -38,8 +38,8 @@ public let TemperatureUnits: [KeyValue_t] = [
] ]
public enum DataSizeBase: String { public enum DataSizeBase: String {
case bit = "bit" case bit
case byte = "byte" case byte
} }
public let SpeedBase: [KeyValue_t] = [ public let SpeedBase: [KeyValue_t] = [
KeyValue_t(key: "bit", value: "Bit", additional: DataSizeBase.bit), 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: "automatic", value: "Automatic"),
KeyValue_t(key: "separator", value: "separator"), KeyValue_t(key: "separator", value: "separator"),
KeyValue_t(key: "oneRow", value: "One row"), 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] = [ public let SpeedPictogram: [KeyValue_t] = [
@@ -58,7 +58,7 @@ public let SpeedPictogram: [KeyValue_t] = [
KeyValue_t(key: "separator", value: "separator"), KeyValue_t(key: "separator", value: "separator"),
KeyValue_t(key: "dots", value: "Dots"), KeyValue_t(key: "dots", value: "Dots"),
KeyValue_t(key: "arrows", value: "Arrows"), KeyValue_t(key: "arrows", value: "Arrows"),
KeyValue_t(key: "chars", value: "Characters"), KeyValue_t(key: "chars", value: "Characters")
] ]
public let BatteryAdditionals: [KeyValue_t] = [ public let BatteryAdditionals: [KeyValue_t] = [
@@ -67,12 +67,12 @@ public let BatteryAdditionals: [KeyValue_t] = [
KeyValue_t(key: "percentage", value: "Percentage"), KeyValue_t(key: "percentage", value: "Percentage"),
KeyValue_t(key: "time", value: "Time"), KeyValue_t(key: "time", value: "Time"),
KeyValue_t(key: "percentageAndTime", value: "Percentage and 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] = [ public let ShortLong: [KeyValue_t] = [
KeyValue_t(key: "short", value: "Short"), 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] 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 typealias Bandwidth = (upload: Int64, download: Int64)
public let NetworkReaders: [KeyValue_t] = [ public let NetworkReaders: [KeyValue_t] = [
KeyValue_t(key: "interface", value: "Interface based"), 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 { 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 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 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 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 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 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) } 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] { public static var allCases: [Color] {
return [.utilization, .pressure, separator_1, return [.utilization, .pressure, separator1,
.systemAccent, .monochrome, separator_2, .systemAccent, .monochrome, separator2,
.clear, .white, .black, .gray, .secondGray, .darkGray, .lightGray, .clear, .white, .black, .gray, .secondGray, .darkGray, .lightGray,
.red, .secondRed, .green, .secondGreen, .blue, .secondBlue, .yellow, .secondYellow, .red, .secondRed, .green, .secondGreen, .blue, .secondBlue, .yellow, .secondYellow,
.orange, .secondOrange, .purple, .secondPurple, .brown, .secondBrown, .orange, .secondOrange, .purple, .secondPurple, .brown, .secondBrown,

View File

@@ -63,7 +63,7 @@ public class macAppUpdater {
return return
} }
fetchLastVersion() { result, error in fetchLastVersion { result, error in
guard error == nil else { guard error == nil else {
completionHandler(nil, error) completionHandler(nil, error)
return return
@@ -76,7 +76,7 @@ public class macAppUpdater {
let downloadURL: String = result![1] let downloadURL: String = result![1]
let lastVersion: String = result![0] 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) self.latest = version_s(current: self.currentVersion, latest: lastVersion, newest: newVersion, url: downloadURL)
completionHandler(self.latest, nil) completionHandler(self.latest, nil)
@@ -89,7 +89,7 @@ public class macAppUpdater {
return 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 } guard let data = data, error == nil else { return }
do { 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 }) { 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 } guard let fileURL = urlOrNil else { return }
do { do {
let downloadsURL = try FileManager.default.url(for: .downloadsDirectory, in: .userDomainMask, appropriateFor: nil, create: false) 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 self.copyFile(from: fileURL, to: destinationURL) { (path, error) in
if error != nil { if error != nil {
print ("copy file error: \(error ?? "copy error")") print("copy file error: \(error ?? "copy error")")
return return
} }
doneHandler(path) doneHandler(path)
} }
} catch { } catch {
print ("file error: \(error)") print("file error: \(error)")
} }
} }
@@ -176,8 +176,8 @@ public class macAppUpdater {
var toPath = to var toPath = to
let fileName = (URL(fileURLWithPath: to.absoluteString)).lastPathComponent let fileName = (URL(fileURLWithPath: to.absoluteString)).lastPathComponent
let fileExt = (URL(fileURLWithPath: to.absoluteString)).pathExtension let fileExt = (URL(fileURLWithPath: to.absoluteString)).pathExtension
var fileNameWithotSuffix : String! var fileNameWithotSuffix: String!
var newFileName : String! var newFileName: String!
var counter = 0 var counter = 0
if fileName.hasSuffix(fileExt) { if fileName.hasSuffix(fileExt) {