-
-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathConversationViewController+Delegates.swift
More file actions
431 lines (352 loc) · 15 KB
/
ConversationViewController+Delegates.swift
File metadata and controls
431 lines (352 loc) · 15 KB
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
//
// Copyright 2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
//
import AVFoundation
import Foundation
public import LibSignalClient
public import SignalServiceKit
public import SignalUI
extension ConversationViewController: AttachmentApprovalViewControllerDelegate {
public func attachmentApproval(
_ attachmentApproval: AttachmentApprovalViewController,
didApproveAttachments approvedAttachments: ApprovedAttachments,
messageBody: MessageBody?,
) {
ModalActivityIndicatorViewController.present(
fromViewController: attachmentApproval,
title: CommonStrings.preparingModal,
asyncBlock: { modal in
await self.sendAttachments(
approvedAttachments,
messageBody: messageBody,
from: attachmentApproval,
attachmentLimits: attachmentApproval.attachmentLimits,
)
modal.dismiss(completion: {
self.dismiss(animated: true)
})
},
)
}
public func attachmentApprovalDidCancel() {
dismiss(animated: true, completion: nil)
self.popKeyBoard()
}
public func attachmentApproval(
_ attachmentApproval: AttachmentApprovalViewController,
didChangeMessageBody newMessageBody: MessageBody?,
) {
AssertIsOnMainThread()
guard hasViewWillAppearEverBegun else {
owsFailDebug("InputToolbar not yet ready.")
return
}
guard let inputToolbar else {
return
}
inputToolbar.setMessageBody(newMessageBody, animated: false)
}
public func attachmentApproval(_ attachmentApproval: AttachmentApprovalViewController, didRemoveAttachment attachmentApprovalItem: AttachmentApprovalItem) { }
public func attachmentApprovalDidTapAddMore(_ attachmentApproval: AttachmentApprovalViewController) { }
public func attachmentApproval(_ attachmentApproval: AttachmentApprovalViewController, didChangeViewOnceState isViewOnce: Bool) { }
}
extension ConversationViewController: AttachmentApprovalViewControllerDataSource {
public var attachmentApprovalTextInputContextIdentifier: String? { textInputContextIdentifier }
public var attachmentApprovalRecipientNames: [String] {
let displayName = SSKEnvironment.shared.databaseStorageRef.read { tx in SSKEnvironment.shared.contactManagerRef.displayName(for: thread, transaction: tx) }
return [displayName]
}
public var attachmentApprovalSendButtonTintColor: UIColor? {
viewState.conversationStyle.bubbleChatColorOutgoing.asChatUIElementTintColor()
}
public func attachmentApprovalMentionableAcis(tx: DBReadTransaction) -> [Aci] {
supportsMentions ? thread.recipientAddresses(with: tx).compactMap(\.aci) : []
}
public func attachmentApprovalMentionCacheInvalidationKey() -> String {
return thread.uniqueId
}
}
extension ConversationViewController: UIAdaptivePresentationControllerDelegate {
public func presentationControllerDidDismiss(_ presentationController: UIPresentationController) {
switch presentationController.presentedViewController {
case is GifPickerNavigationViewController, is UIDocumentPickerViewController:
self.openAttachmentKeyboard()
case let navigationController as OWSNavigationController:
switch navigationController.viewControllers.first {
case is ContactPickerViewController, is LocationPicker:
self.openAttachmentKeyboard()
default:
break
}
default:
break
}
}
}
// MARK: -
extension ConversationViewController: ContactPickerDelegate {
public func contactPickerDidCancel(_: ContactPickerViewController) {
dismiss(animated: true, completion: nil)
self.openAttachmentKeyboard()
}
public func contactPicker(_ contactPicker: ContactPickerViewController, didSelect systemContact: SystemContact) {
AssertIsOnMainThread()
guard let cnContact = SSKEnvironment.shared.contactManagerRef.cnContact(withId: systemContact.cnContactId) else {
owsFailDebug("Could not load system contact.")
return
}
let contactShareDraft = SSKEnvironment.shared.databaseStorageRef.read { tx in
return ContactShareDraft.load(
cnContact: cnContact,
signalContact: systemContact,
contactManager: SSKEnvironment.shared.contactManagerRef,
phoneNumberUtil: SSKEnvironment.shared.phoneNumberUtilRef,
profileManager: SSKEnvironment.shared.profileManagerRef,
recipientManager: DependenciesBridge.shared.recipientManager,
tsAccountManager: DependenciesBridge.shared.tsAccountManager,
tx: tx,
)
}
let approveContactShare = ContactShareViewController(contactShareDraft: contactShareDraft)
approveContactShare.shareDelegate = self
guard let navigationController = contactPicker.navigationController else {
owsFailDebug("Missing contactsPicker.navigationController.")
return
}
navigationController.pushViewController(approveContactShare, animated: true)
}
public func contactPicker(_: ContactPickerViewController, didSelectMultiple systemContacts: [SystemContact]) {
owsFailDebug("Multiple selection not allowed.")
dismiss(animated: true, completion: nil)
}
public func contactPicker(_: ContactPickerViewController, shouldSelect systemContact: SystemContact) -> Bool {
// Any reason to preclude contacts?
return true
}
}
// MARK: -
extension ConversationViewController: ContactShareViewControllerDelegate {
public func contactShareViewController(
_ viewController: ContactShareViewController,
didApproveContactShare contactShare:
ContactShareDraft,
) {
dismiss(animated: true) {
self.send(contactShareDraft: contactShare)
}
}
public func contactShareViewControllerDidCancel(_ viewController: ContactShareViewController) {
dismiss(animated: true, completion: nil)
}
public func titleForContactShareViewController(_ viewController: ContactShareViewController) -> String? {
return nil
}
public func recipientsDescriptionForContactShareViewController(_ viewController: ContactShareViewController) -> String? {
return SSKEnvironment.shared.databaseStorageRef.read { transaction in
SSKEnvironment.shared.contactManagerRef.displayName(for: self.thread, transaction: transaction)
}
}
public func approvalModeForContactShareViewController(_ viewController: ContactShareViewController) -> ApprovalMode {
return .send
}
private func send(contactShareDraft: ContactShareDraft) {
let thread = self.thread
SSKEnvironment.shared.databaseStorageRef.asyncWrite { transaction in
let didAddToProfileWhitelist = ThreadUtil.addThreadToProfileWhitelistIfEmptyOrPendingRequest(
thread,
setDefaultTimerIfNecessary: true,
tx: transaction,
)
transaction.addSyncCompletion {
Task { @MainActor in
ThreadUtil.enqueueMessage(withContactShare: contactShareDraft, thread: thread)
self.messageWasSent()
if didAddToProfileWhitelist {
self.ensureBannerState()
}
}
}
}
}
}
// MARK: -
extension ConversationViewController: ConversationHeaderViewDelegate {
func didTapConversationHeaderView(_ conversationHeaderView: ConversationHeaderView) {
AssertIsOnMainThread()
showConversationSettings()
}
func didTapConversationHeaderViewAvatar(_ conversationHeaderView: ConversationHeaderView) {
AssertIsOnMainThread()
if conversationHeaderView.avatarView.configuration.hasStoriesToDisplay {
let vc = StoryPageViewController(
context: thread.storyContext,
spoilerState: spoilerState,
)
present(vc, animated: true)
} else {
showConversationSettings()
}
}
}
// MARK: -
extension ConversationViewController: ConversationInputTextViewDelegate {
public func didAttemptAttachmentPaste() {
let attachmentLimits = OutgoingAttachmentLimits.currentLimits()
// If trying to paste a sticker, forego anything async since
// the pasteboard will be cleared as soon as paste() exits.
if PasteboardAttachment.hasStickerAttachment() {
do {
self.didPasteAttachments(
[try PasteboardAttachment.loadPreviewableStickerAttachment()].compacted(),
attachmentLimits: attachmentLimits,
)
} catch {
self.showErrorAlert(attachmentError: error as? SignalAttachmentError)
}
return
}
ModalActivityIndicatorViewController.present(
fromViewController: self,
title: OWSLocalizedString(
"ATTACHMENT_PASTING",
comment: "Displayed in a full screen modal when app is processing media that was pasted into message compose field.",
),
asyncBlock: { modal in
do {
let attachments = try await PasteboardAttachment.loadPreviewableAttachments(attachmentLimits: attachmentLimits)
modal.dismiss {
// Note: attachment array might be nil at this point; that's fine.
self.didPasteAttachments(attachments, attachmentLimits: attachmentLimits)
}
} catch {
modal.dismiss {
self.showErrorAlert(attachmentError: error as? SignalAttachmentError)
}
}
},
)
}
func didPasteAttachments(
_ attachments: [PreviewableAttachment]?,
attachmentLimits: OutgoingAttachmentLimits,
) {
AssertIsOnMainThread()
guard let attachments, attachments.count > 0 else {
owsFailDebug("Missing attachments")
return
}
// If the thing we pasted is sticker-like, send it immediately
// and render it borderless.
if attachments.count == 1, let a = attachments.first, a.rawValue.isBorderless {
Task {
await self.sendAttachments(
ApprovedAttachments(nonViewOnceAttachments: [a], imageQuality: .standard),
messageBody: nil,
from: self,
attachmentLimits: attachmentLimits,
)
}
} else {
dismissKeyBoard()
showApprovalDialog(forAttachments: attachments, attachmentLimits: attachmentLimits)
}
}
public func inputTextViewSendMessagePressed() {
AssertIsOnMainThread()
sendButtonPressed()
}
public func textViewDidChange(_ textView: UITextView) {
AssertIsOnMainThread()
if textView.text.strippedOrNil != nil {
SSKEnvironment.shared.typingIndicatorsRef.didStartTypingOutgoingInput(inThread: thread)
}
}
}
// MARK: -
extension ConversationViewController: ConversationSearchControllerDelegate {
public func didDismissSearchController(_ searchController: UISearchController) {
AssertIsOnMainThread()
// This method is called not only when the user taps "cancel" in the searchController, but also
// called when the searchController was dismissed because we switched to another uiMode, like
// "selection". We only want to revert to "normal" in the former case - when the user tapped
// "cancel" in the search controller. Otherwise, if we're already in another mode, like
// "selection", we want to stay in that mode.
if uiMode == .search {
uiMode = .normal
}
}
public func conversationSearchController(
_ conversationSearchController: ConversationSearchController,
didUpdateSearchResults resultSet: ConversationScreenSearchResultSet?,
) {
AssertIsOnMainThread()
self.lastSearchedText = resultSet?.searchText
loadCoordinator.enqueueReload()
}
public func conversationSearchController(
_ conversationSearchController: ConversationSearchController,
didSelectMessageId messageId: String,
) {
AssertIsOnMainThread()
ensureInteractionLoadedThenScrollToInteraction(
messageId,
onScreenPercentage: 1,
alignment: .centerIfNotEntirelyOnScreen,
isAnimated: true,
)
}
}
// MARK: -
extension ConversationViewController: ConversationCollectionViewDelegate {
public func collectionViewWillChangeSize(from oldSize: CGSize, to newSize: CGSize) {
AssertIsOnMainThread()
// Do nothing.
}
public func collectionViewDidChangeSize(from oldSize: CGSize, to newSize: CGSize) {
AssertIsOnMainThread()
if oldSize.width != newSize.width {
resetForSizeOrOrientationChange()
}
updateScrollingContent()
}
public func collectionViewWillAnimate() {
AssertIsOnMainThread()
scrollingAnimationDidStart()
}
public func collectionViewShouldRecognizeSimultaneously(with otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return otherGestureRecognizer == collectionViewContextMenuGestureRecognizer
}
public func scrollingAnimationDidStart() {
AssertIsOnMainThread()
// scrollingAnimationStartDate blocks landing of loads, so we must ensure
// that it is always cleared in a timely way, even if the animation
// is cancelled. Wait no more than N seconds.
scrollingAnimationCompletionTimer?.invalidate()
scrollingAnimationCompletionTimer = .scheduledTimer(withTimeInterval: 5, repeats: false) { [weak self] _ in
self?.scrollingAnimationCompletionTimerDidFire()
}
}
private func scrollingAnimationCompletionTimerDidFire() {
AssertIsOnMainThread()
Logger.warn("Scrolling animation did not complete in a timely way.")
// scrollingAnimationCompletionTimer should already have been cleared,
// but we need to ensure that it is cleared in a timely way.
scrollingAnimationDidComplete()
}
}
// MARK: -
extension ConversationViewController {
func scrollingAnimationDidComplete() {
AssertIsOnMainThread()
scrollingAnimationCompletionTimer?.invalidate()
scrollingAnimationCompletionTimer = nil
autoLoadMoreIfNecessary()
performMessageHighlightAnimationIfNeeded()
focusVoiceoverElementAfterScroll()
}
func resetForSizeOrOrientationChange() {
AssertIsOnMainThread()
updateConversationStyle()
}
}