-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathGraphView.swift
1888 lines (1519 loc) · 64 KB
/
GraphView.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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// GraphView.swift
// Graph View
//
// Created by Vegard Solheim Theriault on 13/01/2017.
// Copyright © 2017 Vegard Solheim Theriault. All rights reserved.
//
// .___ ___. ______ ______ .__ __.
// | \/ | / __ \ / __ \ | \ | |
// | \ / | | | | | | | | | | \| |
// | |\/| | | | | | | | | | | . ` |
// | | | | | `--' | | `--' | | |\ |
// |__| |__| \______/ \______/ |__| \__|
// ___ _____ _____ _ ___ ___ ___ ___
// | \| __\ \ / / __| | / _ \| _ \ __| _ \
// | |) | _| \ V /| _|| |_| (_) | _/ _|| /
// |___/|___| \_/ |___|____\___/|_| |___|_|_\
//
import MetalKit
import Accelerate
import simd
#if os(iOS)
import UIKit
#elseif os(OSX)
import Cocoa
#endif
// -------------------------------
// MARK: Platform Specific Types
// -------------------------------
#if os(iOS)
public typealias View = UIView
public typealias Color = UIColor
fileprivate typealias Label = UILabel
fileprivate typealias Font = UIFont
fileprivate typealias BezierPath = UIBezierPath
fileprivate typealias Point = CGPoint
fileprivate typealias Rect = CGRect
#elseif os(OSX)
public typealias View = NSView
public typealias Color = NSColor
fileprivate typealias Label = NSTextField
fileprivate typealias Font = NSFont
fileprivate typealias BezierPath = NSBezierPath
fileprivate typealias Point = NSPoint
fileprivate typealias Rect = NSRect
#endif
// -------------------------------
// MARK: Constants
// -------------------------------
fileprivate struct Constants {
static let ValueLabelWidth : CGFloat = 60
static let TopBottomPadding : CGFloat = 16
static let CornerRadius : CGFloat = 10
}
// -------------------------------
// MARK: Data Structures
// -------------------------------
public extension GraphView {
public enum GraphType {
case scatter
/// Line currently only works when using the replace(with: ...)
/// function to set the data.
case line
}
public enum SampleSize {
case small
case large
case custom(size: UInt8)
fileprivate func size() -> UInt8 {
switch self {
case .small: return 2
case .large: return 6
case .custom(let size): return size
}
}
}
}
// -------------------------------
// MARK: Graph View
// -------------------------------
public class GraphView: View {
/// The background color of the graph view. This will be a gradient color,
/// unless `.clear` is selected.
public var backgroundTint = BackgroundTintColor.blue {
didSet {
#if os(iOS)
gradientBackground.gradient.colors = backgroundTint.colors().reversed()
#elseif os(OSX)
gradientBackground.gradient.colors = backgroundTint.colors()
#endif
}
}
/// The color of the samples plotted in the graph. This can either be
/// a `.plain` color, or a `.gradient` one.
public var sampleColor = SampleColor.color(plain: .white) {
didSet {
switch sampleColor {
case .color(let color):
metalGraph.uniforms.topColor = color.vector()
metalGraph.uniforms.bottomColor = color.vector()
case .gradient(let top, let bottom):
metalGraph.uniforms.topColor = top.vector()
metalGraph.uniforms.bottomColor = bottom.vector()
}
#if os(iOS)
metalGraph.setNeedsDisplay()
#elseif os(OSX)
metalGraph.setNeedsDisplay(bounds)
#endif
}
}
/// Whether or not the graph should have rounded corners.
public var roundedCorners = true {
didSet { gradientBackground.gradient.cornerRadius = roundedCorners ? Constants.CornerRadius : 0.0 }
}
/// The title string that appears in the top left of the view
public var title = "" {
didSet {
#if os(iOS)
titleLabel.text = title
#elseif os(OSX)
titleLabel.stringValue = title
#endif
}
}
/// The subtitle string that appears right under the title
public var subtitle = "" {
didSet {
#if os(iOS)
subtitleLabel.text = subtitle
#elseif os(OSX)
subtitleLabel.stringValue = subtitle
#endif
}
}
/// The unit of the samples added to the graph. This appears as a suffix
/// for the value labels on the right hand side.
public var valueUnit = "" {
didSet {
updateMinMaxLabels()
}
}
/// The number of desired decimals displayed for the values. The default is 0.
public var valueUnitDecimals = 0 {
didSet {
updateMinMaxLabels()
}
}
/// The number of samples that fit in the graph view. When more samples than this are
/// added, the oldest samples will slide off the left edge. The default value is 1000.
public var capacity: Int {
get { return Int(_capacity) }
set { _capacity = Float(newValue) }
}
/// How the graph should be plotted. The `.line` option currently does not work propertly
public var graphType = GraphType.scatter {
didSet {
metalGraph.graphType = graphType
#if os(iOS)
metalGraph.setNeedsDisplay()
#elseif os(OSX)
metalGraph.setNeedsDisplay(bounds)
#endif
}
}
/// This is only applicable when `graphType` is set to `.scatter`.
public var sampleSize = SampleSize.small {
didSet {
metalGraph.uniforms.pointSize = sampleSize.size()
#if os(iOS)
metalGraph.setNeedsDisplay()
#elseif os(OSX)
metalGraph.setNeedsDisplay(bounds)
#endif
}
}
/// This property is only available on iOS. It specifies if the user should
/// be able to change the capacity (by pinching horizontally), the minimum
/// and maximum value (by pinching vertically), and moving up and down the
/// y-axis (by swiping). When the user has started interacting, an "Auto-Scale"
/// button will appear. This button is removed again when the user taps it.
#if os(iOS)
public var gesturesEnabled = true {
didSet {
if gesturesEnabled {
addGestureRecognizers()
} else {
removeGestureRecognizers()
}
}
}
#endif
/// Gets or sets the range of values that can be visible within the graph view.
/// If `isAutoscaling` is set to true, this will change by itself. If you want
/// to set this variable yourself, you should probably set `isAutoscaling` to false.
public var visibleRange: ClosedRange<Float> {
get {
return ClosedRange<Float>(uncheckedBounds: (metalGraph.uniforms.minValue, metalGraph.uniforms.maxValue))
}
set {
guard newValue.upperBound > newValue.lowerBound else { return }
metalGraph.uniforms.maxValue = newValue.upperBound
metalGraph.uniforms.minValue = newValue.lowerBound
#if os(iOS)
metalGraph.setNeedsDisplay()
#elseif os(OSX)
metalGraph.setNeedsDisplay(bounds)
#endif
updateMinMaxLabels()
}
}
/// Whether or not the graph should be autoscaling. This will be false if the
/// user is currently using gestures
public var isAutoscaling = true {
didSet {
metalGraph.isAutoscaling = isAutoscaling
#if os(iOS)
if isAutoscaling {
removeAutoScaleButton()
} else {
addAutoScaleButton()
}
#endif
}
}
/// Horizontal lines will be drawn with the y-axis values corresponding
/// to the values in this array.
public var horizontalLines: [Float] = [] {
didSet { drawHorizontalLines() }
}
// -------------------------------
// MARK: Public Methods
// -------------------------------
/// Adds a new sample to the graph. If the number of samples added is the
/// same as the value of `capacity`, the oldest value will be pushed out to
/// the left side of the graph view.
public func add(sample: Float) {
metalGraph.add(sample: sample)
}
/// Replaces all the current samples in the graph. This will also modify
/// `capacity` to the numper of samples in this call. Calling this function
/// is much faster than manually calling `add(...)` for each individual sample.
public func replace(with samples: [Float]) {
guard samples.count > 0 else { return }
_capacity = Float(samples.count)
metalGraph.set(samples: samples)
}
/// Removes every sample from the graph.
public func clear() {
metalGraph.clear()
}
// -------------------------------
// MARK: Private Properties
// -------------------------------
#if os(iOS)
private var pinchRecognizer : UIPinchGestureRecognizer?
private var panRecognizer : UIPanGestureRecognizer?
private var doubleTapRecognizer : UITapGestureRecognizer?
private var previousPinchPosY : CGFloat?
#endif
// This is here so it can be set independently of the user facing capacity
// It's also a Float so that scaling will work properly
private var _capacity: Float = 1000 {
didSet {
// Clamping value to [2, Int32.max]
if _capacity < 2 { _capacity = 2 }
else if _capacity > Float(Int32.max) { _capacity = Float(Int32.max) }
metalGraph.changeCapacity(to: UInt32(_capacity))
}
}
private var updateMinMaxLabelsTimer: Timer!
// Subviews
private var gradientBackground : _GradientView!
private var accessoriesView : _AccessoriesView!
fileprivate var metalGraph : _MetalGraphView!
fileprivate var horizontalLineView : _HorizontalLinesView!
fileprivate var maximumValueLabel : Label!
fileprivate var midValueLabel : Label!
fileprivate var minimumValueLabel : Label!
fileprivate var titleLabel : Label!
fileprivate var subtitleLabel : Label!
#if os(iOS)
fileprivate var autoScaleButton : GraphButton?
#endif
// -------------------------------
// MARK: Initialization
// -------------------------------
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
private func setup() {
#if os(iOS)
isOpaque = false
backgroundColor = .clear
#elseif os(OSX)
wantsLayer = true
layer?.isOpaque = false
layer?.backgroundColor = Color.clear.cgColor
#endif
addBackgroundView()
addHorizontalLineView()
addMetalGraphView()
addAccessoriesView()
addValueLabels()
addTitleAndSubtitleLabels()
#if os(iOS)
if gesturesEnabled { addGestureRecognizers() }
#endif
updateMinMaxLabelsTimer = Timer.scheduledTimer(withTimeInterval: 0.25, repeats: true) { _ in
self.updateMinMaxLabels()
}
}
private func addBackgroundView() {
gradientBackground = _GradientView(frame: bounds)
#if os(iOS)
gradientBackground.gradient.colors = backgroundTint.colors().reversed()
#elseif os(OSX)
gradientBackground.gradient.colors = backgroundTint.colors()
#endif
gradientBackground.gradient.cornerRadius = roundedCorners ? Constants.CornerRadius : 0.0
addSubview(gradientBackground)
gradientBackground.translatesAutoresizingMaskIntoConstraints = false
gradientBackground.topAnchor .constraint(equalTo: topAnchor) .isActive = true
gradientBackground.bottomAnchor .constraint(equalTo: bottomAnchor).isActive = true
gradientBackground.trailingAnchor.constraint(equalTo: trailingAnchor) .isActive = true
gradientBackground.leadingAnchor .constraint(equalTo: leadingAnchor) .isActive = true
}
private func addHorizontalLineView() {
horizontalLineView = _HorizontalLinesView(frame: bounds)
addSubview(horizontalLineView)
horizontalLineView.translatesAutoresizingMaskIntoConstraints = false
horizontalLineView.topAnchor .constraint(equalTo: topAnchor, constant: Constants.TopBottomPadding).isActive = true
horizontalLineView.bottomAnchor .constraint(equalTo: bottomAnchor, constant: -Constants.TopBottomPadding).isActive = true
horizontalLineView.leadingAnchor .constraint(equalTo: leadingAnchor, constant: 0) .isActive = true
horizontalLineView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -Constants.ValueLabelWidth) .isActive = true
}
private func addMetalGraphView() {
let uniforms = _MetalGraphView.Uniforms(
offset : 0,
capacity : UInt32(capacity),
minValue : 0,
maxValue : 1,
pointSize : sampleSize.size(),
topColor : vector_float4(1, 1, 1, 1),
bottomColor : vector_float4(1, 1, 1, 1)
)
metalGraph = _MetalGraphView(frame: bounds, uniforms: uniforms)
switch sampleColor {
case .color(let color):
metalGraph.uniforms.topColor = color.vector()
metalGraph.uniforms.bottomColor = color.vector()
case .gradient(let top, let bottom):
metalGraph.uniforms.topColor = top .vector()
metalGraph.uniforms.bottomColor = bottom.vector()
}
addSubview(metalGraph)
metalGraph.translatesAutoresizingMaskIntoConstraints = false
metalGraph.topAnchor .constraint(equalTo: topAnchor, constant: Constants.TopBottomPadding).isActive = true
metalGraph.bottomAnchor .constraint(equalTo: bottomAnchor, constant: -Constants.TopBottomPadding).isActive = true
metalGraph.leadingAnchor .constraint(equalTo: leadingAnchor, constant: 0) .isActive = true
metalGraph.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -Constants.ValueLabelWidth) .isActive = true
}
private func addAccessoriesView() {
accessoriesView = _AccessoriesView(frame: bounds)
addSubview(accessoriesView)
accessoriesView.translatesAutoresizingMaskIntoConstraints = false
accessoriesView.topAnchor .constraint(equalTo: topAnchor) .isActive = true
accessoriesView.bottomAnchor .constraint(equalTo: bottomAnchor) .isActive = true
accessoriesView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
accessoriesView.widthAnchor .constraint(equalToConstant: Constants.ValueLabelWidth).isActive = true
}
private func addValueLabels() {
let maxValue = metalGraph.uniforms.maxValue
let minValue = metalGraph.uniforms.minValue
let midValue = Int32((Double(maxValue - minValue)/2 + Double(minValue)).rounded())
#if os(iOS)
maximumValueLabel = Label()
midValueLabel = Label()
minimumValueLabel = Label()
maximumValueLabel.text = "\(maxValue)"
midValueLabel .text = "\(midValue)"
minimumValueLabel.text = "\(minValue)"
#elseif os(OSX)
maximumValueLabel = Label(labelWithString: "\(maxValue)")
midValueLabel = Label(labelWithString: "\(midValue)")
minimumValueLabel = Label(labelWithString: "\(minValue)")
#endif
addSubview(maximumValueLabel)
addSubview(midValueLabel)
addSubview(minimumValueLabel)
maximumValueLabel.translatesAutoresizingMaskIntoConstraints = false
midValueLabel .translatesAutoresizingMaskIntoConstraints = false
minimumValueLabel.translatesAutoresizingMaskIntoConstraints = false
maximumValueLabel.font = Font.systemFont(ofSize: 15)
midValueLabel .font = Font.systemFont(ofSize: 15)
minimumValueLabel.font = Font.systemFont(ofSize: 15)
maximumValueLabel.textColor = Color(white: 1, alpha: 0.7)
midValueLabel .textColor = Color(white: 1, alpha: 0.7)
minimumValueLabel.textColor = Color(white: 1, alpha: 0.7)
maximumValueLabel.leadingAnchor.constraint(equalTo: accessoriesView.leadingAnchor, constant: 20).isActive = true
midValueLabel .leadingAnchor.constraint(equalTo: accessoriesView.leadingAnchor, constant: 20).isActive = true
minimumValueLabel.leadingAnchor.constraint(equalTo: accessoriesView.leadingAnchor, constant: 20).isActive = true
maximumValueLabel.widthAnchor.constraint(equalToConstant: Constants.ValueLabelWidth).isActive = true
midValueLabel .widthAnchor.constraint(equalToConstant: Constants.ValueLabelWidth).isActive = true
minimumValueLabel.widthAnchor.constraint(equalToConstant: Constants.ValueLabelWidth).isActive = true
maximumValueLabel.topAnchor .constraint(equalTo: topAnchor, constant: Constants.TopBottomPadding - 10).isActive = true
minimumValueLabel.bottomAnchor .constraint(equalTo: bottomAnchor, constant: -7).isActive = true
midValueLabel .centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
}
private func addTitleAndSubtitleLabels() {
#if os(iOS)
titleLabel = Label()
subtitleLabel = Label()
titleLabel .text = title
subtitleLabel.text = subtitle
titleLabel .minimumScaleFactor = 0.1
subtitleLabel.minimumScaleFactor = 0.1
titleLabel .adjustsFontSizeToFitWidth = true
subtitleLabel.adjustsFontSizeToFitWidth = true
#elseif os(OSX)
titleLabel = Label(labelWithString: title)
subtitleLabel = Label(labelWithString: subtitle)
titleLabel .preferredMaxLayoutWidth = 1
subtitleLabel.preferredMaxLayoutWidth = 1
#endif
titleLabel .translatesAutoresizingMaskIntoConstraints = false
subtitleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel .font = Font.systemFont(ofSize: 30)
subtitleLabel.font = Font.systemFont(ofSize: 20)
titleLabel .textColor = Color(white: 1, alpha: 1)
subtitleLabel.textColor = Color(white: 1, alpha: 0.6)
addSubview(titleLabel)
addSubview(subtitleLabel)
titleLabel .leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20).isActive = true
subtitleLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20).isActive = true
titleLabel .topAnchor.constraint(equalTo: topAnchor, constant: 20).isActive = true
subtitleLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 5) .isActive = true
titleLabel .trailingAnchor.constraint(equalTo: metalGraph.trailingAnchor, constant: -20).isActive = true
subtitleLabel.trailingAnchor.constraint(equalTo: metalGraph.trailingAnchor, constant: -20).isActive = true
}
#if os(iOS)
private func addAutoScaleButton() {
guard autoScaleButton == nil else { return }
autoScaleButton = GraphButton(frame: CGRect(x: 0, y: 0, width: 1, height: 1))
autoScaleButton?.text = "Auto Scale"
autoScaleButton?.addTarget(self, action: #selector(autoScaleButtonTapped), for: .touchUpInside)
autoScaleButton?.translatesAutoresizingMaskIntoConstraints = false
autoScaleButton?.alpha = 0
addSubview(autoScaleButton!)
autoScaleButton?.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -(Constants.ValueLabelWidth + 16)).isActive = true
autoScaleButton?.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -16).isActive = true
autoScaleButton?.widthAnchor.constraint(equalToConstant: 110).isActive = true
autoScaleButton?.heightAnchor.constraint(equalToConstant: 30).isActive = true
UIView.animate(withDuration: 0.5) {
self.autoScaleButton?.alpha = 1
}
}
#endif
#if os(iOS)
private func removeAutoScaleButton() {
UIView.animate(
withDuration: 0.5,
delay: 0.1,
options: [],
animations: {
self.autoScaleButton?.alpha = 0
}, completion: { _ in
self.autoScaleButton?.removeFromSuperview()
self.autoScaleButton = nil
}
)
}
#endif
/// Calling this will draw a constant horizontal line across the entire graph
/// for each of the specified values. It will also override any previous
/// horizontal lines.
fileprivate func drawHorizontalLines() {
horizontalLineView.lines = horizontalLines.map {
($0 - visibleRange.lowerBound) / (visibleRange.upperBound - visibleRange.lowerBound)
}
}
// -------------------------------
// MARK: Gesture Recognizers
// -------------------------------
#if os(iOS)
private func addGestureRecognizers() {
pinchRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(pinchRecognizerDidPinch))
pinchRecognizer?.delegate = self
addGestureRecognizer(pinchRecognizer!)
panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(panRecognizerDidPan))
panRecognizer?.delegate = self
panRecognizer?.minimumNumberOfTouches = 1
panRecognizer?.maximumNumberOfTouches = 1
addGestureRecognizer(panRecognizer!)
doubleTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(doubleTapRecognizerDidRecognize))
doubleTapRecognizer?.numberOfTapsRequired = 2
doubleTapRecognizer?.numberOfTouchesRequired = 1
addGestureRecognizer(doubleTapRecognizer!)
}
#endif
#if os(iOS)
private func removeGestureRecognizers() {
if let pinch = pinchRecognizer {
removeGestureRecognizer(pinch)
}
if let pan = panRecognizer {
removeGestureRecognizer(pan)
}
if let doubleTap = doubleTapRecognizer {
removeGestureRecognizer(doubleTap)
}
}
#endif
#if os(iOS)
@objc private func pinchRecognizerDidPinch() {
guard let pinch = pinchRecognizer else { return }
switch pinch.state {
case .began:
isAutoscaling = false
fallthrough
case .changed:
guard pinch.numberOfTouches >= 2 else { return }
let a = pinch.location(ofTouch: 0, in: self)
let b = pinch.location(ofTouch: 1, in: self)
let dx = abs(a.x - b.x)
let dy = abs(a.y - b.y)
let midpointY = abs(a.y - b.y) / 2 + min(a.y, b.y)
// Calculate new capacity
let dxScale = (dx / (dx+dy)) * (1-pinch.scale) + 1
let dyScale = (dy / (dx+dy)) * (1-pinch.scale) + 1
let newCapacity = Float(CGFloat(_capacity) * dxScale)
if newCapacity >= 2 {
_capacity = newCapacity
}
// Calculate new visible range, based on pinch location
let oldMin = metalGraph.uniforms.minValue
let oldMax = metalGraph.uniforms.maxValue
let oldRange = visibleRange
let oldYSpread = oldRange.upperBound - oldRange.lowerBound
let newYSpread = oldYSpread * Float(dyScale)
let spreadChange = oldYSpread - newYSpread
let pinchLocationRatio = midpointY / bounds.height
let newMax = oldMax - Float(pinchLocationRatio) * spreadChange
let newMin = oldMin + Float(1-pinchLocationRatio) * spreadChange
visibleRange = newMin...newMax
// Do panning, works even when one finger is lifted
if let prevPos = previousPinchPosY {
translate(with: Float(midpointY - prevPos))
}
previousPinchPosY = midpointY
pinchRecognizer?.scale = 1.0
default:
// When released, cancelled, failed etc
previousPinchPosY = nil
}
}
#endif
#if os(iOS)
@objc private func doubleTapRecognizerDidRecognize() {
switch sampleSize {
case .custom: sampleSize = .small
case .large : sampleSize = .small
case .small : sampleSize = .large
}
}
#endif
#if os(iOS)
@objc private func panRecognizerDidPan() {
guard let pan = panRecognizer else { return }
switch pan.state {
case .began:
isAutoscaling = false
fallthrough
case .changed:
guard pan.numberOfTouches == 1 else { return }
translate(with: Float(pan.translation(in: self).y))
panRecognizer?.setTranslation(.zero, in: self)
default: break
}
}
#endif
private func translate(with translation: Float) {
let oldRange = visibleRange
let visibleHeight = bounds.height - Constants.TopBottomPadding * 2
let valuesPerPoint = abs(oldRange.upperBound - oldRange.lowerBound) / Float(visibleHeight)
let valuesToMove = translation * valuesPerPoint
let newMin = oldRange.lowerBound + valuesToMove
let newMax = oldRange.upperBound + valuesToMove
visibleRange = newMin...newMax
}
@objc private func autoScaleButtonTapped() {
isAutoscaling = true
}
}
#if os(iOS)
extension GraphView: UIGestureRecognizerDelegate {
public override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
// True unless we find a finger on the auto-scale button
if let autoScaleButton = autoScaleButton {
for i in 0..<gestureRecognizer.numberOfTouches {
let point = gestureRecognizer.location(ofTouch: i, in: self)
if autoScaleButton.frame.contains(point) {
return false
}
}
}
return true
}
}
#endif
extension GraphView {
@objc fileprivate func updateMinMaxLabels() {
drawHorizontalLines()
let minValue = metalGraph.uniforms.minValue
let maxValue = metalGraph.uniforms.maxValue
let midValue = (maxValue - minValue)/2 + minValue
let minValueText = String(format: "%.\(valueUnitDecimals)f", minValue) + " " + self.valueUnit
let midValueText = String(format: "%.\(valueUnitDecimals)f", midValue) + " " + self.valueUnit
let maxValueText = String(format: "%.\(valueUnitDecimals)f", maxValue) + " " + self.valueUnit
#if os(iOS)
self.minimumValueLabel.text = minValueText
self.midValueLabel .text = midValueText
self.maximumValueLabel.text = maxValueText
#elseif os(OSX)
self.minimumValueLabel.stringValue = minValueText
self.midValueLabel .stringValue = midValueText
self.maximumValueLabel.stringValue = maxValueText
#endif
}
}
// -------------------------------
// MARK: Colors
// -------------------------------
public extension GraphView {
public enum BackgroundTintColor: Int {
case gray = 0
case red
case green
case blue
case turquoise
case yellow
case purple
case clear
fileprivate func colors() -> [CGColor] {
switch self {
case .gray:
return [Color(red: 141.0/255.0, green: 140.0/255.0, blue: 146.0/255.0, alpha: 1.0).cgColor,
Color(red: 210.0/255.0, green: 209.0/255.0, blue: 215.0/255.0, alpha: 1.0).cgColor]
case .red:
return [Color(red: 253.0/255.0, green: 58.0/255.0, blue: 52.0/255.0, alpha: 1.0).cgColor,
Color(red: 255.0/255.0, green: 148.0/255.0, blue: 86.0/255.0, alpha: 1.0).cgColor]
case .green:
return [Color(red: 28.0/255.0, green: 180.0/255.0, blue: 28.0/255.0, alpha: 1.0).cgColor,
Color(red: 78.0/255.0, green: 238.0/255.0, blue: 92.0/255.0, alpha: 1.0).cgColor]
case .blue:
return [Color(red: 0.0/255.0, green: 108.0/255.0, blue: 250.0/255.0, alpha: 1.0).cgColor,
Color(red: 90.0/255.0, green: 202.0/255.0, blue: 251.0/255.0, alpha: 1.0).cgColor]
case .turquoise:
return [Color(red: 54.0/255.0, green: 174.0/255.0, blue: 220.0/255.0, alpha: 1.0).cgColor,
Color(red: 82.0/255.0, green: 234.0/255.0, blue: 208.0/255.0, alpha: 1.0).cgColor]
case .yellow:
return [Color(red: 255.0/255.0, green: 160.0/255.0, blue: 33.0/255.0, alpha: 1.0).cgColor,
Color(red: 254.0/255.0, green: 209.0/255.0, blue: 48.0/255.0, alpha: 1.0).cgColor]
case .purple:
return [Color(red: 140.0/255.0, green: 70.0/255.0, blue: 250.0/255.0, alpha: 1.0).cgColor,
Color(red: 217.0/255.0, green: 168.0/255.0, blue: 252.0/255.0, alpha: 1.0).cgColor]
case .clear:
return [Color.clear.cgColor]
}
}
public static var count: Int { return BackgroundTintColor.clear.rawValue + 1 }
}
public enum SampleColor {
case color(plain: Color)
case gradient(top: Color, bottom: Color)
}
}
// -------------------------------
// MARK: Gradient View
// -------------------------------
// This has to be a separate class to work properly with rotation animation
fileprivate class _GradientView: View {
var gradient: CAGradientLayer {
get { return layer as! CAGradientLayer }
}
#if os(iOS)
override class var layerClass: AnyClass {
get { return CAGradientLayer.self }
}
#elseif os(OSX)
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
setup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
private func setup() {
wantsLayer = true
layerContentsRedrawPolicy = .onSetNeedsDisplay
}
fileprivate override func makeBackingLayer() -> CALayer {
return CAGradientLayer()
}
#endif
}
// -------------------------------
// MARK: RenderCycle
// -------------------------------
fileprivate protocol RenderCycleObserver: class {
func renderCycle()
}
class RenderCycle {
private struct WeakRenderCycleObserver {
weak var value : RenderCycleObserver?
init (value: RenderCycleObserver) {
self.value = value
}
}
static let shared = RenderCycle()
private var observers = [WeakRenderCycleObserver]()
private var mutex = pthread_mutex_t()
#if os(iOS)
private var displayLink: CADisplayLink?
#elseif os(OSX)
private var displayLink: CVDisplayLink?
#endif
private init() {
pthread_mutex_init(&mutex, nil)
}
private func initializeDisplayLink() {
#if os(iOS)
displayLink = CADisplayLink(target: self, selector: #selector(renderCycle))
if #available(iOS 10, *) {
displayLink?.preferredFramesPerSecond = 30
} else {
displayLink?.frameInterval = 2
}
displayLink?.add(to: .main, forMode: .commonModes)
#elseif os(OSX)
var dl: CVDisplayLink?
CVDisplayLinkCreateWithActiveCGDisplays(&dl)
guard let displayLink = dl else { return }
self.displayLink = displayLink
CVDisplayLinkSetOutputCallback(displayLink, { _, _, _, _, _, context in
if let context = context {
let me = Unmanaged<RenderCycle>.fromOpaque(context).takeUnretainedValue()
me.renderCycle()
}
return kCVReturnSuccess
}, Unmanaged.passUnretained(self).toOpaque())
CVDisplayLinkStart(displayLink)
#endif
}
private func destroyDisplayLink() {
#if os(iOS)
displayLink?.invalidate()
displayLink = nil
#elseif os(OSX)
guard let displayLink = displayLink else { return }
CVDisplayLinkStop(displayLink)
self.displayLink = nil
#endif
}
@objc private func renderCycle() {
DispatchQueue.main.async {
pthread_mutex_lock(&self.mutex)
self.observers.forEach { $0.value?.renderCycle() }
pthread_mutex_unlock(&self.mutex)
}
}
fileprivate func add(cycleObserver: RenderCycleObserver) {
pthread_mutex_lock(&mutex)
observers.append(WeakRenderCycleObserver(value: cycleObserver))
if observers.count == 1 {
// Just added the first observer
initializeDisplayLink()
}
pthread_mutex_unlock(&mutex)
}
fileprivate func remove(cycleObserver: RenderCycleObserver) {
pthread_mutex_lock(&mutex)
if let idx = observers.index(where: { $0.value === cycleObserver }) {
observers.remove(at: idx)
}
if observers.count == 0 {
// Just removed the last observer
destroyDisplayLink()
}
pthread_mutex_unlock(&mutex)
}
}
// -------------------------------
// MARK: Metal Graph
// -------------------------------
fileprivate class _MetalGraphView: View, RenderCycleObserver {
struct Uniforms {
var offset : UInt32
var capacity : UInt32
var minValue : Float
var maxValue : Float
var pointSize : UInt8
var topColor : vector_float4
var bottomColor: vector_float4
// On macOS, the uniforms must be 256 byte aligned
#if os(OSX)
let pad0 = matrix_double4x4()
let pad1 = matrix_double2x3()
#endif
}