Skip to content

Commit

Permalink
Add config to option to show numbers in short format
Browse files Browse the repository at this point in the history
  • Loading branch information
marcingajda committed Apr 18, 2020
1 parent 50dc461 commit 5cf17cb
Show file tree
Hide file tree
Showing 9 changed files with 216 additions and 99 deletions.
187 changes: 97 additions & 90 deletions Covid-19 Status/Base.lproj/Main.storyboard

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions Covid-19 Status/src/Controller/AppController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ class AppController {
Messenger.shared.onFetchRequest {
self.display.showLoading()
self.provider?.doUpdate()
},
Messenger.shared.onFormatMethodChange { _ in
self.display.renderStats()
}
]

Expand Down
28 changes: 26 additions & 2 deletions Covid-19 Status/src/Controller/PreferencesViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ enum SettingsKey: String {
case fetchInterval
case historySize
case history
case formatMethod
}

class PreferencesViewController: NSViewController {
Expand All @@ -24,6 +25,7 @@ class PreferencesViewController: NSViewController {

@IBOutlet var intervalSelect: NSArrayController?
@IBOutlet var historySelect: NSArrayController?
@IBOutlet var formatMethodButton: NSButton?

@objc dynamic var allowedIntervals = PreferencesOptions.fetchIntervals
@objc dynamic var allowedHistorySizes = PreferencesOptions.historySizes
Expand All @@ -42,16 +44,38 @@ class PreferencesViewController: NSViewController {
Messenger.shared.dispatchHistorySize(size: value)
}

@IBAction func formatMethodChangeHandler(_ sender: NSButton) {
let newMethod: StatsFormatMethod = sender.state == .on ? .short : .long
settings.saveFormatMethod(method: newMethod)
Messenger.shared.dispatchFormatMethod(method: newMethod)
}

override func viewDidLoad() {
super.viewDidLoad()

NSApplication.shared.activate(ignoringOtherApps: true)

guard let formatMethodButton = formatMethodButton else {
ErrorHandler.standard.critical(withMessage: "The app is broken (format method button)")
return
}
guard let intervalSelect = intervalSelect else {
ErrorHandler.standard.critical(withMessage: "The app is broken (interval select)")
return
}
guard let historySelect = historySelect else {
ErrorHandler.standard.critical(withMessage: "The app is broken (history select)")
return
}

print("format method:", settings.formatMethod)
formatMethodButton.state = settings.formatMethod == .short ? .on : .off

let intervalOption = findOption(options: allowedIntervals, value: settings.fetchInterval)
intervalSelect?.setSelectedObjects([intervalOption])
intervalSelect.setSelectedObjects([intervalOption])

let historySizeOption = findOption(options: allowedHistorySizes, value: settings.historySize)
historySelect?.setSelectedObjects([historySizeOption])
historySelect.setSelectedObjects([historySizeOption])

setupObservers()
}
Expand Down
2 changes: 2 additions & 0 deletions Covid-19 Status/src/Preferences/PreferencesOptions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,6 @@ class PreferencesOptions {
}

static var defaultAlertsStatus = true

static var defaultFormatMethod = StatsFormatMethod.long
}
17 changes: 17 additions & 0 deletions Covid-19 Status/src/Preferences/UserDefaults.swift
Original file line number Diff line number Diff line change
Expand Up @@ -83,4 +83,21 @@ extension UserDefaults {
print("Setting alerts enabled status:", enabled)
set(enabled, forKey: SettingsKey.alertsEnabled.rawValue)
}

// format method

var formatMethod: StatsFormatMethod {
if exists(key: SettingsKey.formatMethod.rawValue) {
if let method = StatsFormatMethod(rawValue: string(forKey: SettingsKey.formatMethod.rawValue) ?? "long") {
return method
}
return PreferencesOptions.defaultFormatMethod
}
return PreferencesOptions.defaultFormatMethod
}

func saveFormatMethod(method: StatsFormatMethod) {
print("Setting format method:", method)
set(method.rawValue, forKey: SettingsKey.formatMethod.rawValue)
}
}
15 changes: 15 additions & 0 deletions Covid-19 Status/src/Service/Messenger.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ extension NSNotification.Name {
static let FetchIntervalChange = NSNotification.Name(rawValue: "FetchIntervalChange")
static let AlertsStatusChange = NSNotification.Name(rawValue: "AlertsStatusChange")
static let FetchRequest = NSNotification.Name(rawValue: "FetchRequest")
static let FormatMethodChange = NSNotification.Name(rawValue: "FormatMethodChange")
}

