-
Notifications
You must be signed in to change notification settings - Fork 11
/
CallGridViewController.swift
596 lines (479 loc) · 20.6 KB
/
CallGridViewController.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
//
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import UIKit
import WireDataModel
import WireSyncEngine
import avs
import DifferenceKit
import WireCommonComponents
protocol CallGridViewControllerDelegate: AnyObject {
func callGridViewController(_ viewController: CallGridViewController, perform action: CallGridAction)
}
final class CallGridViewController: SpinnerCapableViewController {
// MARK: - Statics
static let isCoveredKey = "isCovered"
static var maxItemsPerPage: Int {
switch CallingConfiguration.config.streamLimit {
case .limit(amount: let amount): return amount
case .noLimit: return 8
}
}
// MARK: - Private Properties
private var streams: [Stream] {
if let stream = configuration.streams.first(where: { isMaximized(stream: $0) }) {
return [stream]
}
return configuration.streams
}
private var pinchToZoomRule: PinchToZoomRule {
PinchToZoomRule(isOneToOneCall: configuration.callHasTwoParticipants)
}
private var visibleClientsSharingVideo: [AVSClient] = []
private var dataSource: [Stream] = []
private let gridView = GridView(maxItemsPerPage: maxItemsPerPage)
private let thumbnailViewController = PinnableThumbnailViewController()
private let networkConditionView = NetworkConditionIndicatorView()
private let pageIndicator = RoundedPageIndicator()
private let topStack = UIStackView(axis: .vertical)
private let mediaManager: AVSMediaManagerInterface
private var viewCache = [AVSClient: OrientableView]()
// MARK: - Public Properties
// These two views are public for testing purposes
var maximizedView: BaseCallParticipantView?
var hintView = CallGridHintNotificationLabel()
var configuration: CallGridViewControllerInput {
didSet {
guard !configuration.isEqual(to: oldValue) else { return }
dismissMaximizedViewIfNeeded(oldPresentationMode: oldValue.presentationMode)
updateState()
if
configuration.isGroupCall,
configuration.isConnected,
!oldValue.isConnected
{
updateHint(for: .connectionEstablished)
}
}
}
var previewOverlay: UIView? {
return thumbnailViewController.contentView
}
/// Update view visibility when this view controller is covered or not
var isCovered: Bool = false {
didSet {
guard isCovered != oldValue else { return }
notifyVisibilityChanged()
displayIndicatorViewsIfNeeded()
animateNetworkConditionView()
hintView.setMessageHidden(isCovered)
}
}
var dismissSpinner: SpinnerCompletion?
weak var delegate: CallGridViewControllerDelegate?
// MARK: - Initialization
init(configuration: CallGridViewControllerInput,
mediaManager: AVSMediaManagerInterface = AVSMediaManager.sharedInstance()) {
self.configuration = configuration
self.mediaManager = mediaManager
super.init(nibName: nil, bundle: nil)
setupViews()
createConstraints()
updateState()
displayIndicatorViewsIfNeeded()
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
updateHint(for: .viewDidLoad)
}
// MARK: - Setup
private func setupViews() {
gridView.dataSource = self
gridView.gridViewDelegate = self
view.addSubview(gridView)
addToSelf(thumbnailViewController)
view.addSubview(topStack)
topStack.alignment = .center
topStack.spacing = 10
topStack.addArrangedSubview(networkConditionView)
topStack.addArrangedSubview(hintView)
view.addSubview(pageIndicator)
pageIndicator.pageControl.addTarget(self, action: #selector(didChangePage), for: .valueChanged)
networkConditionView.accessibilityIdentifier = "network-conditions-indicator"
}
func releadGridData() {
gridView.reloadData()
}
private func createConstraints() {
[gridView, thumbnailViewController.view, topStack, hintView, networkConditionView, pageIndicator].forEach {
$0?.translatesAutoresizingMaskIntoConstraints = false
}
[ thumbnailViewController.view].forEach {
$0.fitIn(view: view)
}
NSLayoutConstraint.activate([
gridView.topAnchor.constraint(equalTo: view.safeTopAnchor),
gridView.bottomAnchor.constraint(equalTo: view.safeBottomAnchor),
gridView.leadingAnchor.constraint(equalTo: view.safeLeadingAnchor),
gridView.trailingAnchor.constraint(equalTo: view.safeTrailingAnchor)
])
let topStackTopDistance = 6.0
NSLayoutConstraint.activate([
topStack.centerXAnchor.constraint(equalTo: view.centerXAnchor),
topStack.topAnchor.constraint(equalTo: view.safeTopAnchor, constant: topStackTopDistance),
topStack.leadingAnchor.constraint(greaterThanOrEqualTo: view.leadingAnchor, constant: 20),
topStack.trailingAnchor.constraint(lessThanOrEqualTo: view.trailingAnchor, constant: -20),
pageIndicator.centerYAnchor.constraint(equalTo: view.centerYAnchor),
pageIndicator.heightAnchor.constraint(equalToConstant: CGFloat.pageIndicatorHeight),
pageIndicator.centerXAnchor.constraint(equalTo: view.safeTrailingAnchor, constant: -22)
])
pageIndicator.transform = pageIndicator.transform.rotated(by: .pi / 2)
}
@objc func didChangePage(sender: UIPageControl) {
let newCurrentPage = sender.currentPage
pageIndicator.currentPage = newCurrentPage
gridView.scrollToPage(page: newCurrentPage, animated: true)
}
// MARK: - Public Interface
public func handleDoubleTap(gesture: UIGestureRecognizer) {
let location = gesture.location(in: gridView)
toggleMaximized(view: streamView(at: location))
}
// MARK: - View maximization
private func toggleMaximized(view: BaseCallParticipantView?) {
guard let view = view else { return }
guard allowMaximizationToggling(for: view.stream) else { return }
let shouldMaximize = !isMaximized(stream: view.stream)
maximizedView = shouldMaximize ? view : nil
view.isMaximized = shouldMaximize
updateGrid(with: streams)
updateHint(for: .maximizationChanged(stream: view.stream, maximized: view.isMaximized))
}
private func allowMaximizationToggling(for stream: Stream) -> Bool {
let isStreamScreenSharingOneToOne = gridIsOneToOneWithFloatingTile && stream.isScreenSharing
let isStreamMinimizedAndNotSharingVideo = !isMaximized(stream: stream) && !stream.isSharingVideo
return !isStreamScreenSharingOneToOne && !(isStreamMinimizedAndNotSharingVideo && gridHasOnlyOneTile)
}
private func isMaximized(stream: Stream?) -> Bool {
guard
let streamId = stream?.streamId,
let maximizedStreamId = maximizedView?.stream.streamId
else { return false }
return streamId == maximizedStreamId
}
private func dismissMaximizedViewIfNeeded(oldPresentationMode: VideoGridPresentationMode) {
guard oldPresentationMode != configuration.presentationMode else { return }
maximizedView?.isMaximized = false
maximizedView = nil
}
// MARK: - Hint
func updateHint(for event: CallGridEvent) {
switch event {
case .viewDidLoad:
break
case .connectionEstablished:
hintView.show(hint: .fullscreen)
case .configurationChanged where configuration.callHasTwoParticipants:
guard
let stream = configuration.streams.first,
stream.isSharingVideo
else { return }
if stream.isScreenSharing {
hintView.show(hint: .zoom)
} else if isMaximized(stream: stream) {
hintView.show(hint: .goBackOrZoom)
}
case .maximizationChanged(stream: let stream, maximized: let maximized):
if maximized {
hintView.show(hint: stream.isSharingVideo ? .goBackOrZoom : .goBack)
} else {
hintView.hideAndStopTimer()
}
default: break
}
}
// MARK: - UI Update
private func displayIndicatorViewsIfNeeded() {
networkConditionView.networkQuality = configuration.networkQuality
networkConditionView.isHidden = shouldHideNetworkCondition
}
private var shouldHideNetworkCondition: Bool {
return isCovered || configuration.networkQuality.isNormal
}
private func notifyVisibilityChanged() {
NotificationCenter.default.post(
name: .videoGridVisibilityChanged,
object: nil,
userInfo: [CallGridViewController.isCoveredKey: isCovered]
)
}
private func animateNetworkConditionView() {
UIView.animate(
withDuration: 0.2,
delay: 0,
options: [.curveEaseInOut, .beginFromCurrentState],
animations: { self.networkConditionView.alpha = self.isCovered ? 0.0 : 1.0 }
)
}
// MARK: - Grid Update
private func updateState() {
displaySpinnerIfNeeded()
updateSelfCallParticipantView()
updateFloatingView(with: configuration.floatingStream)
updateGrid(with: streams)
displayIndicatorViewsIfNeeded()
updateGridViewAxis()
updateHint(for: .configurationChanged)
requestVideoStreamsIfNeeded(forPage: gridView.currentPage)
selfCallParticipantView?.avatarView.isHidden = !configuration.isConnected
}
private func displaySpinnerIfNeeded() {
let subViewStackWithSpinner = self.view.subviews.filter { $0 is LoadingSpinnerView }
guard
configuration.presentationMode == .activeSpeakers,
configuration.streams.isEmpty,
subViewStackWithSpinner.isEmpty
else {
dismissSpinner?()
return
}
showLoadingView(title: L10n.Localizable.Call.Grid.noActiveSpeakers)
}
private func updateSelfCallParticipantView() {
guard let selfStreamId = ZMUser.selfUser()?.selfStreamId else { return }
// No stream to show. Update the capture state.
guard let selfStream = stream(with: selfStreamId) else {
Log.calling.debug("updating capture state to \(configuration.videoState)")
selfCallParticipantView?.updateCaptureState(with: configuration.videoState)
return
}
if let view = selfCallParticipantView {
view.stream = selfStream
view.shouldShowActiveSpeakerFrame = configuration.shouldShowActiveSpeakerFrame
view.shouldShowBorderWhenVideoIsStopped = shouldShowBorderWhenVideoIsStopped
} else {
viewCache[selfStreamId] = SelfCallParticipantView(
stream: selfStream,
isCovered: isCovered,
shouldShowActiveSpeakerFrame: configuration.shouldShowActiveSpeakerFrame,
shouldShowBorderWhenVideoIsStopped: shouldShowBorderWhenVideoIsStopped,
pinchToZoomRule: pinchToZoomRule
)
}
}
private func updateFloatingView(with stream: Stream?) {
// No stream, remove floating video if there is any.
guard let stream = stream else {
Log.calling.debug("Removing self video from floating preview")
return thumbnailViewController.removeCurrentThumbnailContentView()
}
// We only support the self preview in the floating overlay.
guard stream.streamId == ZMUser.selfUser()?.selfStreamId else {
return Log.calling.error("Invalid operation: Non self preview in overlay")
}
// We have a stream but don't have a preview view yet.
if nil == thumbnailViewController.contentView, let previewView = selfCallParticipantView {
Log.calling.debug("Adding self video to floating preview")
thumbnailViewController.setThumbnailContentView(previewView, contentSize: .previewSize(for: traitCollection))
}
}
private func updateGrid(with newStreams: [Stream]) {
let changeSet = StagedChangeset(source: dataSource, target: newStreams)
UIView.performWithoutAnimation {
gridView.reload(using: changeSet) { dataSource = $0 }
}
pageIndicator.numberOfPages = gridView.numberOfPages
updateStates(with: dataSource)
pruneCache()
}
private func updateStates(with streams: [Stream]) {
streams.forEach {
let view = (cachedStreamView(for: $0) as? CallParticipantView)
view?.stream = $0
view?.shouldShowActiveSpeakerFrame = configuration.shouldShowActiveSpeakerFrame
view?.isPaused = $0.isPaused
view?.pinchToZoomRule = pinchToZoomRule
view?.shouldShowBorderWhenVideoIsStopped = shouldShowBorderWhenVideoIsStopped
view?.accessibilityHint = configuration.callHasTwoParticipants ? "" : view?.accessibilityHint
view?.accessibilityTraits = configuration.callHasTwoParticipants ? .staticText : .button
}
}
private func pruneCache() {
let existingStreamsIds = Set(viewCache.keys)
let currentStreamsIds = configuration.allStreamIds
for deletedStreamId in existingStreamsIds.subtracting(currentStreamsIds) {
guard deletedStreamId != ZMUser.selfUser()?.selfStreamId else { return }
viewCache[deletedStreamId]?.removeFromSuperview()
viewCache.removeValue(forKey: deletedStreamId)
}
}
func requestVideoStreamsIfNeeded(forPage page: Int) {
let startIndex = page * gridView.maxItemsPerPage
var endIndex = startIndex + gridView.maxItemsPerPage
endIndex = min(endIndex, dataSource.count)
guard dataSource.indices.contains(startIndex),
endIndex > startIndex
else { return }
let clients = dataSource[startIndex..<endIndex]
.filter(\.isSharingVideo)
.map(\.streamId)
guard Set(clients) != Set(visibleClientsSharingVideo) else { return }
delegate?.callGridViewController(self, perform: .requestVideoStreamsForClients(clients))
visibleClientsSharingVideo = clients
}
// MARK: - Grid View Axis
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
guard traitCollection.didSizeClassChange(from: previousTraitCollection) else { return }
thumbnailViewController.updateThumbnailContentSize(.previewSize(for: traitCollection), animated: false)
updateGridViewAxis()
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: { [updateGridViewAxis] _ in updateGridViewAxis() })
}
private func updateGridViewAxis() {
let newAxis = gridAxis(for: traitCollection)
guard newAxis != gridView.layoutDirection else { return }
gridView.layoutDirection = newAxis
}
private func gridAxis(for traitCollection: UITraitCollection) -> UICollectionView.ScrollDirection {
let isLandscape = UIWindow.interfaceOrientation?.isLandscape
switch (traitCollection.userInterfaceIdiom, traitCollection.horizontalSizeClass, isLandscape) {
case (.pad, .regular, true), (.phone, _, true):
return .horizontal
default:
return .vertical
}
}
// MARK: - Helpers
private var shouldShowBorderWhenVideoIsStopped: Bool {
!gridHasOnlyOneTile && !gridIsOneToOneWithFloatingTile
}
private var gridHasOnlyOneTile: Bool {
configuration.streams.count == 1
}
private var gridIsOneToOneWithFloatingTile: Bool {
gridHasOnlyOneTile && configuration.floatingStream != nil
}
private func cachedStreamView(for stream: Stream) -> OrientableView? {
return viewCache[stream.streamId]
}
private func streamView(at location: CGPoint) -> BaseCallParticipantView? {
guard let indexPath = gridView.indexPathForItem(at: location) else {
return nil
}
return cachedStreamView(for: dataSource[indexPath.row]) as? BaseCallParticipantView
}
private func stream(with streamId: AVSClient) -> Stream? {
var stream = configuration.streams.first(where: { $0.streamId == streamId })
if stream == nil && configuration.floatingStream?.streamId == streamId {
stream = configuration.floatingStream
}
return stream
}
private var selfCallParticipantView: SelfCallParticipantView? {
guard let selfStreamId = ZMUser.selfUser()?.selfStreamId else {
return nil
}
return viewCache[selfStreamId] as? SelfCallParticipantView
}
}
// MARK: - UICollectionViewDataSource
extension CallGridViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataSource.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: GridCell.reuseIdentifier, for: indexPath) as? GridCell else {
return UICollectionViewCell()
}
let stream = dataSource[indexPath.row]
cell.add(streamView: streamView(for: stream))
return cell
}
private func streamView(for stream: Stream) -> OrientableView {
let streamId = stream.streamId
if let streamView = cachedStreamView(for: stream) {
return streamView
} else {
let view = CallParticipantView(
stream: stream,
isCovered: isCovered,
shouldShowActiveSpeakerFrame: configuration.shouldShowActiveSpeakerFrame,
shouldShowBorderWhenVideoIsStopped: shouldShowBorderWhenVideoIsStopped,
pinchToZoomRule: pinchToZoomRule
)
viewCache[streamId] = view
return view
}
}
}
// MARK: - GridViewDelegate
extension CallGridViewController: GridViewDelegate {
func gridView(_ gridView: GridView, didChangePageTo page: Int) {
pageIndicator.currentPage = page
requestVideoStreamsIfNeeded(forPage: page)
}
}
// MARK: - Test Helpers
extension CallGridViewController {
/// used by snapshot tests
func hideHintView() {
hintView.hideAndStopTimer()
}
}
// MARK: - Extensions
extension ZMEditableUser {
var selfStreamId: AVSClient {
guard
let selfUser = ZMUser.selfUser(),
let clientId = selfUser.selfClient()?.remoteIdentifier
else {
fatal("Could not create self user stream which should always exist")
}
return AVSClient(userId: selfUser.avsIdentifier, clientId: clientId)
}
}
extension CGSize {
static let floatingPreviewSmall = CGSize(width: 108, height: 144)
static let floatingPreviewLarge = CGSize(width: 150, height: 200)
static func previewSize(for traitCollection: UITraitCollection) -> CGSize {
switch traitCollection.horizontalSizeClass {
case .regular:
return .floatingPreviewLarge
case .compact, .unspecified:
return .floatingPreviewSmall
@unknown default:
return .floatingPreviewSmall
}
}
}
extension Notification.Name {
static let videoGridVisibilityChanged = Notification.Name(rawValue: "VideoGridVisibilityChanged")
}
fileprivate extension CGFloat {
static let pageIndicatorHeight: CGFloat = 24
}