-
-
Notifications
You must be signed in to change notification settings - Fork 954
/
Copy pathextensions.swift
566 lines (481 loc) · 19.1 KB
/
extensions.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
//
// extensions.swift
// Kit
//
// Created by Serhiy Mytrovtsiy on 10/04/2020.
// Using Swift 5.0.
// Running on macOS 10.15.
//
// Copyright © 2020 Serhiy Mytrovtsiy. All rights reserved.
//
import Cocoa
extension String: @retroactive LocalizedError {
public var errorDescription: String? { return self }
public var digits: String {
return components(separatedBy: CharacterSet.decimalDigits.inverted).joined()
}
public func widthOfString(usingFont font: NSFont) -> CGFloat {
let fontAttributes = [NSAttributedString.Key.font: font]
let size = self.size(withAttributes: fontAttributes)
return size.width
}
public func condenseWhitespace() -> String {
let components = self.components(separatedBy: .whitespacesAndNewlines)
return components.filter { !$0.isEmpty }.joined(separator: " ")
}
public func findAndCrop(pattern: String) -> (cropped: String, remain: String) {
do {
let regex = try NSRegularExpression(pattern: pattern)
let range = NSRange(self.startIndex..., in: self)
if let match = regex.firstMatch(in: self, options: [], range: range) {
if let range = Range(match.range, in: self) {
let cropped = String(self[range]).trimmingCharacters(in: .whitespaces)
let remaining = self.replacingOccurrences(of: cropped, with: "", options: .regularExpression).trimmingCharacters(in: .whitespaces)
return (cropped, remaining)
}
}
} catch {
print("Error creating regex: \(error.localizedDescription)")
}
return ("", self)
}
public func find(pattern: String) -> String {
do {
let regex = try NSRegularExpression(pattern: pattern)
let stringRange = NSRange(location: 0, length: self.utf16.count)
if let searchRange = regex.firstMatch(in: self, options: [], range: stringRange) {
let start = self.index(self.startIndex, offsetBy: searchRange.range.lowerBound)
let end = self.index(self.startIndex, offsetBy: searchRange.range.upperBound)
let value = String(self[start..<end]).trimmingCharacters(in: .whitespaces)
return value.trimmingCharacters(in: .whitespaces)
}
} catch {}
return ""
}
public var trimmed: String {
var buf = [UInt8]()
var trimming = true
for c in self.utf8 {
if trimming && c < 33 { continue }
trimming = false
buf.append(c)
}
while let last = buf.last, last < 33 {
buf.removeLast()
}
buf.append(0)
return String(cString: buf)
}
public func matches(_ regex: String) -> Bool {
return self.range(of: regex, options: .regularExpression, range: nil, locale: nil) != nil
}
public func removedRegexMatches(pattern: String, replaceWith: String = "") -> String {
do {
let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive)
let range = NSRange(location: 0, length: self.count)
return regex.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: replaceWith)
} catch {
return self
}
}
func removingWhitespaces() -> String {
return components(separatedBy: .whitespaces).joined()
}
}
public extension DispatchSource.MemoryPressureEvent {
func pressureColor() -> NSColor {
switch self {
case .normal:
return NSColor.systemGreen
case .warning:
return NSColor.systemYellow
case .critical:
return NSColor.systemRed
default:
return .controlAccentColor
}
}
}
public extension Double {
func roundTo(decimalPlaces: Int) -> String {
return NSString(format: "%.\(decimalPlaces)f" as NSString, self) as String
}
func rounded(toPlaces places: Int) -> Double {
let divisor = pow(10.0, Double(places))
return (self * divisor).rounded() / divisor
}
func usageColor(zones: colorZones = (0.6, 0.8), reversed: Bool = false) -> NSColor {
let firstColor: NSColor = NSColor.systemBlue
let secondColor: NSColor = NSColor.orange
let thirdColor: NSColor = NSColor.red
if reversed {
switch self {
case 0...zones.orange:
return thirdColor
case zones.orange...zones.red:
return secondColor
default:
return firstColor
}
} else {
switch self {
case 0...zones.orange:
return firstColor
case zones.orange...zones.red:
return secondColor
default:
return thirdColor
}
}
}
func batteryColor(color: Bool = false, lowPowerMode: Bool? = nil) -> NSColor {
if let mode = lowPowerMode, mode {
return NSColor.systemOrange
}
switch self {
case 0.2...0.4:
if !color {
return NSColor.textColor
}
return NSColor.systemOrange
case 0.4...1:
if self == 1 {
return NSColor.textColor
}
if !color {
return NSColor.textColor
}
return NSColor.systemGreen
default:
return NSColor.systemRed
}
}
func secondsToHoursMinutesSeconds() -> (Int, Int) {
let mins = (self.truncatingRemainder(dividingBy: 3600)) / 60
return (Int(self / 3600), Int(mins))
}
func printSecondsToHoursMinutesSeconds(short: Bool = false) -> String {
let (h, m) = self.secondsToHoursMinutesSeconds()
if self == 0 || h < 0 || m < 0 {
return "n/a"
}
let minutes = m > 9 ? "\(m)" : "0\(m)"
if short {
return "\(h):\(minutes)"
}
if h == 0 {
return "\(minutes)min"
} else if m == 0 {
return "\(h)h"
}
return "\(h)h \(minutes)min"
}
}
public extension NSView {
var isDarkMode: Bool {
switch effectiveAppearance.name {
case .darkAqua, .vibrantDark, .accessibilityHighContrastDarkAqua, .accessibilityHighContrastVibrantDark:
return true
default:
return false
}
}
func toggleSettingRow(title: String, action: Selector, state: Bool) -> NSView {
let view: NSStackView = NSStackView()
view.translatesAutoresizingMaskIntoConstraints = false
view.heightAnchor.constraint(equalToConstant: Constants.Settings.row).isActive = true
view.orientation = .horizontal
view.alignment = .centerY
view.distribution = .fill
view.spacing = 0
let titleField: NSTextField = LabelField(frame: NSRect(x: 0, y: 0, width: 0, height: 0), title)
titleField.font = NSFont.systemFont(ofSize: 12, weight: .regular)
titleField.textColor = .textColor
let state: NSControl.StateValue = state ? .on : .off
var toggle: NSControl = NSControl()
if #available(OSX 10.15, *) {
let switchButton = NSSwitch()
switchButton.state = state
switchButton.action = action
switchButton.target = self
toggle = switchButton
} else {
let button: NSButton = NSButton()
button.setButtonType(.switch)
button.state = state
button.title = ""
button.action = action
button.isBordered = false
button.isTransparent = false
button.target = self
button.wantsLayer = true
toggle = button
}
view.addArrangedSubview(titleField)
view.addArrangedSubview(NSView())
view.addArrangedSubview(toggle)
return view
}
func selectSettingsRow(title: String, action: Selector, items: [KeyValue_p], selected: String) -> NSView {
let view = NSStackView()
view.translatesAutoresizingMaskIntoConstraints = false
view.heightAnchor.constraint(equalToConstant: Constants.Settings.row).isActive = true
view.orientation = .horizontal
view.alignment = .centerY
view.distribution = .fill
view.spacing = 0
let titleField: NSTextField = LabelField(frame: NSRect(x: 0, y: 0, width: 0, height: 0), title)
titleField.font = NSFont.systemFont(ofSize: 12, weight: .regular)
titleField.textColor = .textColor
let select: NSPopUpButton = selectView(action: action, items: items, selected: selected)
select.sizeToFit()
view.addArrangedSubview(titleField)
view.addArrangedSubview(NSView())
view.addArrangedSubview(select)
return view
}
func selectView(action: Selector, items: [KeyValue_p], selected: String) -> NSPopUpButton {
let select: NSPopUpButton = NSPopUpButton(frame: NSRect(x: 0, y: 0, width: 50, height: 28))
select.target = self
select.action = action
let menu = NSMenu()
items.forEach { (item) in
if item.key.contains("separator") {
menu.addItem(NSMenuItem.separator())
} else {
let interfaceMenu = NSMenuItem(title: localizedString(item.value), action: nil, keyEquivalent: "")
interfaceMenu.representedObject = item.key
menu.addItem(interfaceMenu)
if selected == item.key {
interfaceMenu.state = .on
}
}
}
select.menu = menu
return select
}
func switchView(action: Selector, state: Bool) -> NSSwitch {
let s = NSSwitch()
s.heightAnchor.constraint(equalToConstant: 25).isActive = true
s.controlSize = .mini
s.state = state ? .on : .off
s.action = action
s.target = self
return s
}
func buttonIconView(_ action: Selector, icon: NSImage) -> NSButton {
let button = NSButton()
button.heightAnchor.constraint(equalToConstant: 22).isActive = true
button.bezelStyle = .regularSquare
button.translatesAutoresizingMaskIntoConstraints = false
button.imageScaling = .scaleNone
button.image = icon
button.contentTintColor = .labelColor
button.isBordered = false
button.action = action
button.target = self
button.focusRingType = .none
return button
}
func textView(_ value: String) -> NSTextField {
let field: NSTextField = TextView()
field.font = NSFont.systemFont(ofSize: 13, weight: .regular)
field.stringValue = value
field.isSelectable = true
return field
}
func sliderView(action: Selector, value: Int, initialValue: String, min: Double = 1, max: Double = 100, valueWidth: CGFloat = 40) -> NSView {
let view: NSStackView = NSStackView()
view.orientation = .horizontal
view.widthAnchor.constraint(equalToConstant: 195).isActive = true
let valueField: NSTextField = LabelField(initialValue)
valueField.font = NSFont.systemFont(ofSize: 12, weight: .regular)
valueField.textColor = .textColor
valueField.alignment = .center
valueField.widthAnchor.constraint(equalToConstant: valueWidth).isActive = true
let slider = NSSlider()
slider.controlSize = .small
slider.minValue = min
slider.maxValue = max
slider.intValue = Int32(value)
slider.target = self
slider.isContinuous = true
slider.action = action
slider.sizeToFit()
view.addArrangedSubview(slider)
view.addArrangedSubview(valueField)
return view
}
}
public class NSButtonWithPadding: NSButton {
public var horizontalPadding: CGFloat = 0
public var verticalPadding: CGFloat = 0
public override var intrinsicContentSize: NSSize {
var size = super.intrinsicContentSize
size.width += self.horizontalPadding
size.height += self.verticalPadding
return size
}
}
public class TextView: NSTextField {
public override init(frame: NSRect = .zero) {
super.init(frame: frame)
self.isEditable = false
self.isSelectable = false
self.isBezeled = false
self.wantsLayer = true
self.textColor = .labelColor
self.backgroundColor = .clear
self.canDrawSubviewsIntoLayer = true
self.alignment = .natural
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
public extension OperatingSystemVersion {
func getFullVersion(separator: String = ".") -> String {
return "\(majorVersion)\(separator)\(minorVersion)\(separator)\(patchVersion)"
}
}
extension URL {
func checkFileExist() -> Bool {
return FileManager.default.fileExists(atPath: self.path)
}
}
public extension NSColor {
func grayscaled() -> NSColor {
guard let space = CGColorSpace(name: CGColorSpace.extendedGray),
let cg = self.cgColor.converted(to: space, intent: .perceptual, options: nil),
let color = NSColor.init(cgColor: cg) else {
return self
}
return color
}
}
public class FlippedStackView: NSStackView {
public override var isFlipped: Bool { return true }
}
public class ScrollableStackView: NSView {
public var stackView: NSStackView = FlippedStackView()
private let clipView: NSClipView = NSClipView()
private let scrollView: NSScrollView = NSScrollView()
public var scrollWidth: CGFloat? {
self.scrollView.verticalScroller?.frame.size.width
}
public init(frame: NSRect = NSRect.zero, orientation: NSUserInterfaceLayoutOrientation = .vertical) {
super.init(frame: frame)
self.clipView.drawsBackground = false
self.stackView.orientation = orientation
self.stackView.translatesAutoresizingMaskIntoConstraints = false
self.scrollView.translatesAutoresizingMaskIntoConstraints = false
if orientation == .vertical {
self.scrollView.hasVerticalScroller = true
self.scrollView.hasHorizontalScroller = false
self.scrollView.autohidesScrollers = true
self.scrollView.horizontalScrollElasticity = .none
} else {
self.scrollView.hasVerticalScroller = false
self.scrollView.hasHorizontalScroller = true
self.scrollView.autohidesScrollers = true
self.scrollView.verticalScrollElasticity = .none
}
self.scrollView.drawsBackground = false
self.scrollView.contentView = self.clipView
self.scrollView.documentView = self.stackView
self.addSubview(self.scrollView)
NSLayoutConstraint.activate([
self.scrollView.leftAnchor.constraint(equalTo: self.leftAnchor),
self.scrollView.rightAnchor.constraint(equalTo: self.rightAnchor),
self.scrollView.topAnchor.constraint(equalTo: self.topAnchor),
self.scrollView.bottomAnchor.constraint(equalTo: self.bottomAnchor),
self.stackView.leftAnchor.constraint(equalTo: self.clipView.leftAnchor),
self.stackView.topAnchor.constraint(equalTo: self.clipView.topAnchor)
])
if orientation == .vertical {
self.stackView.rightAnchor.constraint(equalTo: self.clipView.rightAnchor).isActive = true
} else {
self.stackView.bottomAnchor.constraint(equalTo: self.clipView.bottomAnchor).isActive = true
}
}
required public init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// https://stackoverflow.com/a/54492165
extension NSTextView {
override open func performKeyEquivalent(with event: NSEvent) -> Bool {
let commandKey = NSEvent.ModifierFlags.command.rawValue
let commandShiftKey = NSEvent.ModifierFlags.command.rawValue | NSEvent.ModifierFlags.shift.rawValue
if event.type == NSEvent.EventType.keyDown {
if (event.modifierFlags.rawValue & NSEvent.ModifierFlags.deviceIndependentFlagsMask.rawValue) == commandKey {
switch event.charactersIgnoringModifiers! {
case "x":
if NSApp.sendAction(#selector(NSText.cut(_:)), to: nil, from: self) { return true }
case "c":
if NSApp.sendAction(#selector(NSText.copy(_:)), to: nil, from: self) { return true }
case "v":
if NSApp.sendAction(#selector(NSText.paste(_:)), to: nil, from: self) { return true }
case "z":
if NSApp.sendAction(Selector(("undo:")), to: nil, from: self) { return true }
case "a":
if NSApp.sendAction(#selector(NSResponder.selectAll(_:)), to: nil, from: self) { return true }
default:
break
}
} else if (event.modifierFlags.rawValue & NSEvent.ModifierFlags.deviceIndependentFlagsMask.rawValue) == commandShiftKey {
if event.charactersIgnoringModifiers == "Z" {
if NSApp.sendAction(Selector(("redo:")), to: nil, from: self) { return true }
}
}
}
return super.performKeyEquivalent(with: event)
}
}
public extension Data {
var socketAddress: sockaddr {
return withUnsafeBytes { $0.load(as: sockaddr.self) }
}
}
public extension Date {
func convertToTimeZone(_ timeZone: TimeZone) -> Date {
return addingTimeInterval(TimeInterval(timeZone.secondsFromGMT(for: self) - TimeZone.current.secondsFromGMT(for: self)))
}
func currentTimeSeconds() -> Int {
return Int(self.timeIntervalSince1970)
}
}
public extension TimeZone {
init(fromUTC: String) {
if fromUTC == "local" {
self = TimeZone.current
return
}
let arr = fromUTC.split(separator: ":")
guard !arr.isEmpty else {
self = TimeZone.current
return
}
var secondsFromGMT = 0
if arr.indices.contains(0), let h = Int(arr[0]) {
secondsFromGMT += h*3600
}
if arr.indices.contains(1), let m = Int(arr[1]) {
if secondsFromGMT < 0 {
secondsFromGMT -= m*60
} else {
secondsFromGMT += m*60
}
}
if let tz = TimeZone(secondsFromGMT: secondsFromGMT) {
self = tz
} else {
self = TimeZone.current
}
}
}
extension CGFloat {
func roundedUpToNearestTen() -> CGFloat {
return ceil(self / 10) * 10
}
}