class Messenger: NSObject {
Expand Down Expand Up @@ -88,4 +89,18 @@ class Messenger: NSObject {
}
}
}

// format method

func dispatchFormatMethod(method: StatsFormatMethod) {
notifier.post(name: .FormatMethodChange, object: self, userInfo: ["method": method])
}

func onFormatMethodChange(listener: @escaping (_ enabled: StatsFormatMethod) -> Void) -> NSObjectProtocol {
return notifier.addObserver(forName: .FormatMethodChange, object: nil, queue: nil) { notification in
if let method = notification.userInfo?["method"] as? StatsFormatMethod {
listener(method)
}
}
}
}
3 changes: 2 additions & 1 deletion Covid-19 Status/src/Statistics/Notificator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@ import Foundation
class Notificator {
var lastUpdates: [String: RegionStats] = [:]
var isEnabled = false
var settings = UserDefaults.standard

func showNotification(stats: RegionStats) {
let formatter = StatsFormatter(stats: stats)
let formatter = StatsFormatter(stats: stats, method: settings.formatMethod)

let notification = NSUserNotification()
notification.identifier = formatter.getUniqueId()
Expand Down
14 changes: 13 additions & 1 deletion Covid-19 Status/src/Statistics/StatsDisplay.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,26 @@ import Cocoa
class StatsDisplay: NSObject {
var statusDisplay: NSStatusBarButton?
var deltaDisplay: NSMenuItem?
var currentStats: RegionStats?

var settings = UserDefaults.standard

func setComponents(statusItem: NSStatusBarButton, deltaItem: NSMenuItem) {
statusDisplay = statusItem
deltaDisplay = deltaItem
}

func show(stats: RegionStats) {
let formatter = StatsFormatter(stats: stats)
currentStats = stats
renderStats()
}

func renderStats() {
guard let stats = currentStats else {
return
}

let formatter = StatsFormatter(stats: stats, method: settings.formatMethod)

DispatchQueue.main.async {
self.statusDisplay?.attributedTitle = formatter.getRegionStatus()
Expand Down
46 changes: 41 additions & 5 deletions Covid-19 Status/src/Statistics/StatsFormatter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,29 @@ func menuBarTextFormatter(label: String) -> NSMutableAttributedString {
return text
}

enum StatsFormatMethod: String {
case short
case long
}

class StatsFormatter {
var stats: RegionStats
var method: StatsFormatMethod

init(stats: RegionStats) {
init(stats: RegionStats, method: StatsFormatMethod) {
self.stats = stats
self.method = method
}

func formatStatistic(value: Int) -> String {
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = NumberFormatter.Style.decimal
numberFormatter.groupingSeparator = " "
return numberFormatter.string(from: NSNumber(value: value)) ?? "??"
if method == .long {
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = NumberFormatter.Style.decimal
numberFormatter.groupingSeparator = " "
return numberFormatter.string(from: NSNumber(value: value)) ?? "??"
} else {
return Double(value).shortStringRepresentation
}
}

func getUniqueId() -> String {
Expand Down Expand Up @@ -65,3 +76,28 @@ class StatsFormatter {
)
}
}

extension Double {
var shortStringRepresentation: String {
if self.isNaN {
return "NaN"
}
if self.isInfinite {
return "\(self < 0.0 ? "-" : "+")Infinity"
}

let units = ["", "k", "M", "B"]
var value = self
var unitIndex = 0

while unitIndex < units.count - 1 {
if abs(value) < 1000.0 {
break
}
unitIndex += 1
value /= 1000.0
}

return "\(String(format: "%0.*g", Int(log10(abs(value))) + 2, value))\(units[unitIndex])"
}
}

0 comments on commit 5cf17cb

Please sign in to comment.