// // BaseStatusTableViewCell.swift // Tusker // // Created by Shadowfacts on 11/19/19. // Copyright © 2019 Shadowfacts. All rights reserved. // import UIKit import Pachyderm import Combine import AVKit protocol StatusTableViewCellDelegate: TuskerNavigationDelegate { func statusCellCollapsedStateChanged(_ cell: BaseStatusTableViewCell) } class BaseStatusTableViewCell: UITableViewCell { weak var delegate: StatusTableViewCellDelegate? { didSet { contentTextView.navigationDelegate = delegate } } var overrideMastodonController: MastodonController? var mastodonController: MastodonController! { overrideMastodonController ?? delegate?.apiController } @IBOutlet weak var avatarImageView: UIImageView! @IBOutlet weak var displayNameLabel: EmojiLabel! @IBOutlet weak var usernameLabel: UILabel! @IBOutlet weak var visibilityImageView: UIImageView! @IBOutlet weak var contentWarningLabel: EmojiLabel! @IBOutlet weak var collapseButton: UIButton! @IBOutlet weak var contentTextView: StatusContentTextView! @IBOutlet weak var cardView: StatusCardView! @IBOutlet weak var attachmentsView: AttachmentsContainerView! @IBOutlet weak var replyButton: UIButton! @IBOutlet weak var favoriteButton: UIButton! @IBOutlet weak var reblogButton: UIButton! @IBOutlet weak var moreButton: UIButton! private(set) var prevThreadLinkView: UIView? private(set) var nextThreadLinkView: UIView? var statusID: String! var accountID: String! var favorited = false { didSet { favoriteButton.tintColor = favorited ? UIColor(displayP3Red: 1, green: 0.8, blue: 0, alpha: 1) : tintColor } } var reblogged = false { didSet { reblogButton.tintColor = reblogged ? UIColor(displayP3Red: 1, green: 0.8, blue: 0, alpha: 1) : tintColor } } var statusState: StatusState! var collapsible = false { didSet { collapseButton.isHidden = !collapsible statusState?.collapsible = collapsible } } var collapsed = false { didSet { statusState?.collapsed = collapsed } } var showStatusAutomatically = false private var avatarRequest: ImageCache.Request? private var statusUpdater: Cancellable? private var accountUpdater: Cancellable? private var currentPictureInPictureVideoStatusID: String? private var isGrayscale = false override func awakeFromNib() { super.awakeFromNib() displayNameLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(accountPressed))) usernameLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(accountPressed))) avatarImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(accountPressed))) avatarImageView.layer.masksToBounds = true avatarImageView.addInteraction(UIDragInteraction(delegate: self)) attachmentsView.delegate = self collapseButton.layer.masksToBounds = true collapseButton.layer.cornerRadius = 5 accessibilityElements = [displayNameLabel!, contentWarningLabel!, collapseButton!, contentTextView!, attachmentsView!] attachmentsView.isAccessibilityElement = true moreButton.showsMenuAsPrimaryAction = true NotificationCenter.default.addObserver(self, selector: #selector(preferencesChanged), name: .preferencesChanged, object: nil) contentWarningLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(collapseButtonPressed))) } open func createObserversIfNecessary() { if statusUpdater == nil { statusUpdater = mastodonController.persistentContainer.statusSubject .filter { [unowned self] in $0 == self.statusID } .receive(on: DispatchQueue.main) .sink { [unowned self] in if let mastodonController = mastodonController, let status = mastodonController.persistentContainer.status(for: $0) { self.updateStatusState(status: status) } } } if accountUpdater == nil { accountUpdater = mastodonController.persistentContainer.accountSubject .filter { [unowned self] in $0 == self.accountID } .receive(on: DispatchQueue.main) .sink { [unowned self] in if let mastodonController = mastodonController, let account = mastodonController.persistentContainer.account(for: $0) { self.updateUI(account: account) } } } } final func updateUI(statusID: String, state: StatusState) { createObserversIfNecessary() guard let status = mastodonController.persistentContainer.status(for: statusID) else { fatalError("Missing cached status") } self.statusID = statusID doUpdateUI(status: status, state: state) } func doUpdateUI(status: StatusMO, state: StatusState) { self.statusState = state let account = status.account self.accountID = account.id updateUI(account: account) contentTextView.setTextFrom(status: status) updateGrayscaleableUI(account: account, status: status) updateUIForPreferences(account: account, status: status) cardView.card = status.card cardView.isHidden = status.card == nil cardView.navigationDelegate = navigationDelegate attachmentsView.updateUI(status: status) attachmentsView.isAccessibilityElement = status.attachments.count > 0 attachmentsView.accessibilityLabel = String(format: NSLocalizedString("%d attachments", comment: "status attachments count accessibility label"), status.attachments.count) updateStatusState(status: status) contentWarningLabel.text = status.spoilerText contentWarningLabel.isHidden = status.spoilerText.isEmpty if !contentWarningLabel.isHidden { contentWarningLabel.setEmojis(status.emojis, identifier: statusID) } let reblogDisabled: Bool switch mastodonController.instance?.instanceType { case nil: // todo: this handle a race condition in instance public timelines // a somewhat better solution would be waiting to load the timeline until after the instance is loaded reblogDisabled = true case .mastodon: reblogDisabled = status.visibility == .private || status.visibility == .direct case .pleroma: // Pleroma allows 'Boost to original audience' for your own private posts reblogDisabled = status.visibility == .direct || (status.visibility == .private && status.account.id != mastodonController.account.id) } reblogButton.isEnabled = !reblogDisabled && mastodonController.loggedIn favoriteButton.isEnabled = mastodonController.loggedIn replyButton.isEnabled = mastodonController.loggedIn updateStatusIconsForPreferences(status) if state.unknown { state.resolveFor(status: status, text: contentTextView.text) if state.collapsible! && showStatusAutomatically { state.collapsed = false } } collapsible = state.collapsible! setCollapsed(state.collapsed!, animated: false) } func updateStatusState(status: StatusMO) { favorited = status.favourited reblogged = status.reblogged if favorited { favoriteButton.accessibilityLabel = NSLocalizedString("Undo Favorite", comment: "undo favorite button accessibility label") } else { favoriteButton.accessibilityLabel = NSLocalizedString("Favorite", comment: "favorite button accessibility label") } if reblogged { reblogButton.accessibilityLabel = NSLocalizedString("Undo Reblog", comment: "undo reblog button accessibility label") } else { reblogButton.accessibilityLabel = NSLocalizedString("Reblog", comment: "reblog button accessibility label") } // keep menu in sync with changed states e.g. bookmarked, muted moreButton.menu = UIMenu(title: "", image: nil, identifier: nil, options: [], children: actionsForStatus(status, sourceView: moreButton)) } func updateUI(account: AccountMO) { usernameLabel.text = "@\(account.acct)" avatarImageView.image = nil } @objc private func preferencesChanged() { guard let mastodonController = mastodonController, let account = mastodonController.persistentContainer.account(for: accountID), let status = mastodonController.persistentContainer.status(for: statusID) else { return } updateUIForPreferences(account: account, status: status) } func updateUIForPreferences(account: AccountMO, status: StatusMO) { avatarImageView.layer.cornerRadius = Preferences.shared.avatarStyle.cornerRadius(for: avatarImageView) attachmentsView.contentHidden = Preferences.shared.blurAllMedia || status.sensitive updateStatusIconsForPreferences(status) if isGrayscale != Preferences.shared.grayscaleImages { updateGrayscaleableUI(account: account, status: status) } } func updateStatusIconsForPreferences(_ status: StatusMO) { visibilityImageView.isHidden = !Preferences.shared.alwaysShowStatusVisibilityIcon if Preferences.shared.alwaysShowStatusVisibilityIcon { visibilityImageView.image = UIImage(systemName: status.visibility.unfilledImageName) visibilityImageView.accessibilityLabel = String(format: NSLocalizedString("Visibility: %@", comment: "status visibility indicator accessibility label"), status.visibility.displayName) } let reblogButtonImage: UIImage if Preferences.shared.alwaysShowStatusVisibilityIcon || reblogButton.isEnabled { reblogButtonImage = UIImage(systemName: "repeat")! } else { reblogButtonImage = UIImage(systemName: status.visibility.imageName)! } reblogButton.setImage(reblogButtonImage, for: .normal) } func updateGrayscaleableUI(account: AccountMO, status: StatusMO) { isGrayscale = Preferences.shared.grayscaleImages let avatarURL = account.avatar let accountID = account.id avatarRequest = ImageCache.avatars.get(avatarURL) { [weak self] (_, image) in guard let self = self, let image = image, self.accountID == accountID, let transformedImage = ImageGrayscalifier.convertIfNecessary(url: avatarURL, image: image) else { return } DispatchQueue.main.async { self.avatarImageView.image = transformedImage } } if contentTextView.hasEmojis { contentTextView.setTextFrom(status: status) } displayNameLabel.updateForAccountDisplayName(account: account) } func setShowThreadLinks(prev: Bool, next: Bool) { if prev { if let prevThreadLinkView = prevThreadLinkView { prevThreadLinkView.isHidden = false } else { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = tintColor.withAlphaComponent(0.5) view.layer.cornerRadius = 2.5 view.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner] prevThreadLinkView = view addSubview(view) NSLayoutConstraint.activate([ view.widthAnchor.constraint(equalToConstant: 5), view.centerXAnchor.constraint(equalTo: avatarImageView.centerXAnchor), view.topAnchor.constraint(equalTo: topAnchor), view.bottomAnchor.constraint(equalTo: avatarImageView.topAnchor, constant: -2), ]) } } else { prevThreadLinkView?.isHidden = true } if next { if let nextThreadLinkView = nextThreadLinkView { nextThreadLinkView.isHidden = false } else { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = tintColor.withAlphaComponent(0.5) view.layer.cornerRadius = 2.5 view.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner] nextThreadLinkView = view addSubview(view) NSLayoutConstraint.activate([ view.widthAnchor.constraint(equalToConstant: 5), view.centerXAnchor.constraint(equalTo: avatarImageView.centerXAnchor), view.topAnchor.constraint(equalTo: avatarImageView.bottomAnchor, constant: 2), view.bottomAnchor.constraint(equalTo: bottomAnchor), ]) } } else { nextThreadLinkView?.isHidden = true } } override func prepareForReuse() { super.prepareForReuse() avatarRequest?.cancel() attachmentsView.attachmentViews.allObjects.forEach { $0.removeFromSuperview() } showStatusAutomatically = false } @IBAction func collapseButtonPressed() { setCollapsed(!collapsed, animated: true) delegate?.statusCellCollapsedStateChanged(self) } func setCollapsed(_ collapsed: Bool, animated: Bool) { self.collapsed = collapsed contentTextView.isHidden = collapsed cardView.isHidden = cardView.card == nil || collapsed attachmentsView.isHidden = attachmentsView.attachments.count == 0 || collapsed let buttonImage = UIImage(systemName: collapsed ? "chevron.down" : "chevron.up")! if animated, let buttonImageView = collapseButton.imageView { // we need to use a keyframe animation for this, because we want to control the direction the chevron rotates // when rotating ±π, UIKit will always rotate in the same direction // using a keyframe to set an intermediate point in the animation allows us to force a specific direction UIView.animateKeyframes(withDuration: 0.2, delay: 0, options: .calculationModeLinear, animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.5) { buttonImageView.transform = CGAffineTransform(rotationAngle: collapsed ? .pi / 2 : -.pi / 2) } UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.5) { buttonImageView.transform = CGAffineTransform(rotationAngle: .pi) } }, completion: { (finished) in buttonImageView.transform = .identity self.collapseButton.setImage(buttonImage, for: .normal) }) } else { collapseButton.setImage(buttonImage, for: .normal) } if collapsed { collapseButton.accessibilityLabel = NSLocalizedString("Expand Status", comment: "expand status button accessibility label") } else { collapseButton.accessibilityLabel = NSLocalizedString("Collapse Status", comment: "collapse status button accessibility label") } } @IBAction func replyPressed() { delegate?.compose(inReplyToID: statusID) } @IBAction func favoritePressed() { guard let status = mastodonController.persistentContainer.status(for: statusID) else { fatalError("Missing cached status \(statusID!)") } let oldValue = favorited favorited = !favorited let realStatus = status.reblog ?? status let request = (favorited ? Status.favourite : Status.unfavourite)(realStatus.id) mastodonController.run(request) { response in DispatchQueue.main.async { if case let .success(newStatus, _) = response { self.favorited = newStatus.favourited ?? false self.mastodonController.persistentContainer.addOrUpdate(status: newStatus, incrementReferenceCount: false) UIImpactFeedbackGenerator(style: .light).impactOccurred() } else { self.favorited = oldValue print("Couldn't favorite status \(realStatus.id)") // todo: display error message UINotificationFeedbackGenerator().notificationOccurred(.error) return } } } } @IBAction func reblogPressed() { guard let status = mastodonController.persistentContainer.status(for: statusID) else { fatalError("Missing cached status \(statusID!)") } let oldValue = reblogged reblogged = !reblogged let realStatus = status.reblog ?? status let request = (reblogged ? Status.reblog : Status.unreblog)(realStatus.id) mastodonController.run(request) { response in DispatchQueue.main.async { if case let .success(newStatus, _) = response { self.reblogged = newStatus.reblogged ?? false self.mastodonController.persistentContainer.addOrUpdate(status: newStatus, incrementReferenceCount: false) UIImpactFeedbackGenerator(style: .light).impactOccurred() } else { self.reblogged = oldValue print("Couldn't reblog status \(realStatus.id)") // todo: display error message UINotificationFeedbackGenerator().notificationOccurred(.error) } } } } @IBAction func morePressed() { delegate?.showMoreOptions(forStatus: statusID, sourceView: moreButton) } @objc func accountPressed() { delegate?.selected(account: accountID) } func getStatusCellPreviewProviders(for location: CGPoint, sourceViewController: UIViewController) -> PreviewProviders? { return nil } } extension BaseStatusTableViewCell: AttachmentViewDelegate { func attachmentViewGallery(startingAt index: Int) -> GalleryViewController? { guard let delegate = delegate, let status = mastodonController.persistentContainer.status(for: statusID) else { return nil } let sourceViews = status.attachments.map(attachmentsView.getAttachmentView(for:)) let gallery = delegate.gallery(attachments: status.attachments, sourceViews: sourceViews, startIndex: index) gallery.avPlayerViewControllerDelegate = self return gallery } func attachmentViewPresent(_ vc: UIViewController, animated: Bool) { delegate?.present(vc, animated: animated) } } // todo: This is not ideal. It works when the original cell remains visible and when the cell is reused, but if the cell is dealloc'd // resuming from PiP won't work because AVPlayerViewController.delegate is a weak reference. extension BaseStatusTableViewCell: AVPlayerViewControllerDelegate { func playerViewControllerWillStartPictureInPicture(_ playerViewController: AVPlayerViewController) { // We need to save the current statusID when PiP is initiated, because if the user restores from PiP after this cell has // been reused, the current value of statusID will not be correct. currentPictureInPictureVideoStatusID = statusID } func playerViewControllerDidStopPictureInPicture(_ playerViewController: AVPlayerViewController) { currentPictureInPictureVideoStatusID = nil } func playerViewControllerShouldAutomaticallyDismissAtPictureInPictureStart(_ playerViewController: AVPlayerViewController) -> Bool { // Ideally, when PiP is automatically initiated by app closing the gallery should not be dismissed // and when PiP is started because the user has tapped the button in the player controls the gallery // gallery should be dismissed. Unfortunately, this doesn't seem to be possible. Instead, the gallery is // always dismissed and is recreated when restoring the interface from PiP. return true } func playerViewController(_ playerViewController: AVPlayerViewController, restoreUserInterfaceForPictureInPictureStopWithCompletionHandler completionHandler: @escaping (Bool) -> Void) { guard let delegate = delegate, let playerViewController = playerViewController as? GalleryPlayerViewController, let id = currentPictureInPictureVideoStatusID, let status = mastodonController.persistentContainer.status(for: id), let index = status.attachments.firstIndex(where: { $0.id == playerViewController.attachment?.id }) else { // returning without invoking completionHandler will dismiss the PiP window return } // We create a new gallery view controller starting at the appropriate index and swap the // already-playing VC into the appropriate index so it smoothly continues playing. let sourceViews: [UIImageView?] if self.statusID == id { sourceViews = status.attachments.map(attachmentsView.getAttachmentView(for:)) } else { sourceViews = status.attachments.map { (_) in nil } } let gallery = delegate.gallery(attachments: status.attachments, sourceViews: sourceViews, startIndex: index) gallery.avPlayerViewControllerDelegate = self // ensure that all other page VCs are created gallery.loadViewIfNeeded() // replace the newly created player for the same attachment with the already-playing one gallery.pages[index] = playerViewController gallery.setViewControllers([playerViewController], direction: .forward, animated: false, completion: nil) // this isn't animated, otherwise the animation plays first and then the PiP window expands // which looks even weirder than the black background appearing instantly and then the PiP window animating delegate.present(gallery, animated: false) { completionHandler(false) } } } extension BaseStatusTableViewCell: MenuPreviewProvider { var navigationDelegate: TuskerNavigationDelegate? { return delegate } func getPreviewProviders(for location: CGPoint, sourceViewController: UIViewController) -> PreviewProviders? { guard let mastodonController = mastodonController else { return nil } if avatarImageView.frame.contains(location) { return ( content: { ProfileViewController(accountID: self.accountID, mastodonController: mastodonController) }, actions: { self.actionsForProfile(accountID: self.accountID, sourceView: self.avatarImageView) } ) } return self.getStatusCellPreviewProviders(for: location, sourceViewController: sourceViewController) } } extension BaseStatusTableViewCell: UIDragInteractionDelegate { func dragInteraction(_ interaction: UIDragInteraction, itemsForBeginning session: UIDragSession) -> [UIDragItem] { guard let currentAccountID = mastodonController.accountInfo?.id, let account = mastodonController.persistentContainer.account(for: accountID) else { return [] } let provider = NSItemProvider(object: account.url as NSURL) let activity = UserActivityManager.showProfileActivity(id: accountID, accountID: currentAccountID) provider.registerObject(activity, visibility: .all) return [UIDragItem(itemProvider: provider)] } }