Merge branch 'master' of gitlab.com:peter-iakovlev/telegram-ios

This commit is contained in:
Ali 2020-12-12 00:15:45 +04:00
commit 8c5c3fe633
28 changed files with 3024 additions and 3051 deletions

Binary file not shown.

Binary file not shown.

View File

@ -2687,6 +2687,7 @@ Unused sets are archived when you add more.";
"Channel.AdminLogFilter.EventsEditedMessages" = "Edited Messages";
"Channel.AdminLogFilter.EventsPinned" = "Pinned Messages";
"Channel.AdminLogFilter.EventsLeaving" = "Members Removed";
"Channel.AdminLogFilter.EventsCalls" = "Vocie Chats";
"Channel.AdminLogFilter.AdminsTitle" = "ADMINS";
"Channel.AdminLogFilter.AdminsAll" = "All Admins";

View File

@ -132,6 +132,7 @@ public protocol PresentationCall: class {
var peer: Peer? { get }
var state: Signal<PresentationCallState, NoError> { get }
var audioLevel: Signal<Float, NoError> { get }
var isMuted: Signal<Bool, NoError> { get }
@ -272,7 +273,7 @@ public protocol PresentationGroupCall: class {
var state: Signal<PresentationGroupCallState, NoError> { get }
var summaryState: Signal<PresentationGroupCallSummaryState?, NoError> { get }
var members: Signal<PresentationGroupCallMembers?, NoError> { get }
var audioLevels: Signal<[(PeerId, Float)], NoError> { get }
var audioLevels: Signal<[(PeerId, Float, Bool)], NoError> { get }
var myAudioLevel: Signal<Float, NoError> { get }
var isMuted: Signal<Bool, NoError> { get }
@ -285,7 +286,7 @@ public protocol PresentationGroupCall: class {
func updateMuteState(peerId: PeerId, isMuted: Bool)
func invitePeer(_ peerId: PeerId)
func invitePeer(_ peerId: PeerId) -> Bool
func removedPeer(_ peerId: PeerId)
var invitedPeers: Signal<[PeerId], NoError> { get }
}

View File

@ -565,10 +565,12 @@ class TabBarNode: ASDisplayNode {
if let callsTabBarNodeContainer = callsTabBarNodeContainer {
tabBarNodeContainers.remove(at: 1)
transition.updateAlpha(node: callsTabBarNodeContainer.imageNode, alpha: 0.0)
callsTabBarNodeContainer.imageNode.isUserInteractionEnabled = false
}
} else {
if let callsTabBarNodeContainer = callsTabBarNodeContainer {
transition.updateAlpha(node: callsTabBarNodeContainer.imageNode, alpha: 1.0)
callsTabBarNodeContainer.imageNode.isUserInteractionEnabled = true
}
}
@ -641,6 +643,9 @@ class TabBarNode: ASDisplayNode {
for i in 0 ..< self.tabBarNodeContainers.count {
let node = self.tabBarNodeContainers[i].imageNode
if !node.isUserInteractionEnabled {
continue
}
let distance = abs(location.x - node.position.x)
if let previousClosestNode = closestNode {
if previousClosestNode.1 > distance {

View File

@ -1010,9 +1010,9 @@ public func channelAdminController(context: AccountContext, peerId: PeerId, admi
if updateFlags == nil {
if member.adminInfo?.rights == nil {
if channel.flags.contains(.isCreator) {
updateFlags = maskRightsFlags.subtracting(.canAddAdmins)
updateFlags = maskRightsFlags.subtracting([.canAddAdmins, .canBeAnonymous])
} else if let adminRights = channel.adminRights {
updateFlags = maskRightsFlags.intersection(adminRights.flags).subtracting(.canAddAdmins)
updateFlags = maskRightsFlags.intersection(adminRights.flags).subtracting([.canAddAdmins, .canBeAnonymous])
} else {
updateFlags = []
}

View File

@ -1,9 +1,6 @@
import Foundation
import AsyncDisplayKit
import Display
import Postbox
import TelegramPresentationData
import GZip
private final class ShimmerEffectForegroundNode: ASDisplayNode {
private var currentBackgroundColor: UIColor?
@ -142,7 +139,7 @@ private func decodeStickerThumbnailData(_ data: Data) -> String {
return string
}
class StickerShimmerEffectNode: ASDisplayNode {
public class StickerShimmerEffectNode: ASDisplayNode {
private let backgroundNode: ASDisplayNode
private let effectNode: ShimmerEffectForegroundNode
private let foregroundNode: ASImageNode
@ -155,7 +152,7 @@ class StickerShimmerEffectNode: ASDisplayNode {
private var currentShimmeringColor: UIColor?
private var currentSize = CGSize()
override init() {
public override init() {
self.backgroundNode = ASDisplayNode()
self.effectNode = ShimmerEffectForegroundNode()
self.foregroundNode = ASImageNode()
@ -172,6 +169,9 @@ class StickerShimmerEffectNode: ASDisplayNode {
}
public func update(backgroundColor: UIColor?, foregroundColor: UIColor, shimmeringColor: UIColor, data: Data?, size: CGSize) {
if data == nil {
return
}
if self.currentData == data, let currentBackgroundColor = self.currentBackgroundColor, currentBackgroundColor.isEqual(backgroundColor), let currentForegroundColor = self.currentForegroundColor, currentForegroundColor.isEqual(foregroundColor), let currentShimmeringColor = self.currentShimmeringColor, currentShimmeringColor.isEqual(shimmeringColor), self.currentSize == size {
return
}

View File

@ -61,7 +61,7 @@ final class StickerPackPreviewGridItemNode: GridItemNode {
private var isEmpty: Bool?
private let imageNode: TransformImageNode
private var animationNode: AnimatedStickerNode?
private var placeholderNode: ShimmerEffectNode?
private var placeholderNode: StickerShimmerEffectNode?
private var theme: PresentationTheme?
@ -86,7 +86,8 @@ final class StickerPackPreviewGridItemNode: GridItemNode {
override init() {
self.imageNode = TransformImageNode()
self.imageNode.isLayerBacked = !smartInvertColorsEnabled()
self.placeholderNode = ShimmerEffectNode()
self.placeholderNode = StickerShimmerEffectNode()
self.placeholderNode?.isUserInteractionEnabled = false
super.init()
@ -117,9 +118,11 @@ final class StickerPackPreviewGridItemNode: GridItemNode {
if !animated {
placeholderNode.removeFromSupernode()
} else {
placeholderNode.allowsGroupOpacity = true
placeholderNode.alpha = 0.0
placeholderNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.2, completion: { [weak placeholderNode] _ in
placeholderNode?.removeFromSupernode()
placeholderNode?.allowsGroupOpacity = false
})
}
}
@ -181,9 +184,6 @@ final class StickerPackPreviewGridItemNode: GridItemNode {
self.setNeedsLayout()
}
self.isEmpty = isEmpty
//self.updateSelectionState(animated: false)
//self.updateHiddenMedia()
}
override func layout() {
@ -197,8 +197,8 @@ final class StickerPackPreviewGridItemNode: GridItemNode {
let placeholderFrame = CGRect(origin: CGPoint(x: floor((bounds.width - boundingSize.width) / 2.0), y: floor((bounds.height - boundingSize.height) / 2.0)), size: boundingSize)
placeholderNode.frame = bounds
if let theme = self.theme {
placeholderNode.update(backgroundColor: theme.list.itemBlocksBackgroundColor, foregroundColor: theme.list.mediaPlaceholderColor, shimmeringColor: theme.list.itemBlocksBackgroundColor.withAlphaComponent(0.4), shapes: [.roundedRect(rect: placeholderFrame, cornerRadius: 10.0)], size: bounds.size)
if let theme = self.theme, let (_, stickerItem) = self.currentState, let item = stickerItem {
placeholderNode.update(backgroundColor: theme.list.itemBlocksBackgroundColor, foregroundColor: theme.list.mediaPlaceholderColor, shimmeringColor: theme.list.itemBlocksBackgroundColor.withAlphaComponent(0.4), data: item.file.immediateThumbnailData, size: placeholderFrame.size)
}
}

View File

@ -230,9 +230,27 @@ public class CallStatusBarNodeImpl: CallStatusBarNode {
strongSelf.currentPeer = peer
strongSelf.currentCallState = state
strongSelf.currentIsMuted = isMuted
let currentIsConnected: Bool
switch state.state {
case .active, .terminating, .terminated:
currentIsConnected = true
default:
currentIsConnected = false
}
strongSelf.currentIsConnected = currentIsConnected
strongSelf.update()
}
}))
self.audioLevelDisposable.set((call.audioLevel
|> deliverOnMainQueue).start(next: { [weak self] audioLevel in
guard let strongSelf = self else {
return
}
strongSelf.backgroundNode.audioLevel = audioLevel
}))
case let .groupCall(sharedContext, account, call):
self.presentationData = sharedContext.currentPresentationData.with { $0 }
self.presentationDataDisposable.set((sharedContext.presentationData
@ -342,7 +360,15 @@ public class CallStatusBarNodeImpl: CallStatusBarNode {
}
}
self.backgroundNode.connectingColor = presentationData.theme.chatList.unreadBadgeInactiveBackgroundColor
let sourceColor = presentationData.theme.chatList.unreadBadgeInactiveBackgroundColor
let color: UIColor
if sourceColor.alpha < 1.0 {
color = presentationData.theme.chatList.unreadBadgeInactiveBackgroundColor.mixedWith(sourceColor.withAlphaComponent(1.0), alpha: sourceColor.alpha)
} else {
color = sourceColor
}
self.backgroundNode.connectingColor = color
}
if self.subtitleNode.segments != segments {

View File

@ -14,7 +14,7 @@ import DeviceAccess
import UniversalMediaPlayer
import AccountContext
private final class PresentationCallToneRenderer {
final class PresentationCallToneRenderer {
let queue: Queue
let tone: PresentationCallTone
@ -93,16 +93,27 @@ private final class PresentationCallToneRenderer {
var takenCount = 0
while takenCount < frameSize {
let dataOffset = (takeOffset + takenCount) % toneData.count
let dataCount = min(frameSize, toneData.count - dataOffset)
memcpy(bytes, dataBytes.advanced(by: dataOffset), dataCount)
let dataCount = min(frameSize - takenCount, toneData.count - dataOffset)
//print("take from \(dataOffset) count: \(dataCount)")
memcpy(bytes.advanced(by: takenCount), dataBytes.advanced(by: dataOffset), dataCount)
takenCount += dataCount
if let toneDataMaxOffset = toneDataMaxOffset, takeOffset + takenCount >= toneDataMaxOffset {
break
}
}
if takenCount < frameSize {
//print("fill with zeros from \(takenCount) count: \(frameSize - takenCount)")
memset(bytes.advanced(by: takenCount), 0, frameSize - takenCount)
}
}
if let toneDataMaxOffset = toneDataMaxOffset, takeOffset + frameSize > toneDataMaxOffset {
/*if let toneDataMaxOffset = toneDataMaxOffset, takeOffset + frameSize > toneDataMaxOffset {
let validCount = max(0, toneDataMaxOffset - takeOffset)
memset(bytes.advanced(by: validCount), 0, frameSize - validCount)
}
print("clear from \(validCount) count: \(frameSize - validCount)")
}*/
let status = CMBlockBufferCreateWithMemoryBlock(allocator: nil, memoryBlock: bytes, blockLength: frameSize, blockAllocator: nil, customBlockSource: nil, offsetToData: 0, dataLength: frameSize, flags: 0, blockBufferOut: &blockBuffer)
if status != noErr {
@ -189,6 +200,7 @@ public final class PresentationCallImpl: PresentationCall {
private var requestedVideoAspect: Float?
private var reception: Int32?
private var receptionDisposable: Disposable?
private var audioLevelDisposable: Disposable?
private var reportedIncomingCall = false
private var batteryLevelDisposable: Disposable?
@ -208,6 +220,11 @@ public final class PresentationCallImpl: PresentationCall {
return self.statePromise.get()
}
private let audioLevelPromise = ValuePromise<Float>(0.0)
public var audioLevel: Signal<Float, NoError> {
return self.audioLevelPromise.get()
}
private let isMutedPromise = ValuePromise<Bool>(false)
private var isMutedValue = false
public var isMuted: Signal<Bool, NoError> {
@ -425,6 +442,7 @@ public final class PresentationCallImpl: PresentationCall {
self.sessionStateDisposable?.dispose()
self.ongoingContextStateDisposable?.dispose()
self.receptionDisposable?.dispose()
self.audioLevelDisposable?.dispose()
self.batteryLevelDisposable?.dispose()
self.audioSessionDisposable?.dispose()
@ -645,6 +663,13 @@ public final class PresentationCallImpl: PresentationCall {
}
})
self.audioLevelDisposable = (ongoingContext.audioLevel
|> deliverOnMainQueue).start(next: { [weak self] level in
if let strongSelf = self {
strongSelf.audioLevelPromise.set(level)
}
})
func batteryLevelIsLowSignal() -> Signal<Bool, NoError> {
return Signal { subscriber in
let device = UIDevice.current

View File

@ -71,6 +71,8 @@ enum PresentationCallTone {
case busy
case failed
case ended
case groupJoined
case groupLeft
var loopCount: Int? {
switch self {
@ -80,6 +82,8 @@ enum PresentationCallTone {
return 1
case .ended:
return 1
case .groupJoined, .groupLeft:
return 1
default:
return nil
}
@ -98,5 +102,9 @@ func presentationCallToneData(_ tone: PresentationCallTone) -> Data? {
return loadToneData(name: "voip_fail.caf")
case .ended:
return loadToneData(name: "voip_end.caf")
case .groupJoined:
return loadToneData(name: "voip_group_joined.wav")
case .groupLeft:
return loadToneData(name: "voip_group_left.wav")
}
}

View File

@ -239,20 +239,20 @@ public final class PresentationGroupCallImpl: PresentationGroupCall {
}
}
private let audioLevelsPromise = Promise<[(PeerId, Float)]>()
private let audioLevelsPromise = Promise<[(PeerId, Float, Bool)]>()
init() {
}
func update(levels: [(PeerId, Float)]) {
func update(levels: [(PeerId, Float, Bool)]) {
let timestamp = Int32(CFAbsoluteTimeGetCurrent())
let currentParticipants: [PeerId: Participant] = self.participants
var validSpeakers: [PeerId: Participant] = [:]
var silentParticipants = Set<PeerId>()
var speakingParticipants = Set<PeerId>()
for (peerId, level) in levels {
if level > speakingLevelThreshold {
for (peerId, level, hasVoice) in levels {
if level > speakingLevelThreshold && hasVoice {
validSpeakers[peerId] = Participant(timestamp: timestamp, level: level)
speakingParticipants.insert(peerId)
} else {
@ -276,9 +276,11 @@ public final class PresentationGroupCallImpl: PresentationGroupCall {
}
}
var audioLevels: [(PeerId, Float)] = []
for (peerId, speaker) in validSpeakers {
audioLevels.append((peerId, speaker.level))
var audioLevels: [(PeerId, Float, Bool)] = []
for (peerId, level, hasVoice) in levels {
if level > 0.1 {
audioLevels.append((peerId, level, hasVoice))
}
}
self.participants = validSpeakers
@ -290,7 +292,7 @@ public final class PresentationGroupCallImpl: PresentationGroupCall {
return self.speakingParticipantsPromise.get() |> distinctUntilChanged
}
func getAudioLevels() -> Signal<[(PeerId, Float)], NoError> {
func getAudioLevels() -> Signal<[(PeerId, Float, Bool)], NoError> {
return self.audioLevelsPromise.get()
}
}
@ -310,6 +312,8 @@ public final class PresentationGroupCallImpl: PresentationGroupCall {
public let peerId: PeerId
public let peer: Peer?
private let temporaryJoinTimestamp: Int32
private var internalState: InternalState = .requesting
private var callContext: OngoingGroupCallContext?
@ -357,7 +361,7 @@ public final class PresentationGroupCallImpl: PresentationGroupCall {
private let speakingParticipantsContext = SpeakingParticipantsContext()
private var speakingParticipantsReportTimestamp: [PeerId: Double] = [:]
public var audioLevels: Signal<[(PeerId, Float)], NoError> {
public var audioLevels: Signal<[(PeerId, Float, Bool)], NoError> {
return self.speakingParticipantsContext.getAudioLevels()
}
@ -385,6 +389,8 @@ public final class PresentationGroupCallImpl: PresentationGroupCall {
return self._canBeRemoved.get()
}
private let wasRemoved = Promise<Bool>(false)
private var stateValue = PresentationGroupCallState.initialValue {
didSet {
if self.stateValue != oldValue {
@ -438,6 +444,9 @@ public final class PresentationGroupCallImpl: PresentationGroupCall {
private var removedChannelMembersDisposable: Disposable?
private var didConnectOnce: Bool = false
private var toneRenderer: PresentationCallToneRenderer?
init(
accountContext: AccountContext,
audioSession: ManagedAudioSession,
@ -459,6 +468,8 @@ public final class PresentationGroupCallImpl: PresentationGroupCall {
self.peerId = peerId
self.peer = peer
self.temporaryJoinTimestamp = Int32(CFAbsoluteTimeGetCurrent() + NSTimeIntervalSince1970)
var didReceiveAudioOutputs = false
if !audioSession.getIsHeadsetPluggedIn() {
@ -522,10 +533,15 @@ public final class PresentationGroupCallImpl: PresentationGroupCall {
return EmptyDisposable
})
} else {
audioSessionControl.activate({ _ in })
audioSessionActive = .single(true)
audioSessionControl.activate({ [weak self] _ in
Queue.mainQueue().async {
guard let strongSelf = self else {
return
}
strongSelf.audioSessionActive.set(.single(true))
}
})
}
strongSelf.audioSessionActive.set(audioSessionActive)
} else {
strongSelf.audioSessionActive.set(.single(false))
}
@ -562,7 +578,7 @@ public final class PresentationGroupCallImpl: PresentationGroupCall {
switch update {
case let .state(update):
for participantUpdate in update.participantUpdates {
if participantUpdate.isRemoved {
if case .left = participantUpdate.participationStatusChange {
removedSsrc.append(participantUpdate.ssrc)
if participantUpdate.peerId == strongSelf.accountContext.account.peerId {
@ -574,6 +590,7 @@ public final class PresentationGroupCallImpl: PresentationGroupCall {
if case let .estabilished(_, _, ssrc, _) = strongSelf.internalState, ssrc != participantUpdate.ssrc {
strongSelf._canBeRemoved.set(.single(true))
}
} else if case .joined = participantUpdate.participationStatusChange {
}
}
case let .call(isTerminated, _):
@ -611,10 +628,15 @@ public final class PresentationGroupCallImpl: PresentationGroupCall {
impl.get(account: accountContext.account, peerId: peerId, call: CachedChannelData.ActiveCall(id: initialCall.id, accessHash: initialCall.accessHash))
}) {
if let participantsContext = temporaryParticipantsContext.context.participantsContext {
let accountPeerId = self.accountContext.account.peerId
let accountPeer = self.accountContext.account.postbox.transaction { transaction -> Peer? in
return transaction.getPeer(accountPeerId)
}
self.participantsContextStateDisposable.set(combineLatest(queue: .mainQueue(),
accountPeer,
participantsContext.state,
participantsContext.activeSpeakers
).start(next: { [weak self] state, activeSpeakers in
).start(next: { [weak self] accountPeer, state, activeSpeakers in
guard let strongSelf = self else {
return
}
@ -631,7 +653,22 @@ public final class PresentationGroupCallImpl: PresentationGroupCall {
var updatedInvitedPeers = strongSelf.invitedPeersValue
var didUpdateInvitedPeers = false
for participant in state.participants {
var participants = state.participants
if !participants.contains(where: { $0.peer.id == accountPeerId }) {
if let accountPeer = accountPeer {
participants.append(GroupCallParticipantsContext.Participant(
peer: accountPeer,
ssrc: 0,
joinTimestamp: strongSelf.temporaryJoinTimestamp,
activityTimestamp: nil,
muteState: GroupCallParticipantsContext.Participant.MuteState(canUnmute: true)
))
participants.sort()
}
}
for participant in participants {
members.participants.append(participant)
if topParticipants.count < 3 {
@ -809,6 +846,14 @@ public final class PresentationGroupCallImpl: PresentationGroupCall {
strongSelf.checkCallDisposable = nil
}
}
if case .connected = state, !strongSelf.didConnectOnce {
strongSelf.didConnectOnce = true
let toneRenderer = PresentationCallToneRenderer(tone: .groupJoined)
strongSelf.toneRenderer = toneRenderer
toneRenderer.setAudioSessionActive(strongSelf.isAudioSessionActive)
}
}))
self.audioLevelsDisposable.set((callContext.audioLevels
@ -816,9 +861,10 @@ public final class PresentationGroupCallImpl: PresentationGroupCall {
guard let strongSelf = self else {
return
}
var result: [(PeerId, Float)] = []
var result: [(PeerId, Float, Bool)] = []
var myLevel: Float = 0.0
for (ssrcKey, level) in levels {
var myLevelHasVoice: Bool = false
for (ssrcKey, level, hasVoice) in levels {
var peerId: PeerId?
switch ssrcKey {
case .local:
@ -828,20 +874,20 @@ public final class PresentationGroupCallImpl: PresentationGroupCall {
}
if let peerId = peerId {
if case .local = ssrcKey {
myLevel = level
if !strongSelf.isMutedValue.isEffectivelyMuted {
myLevel = level
myLevelHasVoice = hasVoice
}
}
result.append((peerId, level))
result.append((peerId, level, hasVoice))
}
}
strongSelf.speakingParticipantsContext.update(levels: result)
let mappedLevel = myLevel * 1.5
strongSelf.myAudioLevelPipe.putNext(mappedLevel)
strongSelf.processMyAudioLevel(level: mappedLevel)
if !strongSelf.isMutedValue.isEffectivelyMuted {
strongSelf.speakingParticipantsContext.update(levels: [(strongSelf.account.peerId, mappedLevel)])
}
strongSelf.processMyAudioLevel(level: mappedLevel, hasVoice: myLevelHasVoice)
}))
}
}
@ -1047,9 +1093,24 @@ public final class PresentationGroupCallImpl: PresentationGroupCall {
private func updateIsAudioSessionActive(_ value: Bool) {
if self.isAudioSessionActive != value {
self.isAudioSessionActive = value
self.toneRenderer?.setAudioSessionActive(value)
}
}
private func markAsCanBeRemoved() {
self.callContext?.stop()
self.callContext = nil
self._canBeRemoved.set(.single(true))
let toneRenderer = PresentationCallToneRenderer(tone: .groupLeft)
self.toneRenderer = toneRenderer
toneRenderer.setAudioSessionActive(self.isAudioSessionActive)
Queue.mainQueue().after(0.5, {
self.wasRemoved.set(.single(true))
})
}
public func leave(terminateIfPossible: Bool) -> Signal<Bool, NoError> {
if case let .estabilished(callInfo, _, localSsrc, _) = self.internalState {
if terminateIfPossible {
@ -1058,9 +1119,7 @@ public final class PresentationGroupCallImpl: PresentationGroupCall {
guard let strongSelf = self else {
return
}
strongSelf.callContext?.stop()
strongSelf.callContext = nil
strongSelf._canBeRemoved.set(.single(true))
strongSelf.markAsCanBeRemoved()
}))
} else {
self.leaveDisposable.set((leaveGroupCall(account: self.account, callId: callInfo.id, accessHash: callInfo.accessHash, source: localSsrc)
@ -1068,23 +1127,16 @@ public final class PresentationGroupCallImpl: PresentationGroupCall {
guard let strongSelf = self else {
return
}
strongSelf.callContext?.stop()
strongSelf.callContext = nil
strongSelf._canBeRemoved.set(.single(true))
strongSelf.markAsCanBeRemoved()
}, completed: { [weak self] in
guard let strongSelf = self else {
return
}
strongSelf.callContext?.stop()
strongSelf.callContext = nil
strongSelf._canBeRemoved.set(.single(true))
strongSelf.markAsCanBeRemoved()
}))
}
} else {
self.callContext?.stop()
self.callContext = nil
self.requestDisposable.set(nil)
self._canBeRemoved.set(.single(true))
self.markAsCanBeRemoved()
}
return self._canBeRemoved.get()
}
@ -1273,9 +1325,9 @@ public final class PresentationGroupCallImpl: PresentationGroupCall {
}))
}
public func invitePeer(_ peerId: PeerId) {
public func invitePeer(_ peerId: PeerId) -> Bool {
guard case let .estabilished(callInfo, _, _, _) = self.internalState, !self.invitedPeersValue.contains(peerId) else {
return
return false
}
var updatedInvitedPeers = self.invitedPeersValue
@ -1283,6 +1335,8 @@ public final class PresentationGroupCallImpl: PresentationGroupCall {
self.invitedPeersValue = updatedInvitedPeers
let _ = inviteToGroupCall(account: self.account, callId: callInfo.id, accessHash: callInfo.accessHash, peerId: peerId).start()
return true
}
public func removedPeer(_ peerId: PeerId) {
@ -1329,10 +1383,10 @@ public final class PresentationGroupCallImpl: PresentationGroupCall {
myAudioLevelTimer.start()
}
private func processMyAudioLevel(level: Float) {
private func processMyAudioLevel(level: Float, hasVoice: Bool) {
self.currentMyAudioLevel = level
if level > 0.01 {
if level > 0.01 && hasVoice {
self.currentMyAudioLevelTimestamp = CACurrentMediaTime()
if self.myAudioLevelTimer == nil {

View File

@ -132,7 +132,7 @@ final class VoiceChatActionButton: HighlightTrackingButtonNode {
self.backgroundNode.audioLevel = level
}
func applyParams(animated: Bool) {
private func applyParams(animated: Bool) {
guard let (size, _, state, _, small, title, subtitle, snap) = self.currentParams else {
return
}
@ -209,6 +209,31 @@ final class VoiceChatActionButton: HighlightTrackingButtonNode {
self.wasActiveWhenPressed = false
}
private func applyIconParams() {
guard let (size, _, state, _, small, title, subtitle, snap) = self.currentParams else {
return
}
var iconMuted = true
var iconColor: UIColor = UIColor(rgb: 0xffffff)
switch state {
case let .active(state):
switch state {
case .on:
iconMuted = false
case .muted:
break
case .cantSpeak:
if !snap {
iconColor = UIColor(rgb: 0xff3b30)
}
}
case .connecting:
break
}
self.iconNode.update(state: VoiceChatMicrophoneNode.State(muted: iconMuted, color: iconColor), animated: true)
}
func update(snap: Bool, animated: Bool) {
if let previous = self.currentParams {
self.currentParams = (previous.size, previous.buttonSize, previous.state, previous.dark, previous.small, previous.title, previous.subtitle, snap)
@ -217,6 +242,7 @@ final class VoiceChatActionButton: HighlightTrackingButtonNode {
self.backgroundNode.glowHidden = snap
self.backgroundNode.updateColors()
self.applyParams(animated: animated)
self.applyIconParams()
}
}
@ -225,27 +251,24 @@ final class VoiceChatActionButton: HighlightTrackingButtonNode {
let previousState = previous?.state
self.currentParams = (size, buttonSize, state, dark, small, title, subtitle, previous?.snap ?? false)
var iconMuted = true
var iconColor: UIColor = .white
var backgroundState: VoiceChatActionButtonBackgroundNode.State
switch state {
case let .active(state):
switch state {
case .on:
iconMuted = false
backgroundState = .blob(true)
case .muted:
backgroundState = .blob(false)
case .cantSpeak:
iconColor = UIColor(rgb: 0xff3b30)
backgroundState = .disabled
}
case .connecting:
backgroundState = .connecting
}
self.applyIconParams()
self.backgroundNode.isDark = dark
self.backgroundNode.update(state: backgroundState, animated: true)
self.iconNode.update(state: VoiceChatMicrophoneNode.State(muted: iconMuted, color: iconColor), animated: true)
if case .active = state, let previousState = previousState, case .connecting = previousState, animated {
self.activeDisposable.set((self.activePromise.get()

View File

@ -172,9 +172,9 @@ public final class VoiceChatController: ViewController {
}
}
func updateAudioLevels(_ levels: [(PeerId, Float)], reset: Bool = false) {
func updateAudioLevels(_ levels: [(PeerId, Float, Bool)], reset: Bool = false) {
var updated = Set<PeerId>()
for (peerId, level) in levels {
for (peerId, level, _) in levels {
if let pipe = self.audioLevels[peerId] {
if reset {
pipe.putNext(level)
@ -579,10 +579,11 @@ public final class VoiceChatController: ViewController {
return
}
if let participant = participant {
strongSelf.call.invitePeer(participant.peer.id)
dismissController?()
strongSelf.controller?.present(UndoOverlayController(presentationData: strongSelf.presentationData, content: .invitedToVoiceChat(context: strongSelf.context, peer: participant.peer, text: strongSelf.presentationData.strings.VoiceChat_InvitedPeerText(peer.displayTitle(strings: strongSelf.presentationData.strings, displayOrder: strongSelf.presentationData.nameDisplayOrder)).0), elevatedLayout: false, action: { _ in return false }), in: .current)
if strongSelf.call.invitePeer(participant.peer.id) {
strongSelf.controller?.present(UndoOverlayController(presentationData: strongSelf.presentationData, content: .invitedToVoiceChat(context: strongSelf.context, peer: participant.peer, text: strongSelf.presentationData.strings.VoiceChat_InvitedPeerText(peer.displayTitle(strings: strongSelf.presentationData.strings, displayOrder: strongSelf.presentationData.nameDisplayOrder)).0), elevatedLayout: false, action: { _ in return false }), in: .current)
}
} else {
strongSelf.controller?.present(textAlertController(context: strongSelf.context, forceTheme: strongSelf.darkTheme, title: nil, text: strongSelf.presentationData.strings.VoiceChat_InviteMemberToGroupFirstText(peer.displayTitle(strings: strongSelf.presentationData.strings, displayOrder: strongSelf.presentationData.nameDisplayOrder), groupPeer.displayTitle(strings: strongSelf.presentationData.strings, displayOrder: strongSelf.presentationData.nameDisplayOrder)).0, actions: [TextAlertAction(type: .genericAction, title: presentationData.strings.Common_Cancel, action: {}), TextAlertAction(type: .defaultAction, title: presentationData.strings.VoiceChat_InviteMemberToGroupFirstAdd, action: {
guard let strongSelf = self else {
@ -650,10 +651,11 @@ public final class VoiceChatController: ViewController {
dismissController?()
return
}
strongSelf.call.invitePeer(peer.id)
dismissController?()
strongSelf.controller?.present(UndoOverlayController(presentationData: strongSelf.presentationData, content: .invitedToVoiceChat(context: strongSelf.context, peer: peer, text: strongSelf.presentationData.strings.VoiceChat_InvitedPeerText(peer.displayTitle(strings: strongSelf.presentationData.strings, displayOrder: strongSelf.presentationData.nameDisplayOrder)).0), elevatedLayout: false, action: { _ in return false }), in: .current)
if strongSelf.call.invitePeer(peer.id) {
strongSelf.controller?.present(UndoOverlayController(presentationData: strongSelf.presentationData, content: .invitedToVoiceChat(context: strongSelf.context, peer: peer, text: strongSelf.presentationData.strings.VoiceChat_InvitedPeerText(peer.displayTitle(strings: strongSelf.presentationData.strings, displayOrder: strongSelf.presentationData.nameDisplayOrder)).0), elevatedLayout: false, action: { _ in return false }), in: .current)
}
}))
})]), in: .window(.root))
}
@ -837,7 +839,15 @@ public final class VoiceChatController: ViewController {
|> deliverOnMainQueue).start(next: { [weak self] presentationData in
if let strongSelf = self {
strongSelf.presentationData = presentationData
strongSelf.actionButton.connectingColor = presentationData.theme.chatList.unreadBadgeInactiveBackgroundColor
let sourceColor = presentationData.theme.chatList.unreadBadgeInactiveBackgroundColor
let color: UIColor
if sourceColor.alpha < 1.0 {
color = presentationData.theme.chatList.unreadBadgeInactiveBackgroundColor.mixedWith(sourceColor.withAlphaComponent(1.0), alpha: sourceColor.alpha)
} else {
color = sourceColor
}
strongSelf.actionButton.connectingColor = color
}
})
@ -855,7 +865,6 @@ public final class VoiceChatController: ViewController {
}
if strongSelf.callState != state {
let wasMuted = strongSelf.callState?.muteState != nil
strongSelf.callState = state
if let muteState = state.muteState, !muteState.canUnmute {
@ -1227,7 +1236,7 @@ public final class VoiceChatController: ViewController {
self.call.setIsMuted(action: .muted(isPushToTalkActive: false))
}
self.itemInteraction?.updateAudioLevels([(self.context.account.peerId, 0.0)], reset: true)
self.itemInteraction?.updateAudioLevels([(self.context.account.peerId, 0.0, false)], reset: true)
if let (layout, navigationHeight) = self.validLayout {
self.containerLayoutUpdated(layout, navigationHeight: navigationHeight, transition: .animated(duration: 0.3, curve: .spring))
@ -1760,17 +1769,6 @@ public final class VoiceChatController: ViewController {
index += 1
}
if let accountPeer = self.accountPeer, !processedPeerIds.contains(accountPeer.id) {
entries.insert(.peer(PeerEntry(
peer: accountPeer,
presence: nil,
activityTimestamp: Int32.max - 1 - index,
state: .listening,
muteState: GroupCallParticipantsContext.Participant.MuteState(canUnmute: true),
canManageCall: callState?.canManageCall ?? false
)), at: 1)
}
for peer in invitedPeers {
if processedPeerIds.contains(peer.id) {
continue

View File

@ -103,6 +103,7 @@ public func getCurrentGroupCall(account: Account, callId: Int64, accessHash: Int
peer: peer,
ssrc: ssrc,
joinTimestamp: date,
activityTimestamp: activeDate.flatMap(Double.init),
muteState: muteState
))
}
@ -512,6 +513,20 @@ public final class GroupCallParticipantsContext {
public var activityTimestamp: Double?
public var muteState: MuteState?
public init(
peer: Peer,
ssrc: UInt32,
joinTimestamp: Int32,
activityTimestamp: Double?,
muteState: MuteState?
) {
self.peer = peer
self.ssrc = ssrc
self.joinTimestamp = joinTimestamp
self.activityTimestamp = activityTimestamp
self.muteState = muteState
}
public static func ==(lhs: Participant, rhs: Participant) -> Bool {
if !lhs.peer.isEqual(rhs.peer) {
return false
@ -599,12 +614,18 @@ public final class GroupCallParticipantsContext {
public enum Update {
public struct StateUpdate {
public struct ParticipantUpdate {
public enum ParticipationStatusChange {
case none
case joined
case left
}
public var peerId: PeerId
public var ssrc: UInt32
public var joinTimestamp: Int32
public var activityTimestamp: Double?
public var muteState: Participant.MuteState?
public var isRemoved: Bool
public var participationStatusChange: ParticipationStatusChange
}
public var participantUpdates: [ParticipantUpdate]
@ -896,7 +917,7 @@ public final class GroupCallParticipantsContext {
var updatedTotalCount = strongSelf.stateValue.state.totalCount
for participantUpdate in update.participantUpdates {
if participantUpdate.isRemoved {
if case .left = participantUpdate.participationStatusChange {
if let index = updatedParticipants.firstIndex(where: { $0.peer.id == participantUpdate.peerId }) {
updatedParticipants.remove(at: index)
updatedTotalCount = max(0, updatedTotalCount - 1)
@ -912,7 +933,7 @@ public final class GroupCallParticipantsContext {
if let index = updatedParticipants.firstIndex(where: { $0.peer.id == participantUpdate.peerId }) {
previousActivityTimestamp = updatedParticipants[index].activityTimestamp
updatedParticipants.remove(at: index)
} else {
} else if case .left = participantUpdate.participationStatusChange {
updatedTotalCount += 1
}
@ -1092,13 +1113,24 @@ extension GroupCallParticipantsContext.Update.StateUpdate.ParticipantUpdate {
muteState = GroupCallParticipantsContext.Participant.MuteState(canUnmute: canUnmute)
}
let isRemoved = (flags & (1 << 1)) != 0
let justJoined = (flags & (1 << 4)) != 0
let participationStatusChange: GroupCallParticipantsContext.Update.StateUpdate.ParticipantUpdate.ParticipationStatusChange
if isRemoved {
participationStatusChange = .left
} else if justJoined {
participationStatusChange = .joined
} else {
participationStatusChange = .none
}
self.init(
peerId: peerId,
ssrc: ssrc,
joinTimestamp: date,
activityTimestamp: activeDate.flatMap(Double.init),
muteState: muteState,
isRemoved: isRemoved
participationStatusChange: participationStatusChange
)
}
}
@ -1118,13 +1150,24 @@ extension GroupCallParticipantsContext.Update.StateUpdate {
muteState = GroupCallParticipantsContext.Participant.MuteState(canUnmute: canUnmute)
}
let isRemoved = (flags & (1 << 1)) != 0
let justJoined = (flags & (1 << 4)) != 0
let participationStatusChange: GroupCallParticipantsContext.Update.StateUpdate.ParticipantUpdate.ParticipationStatusChange
if isRemoved {
participationStatusChange = .left
} else if justJoined {
participationStatusChange = .joined
} else {
participationStatusChange = .none
}
participantUpdates.append(GroupCallParticipantsContext.Update.StateUpdate.ParticipantUpdate(
peerId: peerId,
ssrc: ssrc,
joinTimestamp: date,
activityTimestamp: activeDate.flatMap(Double.init),
muteState: muteState,
isRemoved: isRemoved
participationStatusChange: participationStatusChange
))
}
}

View File

@ -235,7 +235,7 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G
private let unblockingPeer = ValuePromise<Bool>(false, ignoreRepeated: true)
private let searching = ValuePromise<Bool>(false, ignoreRepeated: true)
private let searchResult = Promise<(SearchMessagesResult, SearchMessagesState, SearchMessagesLocation)?>()
private let loadingMessage = ValuePromise<ChatLoadingMessageSubject?>(nil, ignoreRepeated: true)
private let loadingMessage = Promise<ChatLoadingMessageSubject?>(nil)
private let performingInlineSearch = ValuePromise<Bool>(false, ignoreRepeated: true)
private var preloadHistoryPeerId: PeerId?
@ -4828,7 +4828,7 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G
guard let strongSelf = self else {
return
}
strongSelf.loadingMessage.set(.generic)
strongSelf.loadingMessage.set(.single(.generic))
let peerId: PeerId
let threadId: Int64?
@ -4843,7 +4843,7 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G
strongSelf.messageIndexDisposable.set((searchMessageIdByTimestamp(account: strongSelf.context.account, peerId: peerId, threadId: threadId, timestamp: timestamp) |> deliverOnMainQueue).start(next: { messageId in
if let strongSelf = self {
strongSelf.loadingMessage.set(nil)
strongSelf.loadingMessage.set(.single(nil))
if let messageId = messageId {
strongSelf.navigateToMessage(from: nil, to: .id(messageId), forceInCurrentChat: true)
}
@ -9251,13 +9251,13 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G
}
}, completed: { [weak self] in
if let strongSelf = self {
strongSelf.loadingMessage.set(nil)
strongSelf.loadingMessage.set(.single(nil))
strongSelf.chatDisplayNode.historyNode.scrollToEndOfHistory()
}
}))
cancelImpl = { [weak self] in
if let strongSelf = self {
strongSelf.loadingMessage.set(nil)
strongSelf.loadingMessage.set(.single(nil))
strongSelf.messageIndexDisposable.set(nil)
}
}
@ -9315,13 +9315,13 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G
}
}, completed: { [weak self] in
if let strongSelf = self {
strongSelf.loadingMessage.set(nil)
strongSelf.loadingMessage.set(.single(nil))
strongSelf.chatDisplayNode.historyNode.scrollToStartOfHistory()
}
}))
cancelImpl = { [weak self] in
if let strongSelf = self {
strongSelf.loadingMessage.set(nil)
strongSelf.loadingMessage.set(.single(nil))
strongSelf.messageIndexDisposable.set(nil)
}
}
@ -9499,14 +9499,14 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G
if let scrollFromIndex = scrollFromIndex {
if let messageId = messageLocation.messageId, let message = self.chatDisplayNode.historyNode.messageInCurrentHistoryView(messageId) {
self.loadingMessage.set(nil)
self.loadingMessage.set(.single(nil))
self.messageIndexDisposable.set(nil)
self.chatDisplayNode.historyNode.scrollToMessage(from: scrollFromIndex, to: message.index, animated: animated, scrollPosition: scrollPosition)
completion?()
} else if case let .index(index) = messageLocation, index.id.id == 0, index.timestamp > 0, case .scheduledMessages = self.presentationInterfaceState.subject {
self.chatDisplayNode.historyNode.scrollToMessage(from: scrollFromIndex, to: index, animated: animated, scrollPosition: scrollPosition)
} else {
self.loadingMessage.set(statusSubject)
self.loadingMessage.set(.single(statusSubject) |> delay(0.1, queue: .mainQueue()))
let searchLocation: ChatHistoryInitialSearchLocation
switch messageLocation {
case let .id(id):
@ -9588,12 +9588,12 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G
}
}, completed: { [weak self] in
if let strongSelf = self {
strongSelf.loadingMessage.set(nil)
strongSelf.loadingMessage.set(.single(nil))
}
}))
cancelImpl = { [weak self] in
if let strongSelf = self {
strongSelf.loadingMessage.set(nil)
strongSelf.loadingMessage.set(.single(nil))
strongSelf.messageIndexDisposable.set(nil)
}
}
@ -9615,7 +9615,7 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G
if let _ = fromId, rememberInStack {
self.historyNavigationStack.add(fromIndex)
}
self.loadingMessage.set(statusSubject)
self.loadingMessage.set(.single(statusSubject) |> delay(0.1, queue: .mainQueue()))
let historyView = preloadedChatHistoryViewForLocation(ChatHistoryLocationInput(content: .InitialSearch(location: searchLocation, count: 50, highlight: true), id: 0), context: self.context, chatLocation: self.chatLocation, subject: self.subject, chatLocationContextHolder: self.chatLocationContextHolder, fixedCombinedReadStates: nil, tagMask: nil, additionalData: [])
let signal = historyView
|> mapToSignal { historyView -> Signal<MessageIndex?, NoError> in
@ -9646,7 +9646,7 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G
}
}, completed: { [weak self] in
if let strongSelf = self {
strongSelf.loadingMessage.set(nil)
strongSelf.loadingMessage.set(.single(nil))
}
}))
} else {

View File

@ -21,6 +21,7 @@ import Markdown
import ManagedAnimationNode
import SlotMachineAnimationNode
import UniversalMediaPlayer
import ShimmerEffect
private let nameFont = Font.medium(14.0)
private let inlineBotPrefixFont = Font.regular(14.0)

View File

@ -293,6 +293,7 @@ private func channelRecentActionsFilterControllerEntries(presentationData: Prese
([.editMessages], presentationData.strings.Channel_AdminLogFilter_EventsEditedMessages),
([.pinnedMessages], presentationData.strings.Channel_AdminLogFilter_EventsPinned),
([.leave], presentationData.strings.Channel_AdminLogFilter_EventsLeaving),
([.calls], presentationData.strings.Channel_AdminLogFilter_EventsCalls)
]
} else {
order = [

View File

@ -51,7 +51,7 @@ final class HorizontalStickerGridItemNode: GridItemNode {
private var currentState: (Account, HorizontalStickerGridItem, CGSize)?
private let imageNode: TransformImageNode
private var animationNode: AnimatedStickerNode?
private var placeholderNode: ShimmerEffectNode?
private var placeholderNode: StickerShimmerEffectNode?
private let stickerFetchedDisposable = MetaDisposable()
@ -81,7 +81,7 @@ final class HorizontalStickerGridItemNode: GridItemNode {
override init() {
self.imageNode = TransformImageNode()
self.placeholderNode = ShimmerEffectNode()
self.placeholderNode = StickerShimmerEffectNode()
super.init()
@ -114,9 +114,11 @@ final class HorizontalStickerGridItemNode: GridItemNode {
if !animated {
placeholderNode.removeFromSupernode()
} else {
placeholderNode.allowsGroupOpacity = true
placeholderNode.alpha = 0.0
placeholderNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.2, completion: { [weak placeholderNode] _ in
placeholderNode?.removeFromSupernode()
placeholderNode?.allowsGroupOpacity = false
})
}
}
@ -188,8 +190,8 @@ final class HorizontalStickerGridItemNode: GridItemNode {
let placeholderFrame = CGRect(origin: CGPoint(x: floor((bounds.width - boundingSize.width) / 2.0), y: floor((bounds.height - boundingSize.height) / 2.0)), size: boundingSize)
placeholderNode.frame = bounds
if let theme = self.currentState?.1.theme {
placeholderNode.update(backgroundColor: theme.list.plainBackgroundColor, foregroundColor: theme.list.mediaPlaceholderColor.mixedWith(theme.list.plainBackgroundColor, alpha: 0.4), shimmeringColor: theme.list.mediaPlaceholderColor.withAlphaComponent(0.3), shapes: [.roundedRect(rect: placeholderFrame, cornerRadius: 10.0)], size: bounds.size)
if let theme = self.currentState?.1.theme, let file = self.currentState?.1.file {
placeholderNode.update(backgroundColor: theme.list.plainBackgroundColor, foregroundColor: theme.list.mediaPlaceholderColor.mixedWith(theme.list.plainBackgroundColor, alpha: 0.4), shimmeringColor: theme.list.mediaPlaceholderColor.withAlphaComponent(0.3), data: file.immediateThumbnailData, size: bounds.size)
}
}

View File

@ -11,61 +11,7 @@ import StickerResources
import AccountContext
import AnimatedStickerNode
import TelegramAnimatedStickerNode
class MediaInputPaneTrendingItem: ListViewItem {
let account: Account
let theme: PresentationTheme
let strings: PresentationStrings
let interaction: TrendingPaneInteraction
let info: StickerPackCollectionInfo
let topItems: [StickerPackItem]
let installed: Bool
let unread: Bool
init(account: Account, theme: PresentationTheme, strings: PresentationStrings, interaction: TrendingPaneInteraction, info: StickerPackCollectionInfo, topItems: [StickerPackItem], installed: Bool, unread: Bool) {
self.account = account
self.theme = theme
self.strings = strings
self.interaction = interaction
self.info = info
self.topItems = topItems
self.installed = installed
self.unread = unread
}
func nodeConfiguredForParams(async: @escaping (@escaping () -> Void) -> Void, params: ListViewItemLayoutParams, synchronousLoads: Bool, previousItem: ListViewItem?, nextItem: ListViewItem?, completion: @escaping (ListViewItemNode, @escaping () -> (Signal<Void, NoError>?, (ListViewItemApply) -> Void)) -> Void) {
async {
let node = MediaInputPaneTrendingItemNode()
let (layout, apply) = node.asyncLayout()(self, params)
node.contentSize = layout.contentSize
node.insets = layout.insets
Queue.mainQueue().async {
completion(node, {
return (nil, { info in apply(synchronousLoads && info.isOnScreen) })
})
}
}
}
func updateNode(async: @escaping (@escaping () -> Void) -> Void, node: @escaping () -> ListViewItemNode, params: ListViewItemLayoutParams, previousItem: ListViewItem?, nextItem: ListViewItem?, animation: ListViewItemUpdateAnimation, completion: @escaping (ListViewItemNodeLayout, @escaping (ListViewItemApply) -> Void) -> Void) {
Queue.mainQueue().async {
if let nodeValue = node() as? MediaInputPaneTrendingItemNode {
let makeLayout = nodeValue.asyncLayout()
async {
let (layout, apply) = makeLayout(self, params)
Queue.mainQueue().async {
completion(layout, { _ in
apply(false)
})
}
}
}
}
}
}
import ShimmerEffect
private let titleFont = Font.bold(16.0)
private let statusFont = Font.regular(15.0)
@ -74,7 +20,10 @@ private let buttonFont = Font.medium(13.0)
final class TrendingTopItemNode: ASDisplayNode {
private let imageNode: TransformImageNode
private var animationNode: AnimatedStickerNode?
private var placeholderNode: StickerShimmerEffectNode?
public private(set) var file: TelegramMediaFile? = nil
public private(set) var theme: PresentationTheme?
private var listAppearance = false
private var itemSize: CGSize?
private let loadDisposable = MetaDisposable()
@ -91,15 +40,77 @@ final class TrendingTopItemNode: ASDisplayNode {
override init() {
self.imageNode = TransformImageNode()
self.imageNode.contentAnimations = [.subsequentUpdates]
self.placeholderNode = StickerShimmerEffectNode()
self.placeholderNode?.isUserInteractionEnabled = false
super.init()
self.addSubnode(self.imageNode)
if let placeholderNode = self.placeholderNode {
self.addSubnode(placeholderNode)
}
var firstTime = true
self.imageNode.imageUpdated = { [weak self] image in
guard let strongSelf = self else {
return
}
if image != nil {
strongSelf.removePlaceholder(animated: !firstTime)
}
firstTime = false
}
}
deinit {
self.loadDisposable.dispose()
}
private func removePlaceholder(animated: Bool) {
if let placeholderNode = self.placeholderNode {
self.placeholderNode = nil
if !animated {
placeholderNode.removeFromSupernode()
} else {
placeholderNode.allowsGroupOpacity = true
placeholderNode.alpha = 0.0
placeholderNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.2, completion: { [weak placeholderNode] _ in
placeholderNode?.removeFromSupernode()
placeholderNode?.allowsGroupOpacity = false
})
}
}
}
private var absoluteLocation: (CGRect, CGSize)?
func updateAbsoluteRect(_ rect: CGRect, within containerSize: CGSize) {
self.absoluteLocation = (rect, containerSize)
if let placeholderNode = placeholderNode {
placeholderNode.updateAbsoluteRect(rect, within: containerSize)
}
}
func update(theme: PresentationTheme, listAppearance: Bool) {
self.theme = theme
self.listAppearance = listAppearance
let backgroundColor: UIColor
let foregroundColor: UIColor
let shimmeringColor: UIColor
if listAppearance {
backgroundColor = theme.list.plainBackgroundColor
foregroundColor = theme.list.itemPlainSeparatorColor.blitOver(backgroundColor, alpha: 0.3)
shimmeringColor = theme.list.itemBlocksBackgroundColor.withAlphaComponent(0.4)
} else {
backgroundColor = theme.chat.inputMediaPanel.stickersBackgroundColor.withAlphaComponent(1.0)
foregroundColor = theme.chat.inputMediaPanel.stickersSectionTextColor.blitOver(backgroundColor, alpha: 0.15)
shimmeringColor = theme.list.itemBlocksBackgroundColor.withAlphaComponent(0.3)
}
if let placeholderNode = self.placeholderNode, let file = self.file {
placeholderNode.update(backgroundColor: backgroundColor, foregroundColor: foregroundColor, shimmeringColor: shimmeringColor, data: file.immediateThumbnailData, size: placeholderNode.frame.size)
}
}
func setup(account: Account, item: StickerPackItem, itemSize: CGSize, synchronousLoads: Bool) {
self.file = item.file
self.itemSize = itemSize
@ -112,8 +123,13 @@ final class TrendingTopItemNode: ASDisplayNode {
animationNode = AnimatedStickerNode()
animationNode.transform = self.imageNode.transform
animationNode.visibility = self.visibility
self.addSubnode(animationNode)
self.animationNode = animationNode
if let placeholderNode = self.placeholderNode {
self.insertSubnode(animationNode, belowSubnode: placeholderNode)
} else {
self.addSubnode(animationNode)
}
}
let dimensions = item.file.dimensions ?? PixelDimensions(width: 512, height: 512)
let fittedDimensions = dimensions.cgSize.aspectFitted(CGSize(width: 160.0, height: 160.0))
@ -161,285 +177,17 @@ final class TrendingTopItemNode: ASDisplayNode {
self.imageNode.frame = self.bounds
self.animationNode?.updateLayout(size: self.bounds.size)
}
}
class MediaInputPaneTrendingItemNode: ListViewItemNode {
private let titleNode: TextNode
private let descriptionNode: TextNode
private let unreadNode: ASImageNode
private let installTextNode: TextNode
private let installBackgroundNode: ASImageNode
private let installButtonNode: HighlightTrackingButtonNode
private var itemNodes: [TrendingTopItemNode]
private var item: MediaInputPaneTrendingItem?
private let preloadDisposable = MetaDisposable()
private let readDisposable = MetaDisposable()
override var visibility: ListViewItemNodeVisibility {
didSet {
let wasVisible = oldValue != .none
let isVisible = self.visibility != .none
let size = self.bounds.size
let boundingSize = size
if let placeholderNode = self.placeholderNode {
let placeholderFrame = CGRect(origin: CGPoint(x: floor((size.width - boundingSize.width) / 2.0), y: floor((size.height - boundingSize.height) / 2.0)), size: boundingSize)
placeholderNode.frame = placeholderFrame
if isVisible != wasVisible {
for node in self.itemNodes {
node.visibility = isVisible
}
if isVisible {
if let item = self.item, item.unread {
self.readDisposable.set((
markFeaturedStickerPacksAsSeenInteractively(postbox: item.account.postbox, ids: [item.info.id])
|> delay(1.0, queue: .mainQueue())
).start())
}
} else {
self.readDisposable.set(nil)
}
if let theme = self.theme {
self.update(theme: theme, listAppearance: self.listAppearance)
}
}
}
init() {
self.titleNode = TextNode()
self.titleNode.isUserInteractionEnabled = false
self.titleNode.contentMode = .left
self.titleNode.contentsScale = UIScreen.main.scale
self.descriptionNode = TextNode()
self.descriptionNode.isUserInteractionEnabled = false
self.descriptionNode.contentMode = .left
self.descriptionNode.contentsScale = UIScreen.main.scale
self.unreadNode = ASImageNode()
self.unreadNode.isLayerBacked = true
self.unreadNode.displayWithoutProcessing = true
self.unreadNode.displaysAsynchronously = false
self.installTextNode = TextNode()
self.installTextNode.isUserInteractionEnabled = false
self.installTextNode.contentMode = .left
self.installTextNode.contentsScale = UIScreen.main.scale
self.installBackgroundNode = ASImageNode()
self.installBackgroundNode.isLayerBacked = true
self.installBackgroundNode.displayWithoutProcessing = true
self.installBackgroundNode.displaysAsynchronously = false
self.installButtonNode = HighlightTrackingButtonNode()
self.itemNodes = []
super.init(layerBacked: false, dynamicBounce: false)
self.addSubnode(self.titleNode)
self.addSubnode(self.descriptionNode)
self.addSubnode(self.unreadNode)
self.addSubnode(self.installBackgroundNode)
self.addSubnode(self.installTextNode)
self.addSubnode(self.installButtonNode)
self.installButtonNode.highligthedChanged = { [weak self] highlighted in
if let strongSelf = self {
if highlighted {
strongSelf.installBackgroundNode.layer.removeAnimation(forKey: "opacity")
strongSelf.installBackgroundNode.alpha = 0.4
strongSelf.installTextNode.layer.removeAnimation(forKey: "opacity")
strongSelf.installTextNode.alpha = 0.4
} else {
strongSelf.installBackgroundNode.alpha = 1.0
strongSelf.installBackgroundNode.layer.animateAlpha(from: 0.4, to: 1.0, duration: 0.2)
strongSelf.installTextNode.alpha = 1.0
strongSelf.installTextNode.layer.animateAlpha(from: 0.4, to: 1.0, duration: 0.2)
}
}
}
self.installButtonNode.addTarget(self, action: #selector(self.installPressed), forControlEvents: .touchUpInside)
}
deinit {
self.preloadDisposable.dispose()
self.readDisposable.dispose()
}
override func didLoad() {
super.didLoad()
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.tapGesture(_:))))
}
func asyncLayout() -> (_ item: MediaInputPaneTrendingItem, _ params: ListViewItemLayoutParams) -> (ListViewItemNodeLayout, (Bool) -> Void) {
let makeInstallLayout = TextNode.asyncLayout(self.installTextNode)
let makeTitleLayout = TextNode.asyncLayout(self.titleNode)
let makeDescriptionLayout = TextNode.asyncLayout(self.descriptionNode)
let currentItem = self.item
return { item, params in
var updateButtonBackgroundImage: UIImage?
if currentItem?.theme !== item.theme {
updateButtonBackgroundImage = PresentationResourcesChat.chatInputMediaPanelAddPackButtonImage(item.theme)
}
let unreadImage = PresentationResourcesItemList.stickerUnreadDotImage(item.theme)
let leftInset: CGFloat = 14.0
let rightInset: CGFloat = 16.0
let (installLayout, installApply) = makeInstallLayout(TextNodeLayoutArguments(attributedString: NSAttributedString(string: item.strings.Stickers_Install, font: buttonFont, textColor: item.theme.list.itemAccentColor), backgroundColor: nil, maximumNumberOfLines: 1, truncationType: .end, constrainedSize: CGSize(width: params.width - params.leftInset - params.rightInset - leftInset - rightInset, height: CGFloat.greatestFiniteMagnitude), alignment: .natural, cutout: nil, insets: UIEdgeInsets()))
let (titleLayout, titleApply) = makeTitleLayout(TextNodeLayoutArguments(attributedString: NSAttributedString(string: item.info.title, font: titleFont, textColor: item.theme.list.itemPrimaryTextColor), backgroundColor: nil, maximumNumberOfLines: 1, truncationType: .end, constrainedSize: CGSize(width: params.width - params.leftInset - params.rightInset - leftInset - rightInset - 20.0 - installLayout.size.width, height: CGFloat.greatestFiniteMagnitude), alignment: .natural, cutout: nil, insets: UIEdgeInsets()))
let (descriptionLayout, descriptionApply) = makeDescriptionLayout(TextNodeLayoutArguments(attributedString: NSAttributedString(string: item.strings.StickerPack_StickerCount(item.info.count), font: statusFont, textColor: item.theme.chat.inputMediaPanel.stickersSectionTextColor), backgroundColor: nil, maximumNumberOfLines: 1, truncationType: .end, constrainedSize: CGSize(width: params.width - params.leftInset - params.rightInset - leftInset - rightInset - 20.0, height: CGFloat.greatestFiniteMagnitude), alignment: .natural, cutout: nil, insets: UIEdgeInsets()))
let contentSize: CGSize = CGSize(width: params.width, height: 120.0)
let insets: UIEdgeInsets = UIEdgeInsets(top: 8.0, left: 0.0, bottom: 0.0, right: 0.0)
let layout = ListViewItemNodeLayout(contentSize: contentSize, insets: insets)
var topItems = item.topItems
if topItems.count > 5 {
topItems.removeSubrange(5 ..< topItems.count)
}
return (layout, { [weak self] synchronousLoads in
if let strongSelf = self {
if (item.topItems.count < Int(item.info.count) || item.topItems.count < 5) && strongSelf.item?.info.id != item.info.id {
strongSelf.preloadDisposable.set(preloadedFeaturedStickerSet(network: item.account.network, postbox: item.account.postbox, id: item.info.id).start())
}
strongSelf.item = item
let _ = installApply()
let _ = titleApply()
let _ = descriptionApply()
if let updateButtonBackgroundImage = updateButtonBackgroundImage {
strongSelf.installBackgroundNode.image = updateButtonBackgroundImage
}
let installWidth: CGFloat = installLayout.size.width + 20.0
let buttonFrame = CGRect(origin: CGPoint(x: params.width - params.rightInset - rightInset - installWidth, y: 4.0), size: CGSize(width: installWidth, height: 26.0))
strongSelf.installBackgroundNode.frame = buttonFrame
strongSelf.installTextNode.frame = CGRect(origin: CGPoint(x: buttonFrame.minX + floor((buttonFrame.width - installLayout.size.width) / 2.0), y: buttonFrame.minY + floor((buttonFrame.height - installLayout.size.height) / 2.0) + 1.0), size: installLayout.size)
strongSelf.installButtonNode.frame = buttonFrame
if item.installed {
strongSelf.installButtonNode.isHidden = true
strongSelf.installBackgroundNode.isHidden = true
strongSelf.installTextNode.isHidden = true
} else {
strongSelf.installButtonNode.isHidden = false
strongSelf.installBackgroundNode.isHidden = false
strongSelf.installTextNode.isHidden = false
}
let titleFrame = CGRect(origin: CGPoint(x: params.leftInset + leftInset, y: 2.0), size: titleLayout.size)
strongSelf.titleNode.frame = titleFrame
strongSelf.descriptionNode.frame = CGRect(origin: CGPoint(x: params.leftInset + leftInset, y: 23.0), size: descriptionLayout.size)
if item.unread {
strongSelf.unreadNode.isHidden = false
} else {
strongSelf.unreadNode.isHidden = true
}
if let image = unreadImage {
strongSelf.unreadNode.image = image
strongSelf.unreadNode.frame = CGRect(origin: CGPoint(x: titleFrame.maxX + 2.0, y: titleFrame.minY + 7.0), size: image.size)
}
let sideInset: CGFloat = 2.0
let availableWidth = params.width - params.leftInset - params.rightInset - sideInset * 2.0
var itemSide: CGFloat = floor(availableWidth / 5.0)
itemSide = min(itemSide, 75.0)
let itemSize = CGSize(width: itemSide, height: itemSide)
var offset = sideInset
let itemSpacing = (max(0, availableWidth - 5.0 * itemSide - sideInset * 2.0)) / 4.0
let isVisible = strongSelf.visibility != .none
for i in 0 ..< topItems.count {
let file = topItems[i].file
let node: TrendingTopItemNode
if i < strongSelf.itemNodes.count {
node = strongSelf.itemNodes[i]
} else {
node = TrendingTopItemNode()
node.visibility = isVisible
strongSelf.itemNodes.append(node)
strongSelf.addSubnode(node)
}
if file.fileId != node.file?.fileId {
node.setup(account: item.account, item: topItems[i], itemSize: itemSize, synchronousLoads: synchronousLoads)
}
if let dimensions = file.dimensions {
let imageSize = dimensions.cgSize.aspectFitted(itemSize)
node.frame = CGRect(origin: CGPoint(x: offset, y: 48.0), size: imageSize)
offset += itemSize.width + itemSpacing
}
}
if topItems.count < strongSelf.itemNodes.count {
for i in (topItems.count ..< strongSelf.itemNodes.count).reversed() {
strongSelf.itemNodes[i].removeFromSupernode()
strongSelf.itemNodes.remove(at: i)
}
}
strongSelf.updatePreviewing(animated: false)
}
})
}
}
override func animateInsertion(_ currentTimestamp: Double, duration: Double, short: Bool) {
self.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.4)
}
override func animateRemoved(_ currentTimestamp: Double, duration: Double) {
self.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.15, removeOnCompletion: false)
}
@objc func installPressed() {
if let item = self.item {
item.interaction.installPack(item.info)
}
}
@objc func tapGesture(_ recognizer: UITapGestureRecognizer) {
if case .ended = recognizer.state {
if let item = self.item {
item.interaction.openPack(item.info)
}
}
}
func itemAt(point: CGPoint) -> (ASDisplayNode, StickerPackItem)? {
guard let item = self.item else {
return nil
}
var index = 0
for itemNode in self.itemNodes {
if itemNode.frame.contains(point), index < item.topItems.count {
return (itemNode, item.topItems[index])
}
index += 1
}
return nil
}
func updatePreviewing(animated: Bool) {
guard let item = self.item else {
return
}
var index = 0
for itemNode in self.itemNodes {
if index < item.topItems.count {
let isPreviewing = item.interaction.getItemIsPreviewed(item.topItems[index])
itemNode.updatePreviewing(animated: animated, isPreviewing: isPreviewing)
}
index += 1
}
}
}

View File

@ -302,6 +302,16 @@ class StickerPaneSearchGlobalItemNode: GridItemNode {
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.tapGesture(_:))))
}
private var absoluteLocation: (CGRect, CGSize)?
override public func updateAbsoluteRect(_ rect: CGRect, within containerSize: CGSize) {
self.absoluteLocation = (rect, containerSize)
for node in self.itemNodes {
let nodeRect = CGRect(origin: CGPoint(x: rect.minX + node.frame.minX, y: rect.minY + node.frame.minY), size: node.frame.size)
node.updateAbsoluteRect(nodeRect, within: containerSize)
}
}
func setup(item: StickerPaneSearchGlobalItem) {
if item.topItems.count < Int(item.info.count) && item.topItems.count < 5 && self.item?.info.id != item.info.id {
self.preloadDisposable.set(preloadedFeaturedStickerSet(network: item.account.network, postbox: item.account.postbox, id: item.info.id).start())
@ -451,11 +461,17 @@ class StickerPaneSearchGlobalItemNode: GridItemNode {
if file.fileId != node.file?.fileId {
node.setup(account: item.account, item: topItems[i], itemSize: itemSize, synchronousLoads: synchronousLoads)
}
if item.theme !== node.theme {
node.update(theme: item.theme, listAppearance: item.listAppearance)
}
if let dimensions = file.dimensions {
let imageSize = dimensions.cgSize.aspectFitted(itemSize)
node.frame = CGRect(origin: CGPoint(x: offset, y: 48.0 + topOffset), size: imageSize)
offset += itemSize.width + itemSpacing
}
if let (rect, size) = strongSelf.absoluteLocation {
strongSelf.updateAbsoluteRect(rect, within: size)
}
}
if topItems.count < strongSelf.itemNodes.count {

View File

@ -46,7 +46,7 @@ public final class OngoingGroupCallContext {
let joinPayload = Promise<(String, UInt32)>()
let networkState = ValuePromise<NetworkState>(.connecting, ignoreRepeated: true)
let isMuted = ValuePromise<Bool>(true, ignoreRepeated: true)
let audioLevels = ValuePipe<[(AudioLevelKey, Float)]>()
let audioLevels = ValuePipe<[(AudioLevelKey, Float, Bool)]>()
init(queue: Queue, inputDeviceId: String, outputDeviceId: String) {
self.queue = queue
@ -88,7 +88,7 @@ public final class OngoingGroupCallContext {
let audioLevels = self.audioLevels
audioLevelsUpdatedImpl = { levels in
var mappedLevels: [(AudioLevelKey, Float)] = []
var mappedLevels: [(AudioLevelKey, Float, Bool)] = []
var i = 0
while i < levels.count {
let uintValue = levels[i].uint32Value
@ -98,8 +98,8 @@ public final class OngoingGroupCallContext {
} else {
key = .source(uintValue)
}
mappedLevels.append((key, levels[i + 1].floatValue))
i += 2
mappedLevels.append((key, levels[i + 1].floatValue, levels[i + 2].boolValue))
i += 3
}
queue.async {
audioLevels.putNext(mappedLevels)
@ -177,7 +177,7 @@ public final class OngoingGroupCallContext {
}
}
public var audioLevels: Signal<[(AudioLevelKey, Float)], NoError> {
public var audioLevels: Signal<[(AudioLevelKey, Float, Bool)], NoError> {
return Signal { subscriber in
let disposable = MetaDisposable()
self.impl.with { impl in

View File

@ -559,6 +559,11 @@ public final class OngoingCallContext {
return self.receptionPromise.get()
}
private let audioLevelPromise = Promise<Float>(0.0)
public var audioLevel: Signal<Float, NoError> {
return self.audioLevelPromise.get()
}
private let audioSessionDisposable = MetaDisposable()
private var networkTypeDisposable: Disposable?
@ -687,6 +692,9 @@ public final class OngoingCallContext {
context.signalBarsChanged = { signalBars in
self?.receptionPromise.set(.single(signalBars))
}
context.audioLevelUpdated = { level in
self?.audioLevelPromise.set(.single(level))
}
strongSelf.networkTypeDisposable = (updatedNetworkType
|> deliverOn(queue)).start(next: { networkType in

View File

@ -127,6 +127,7 @@ typedef NS_ENUM(int32_t, OngoingCallDataSavingWebrtc) {
@property (nonatomic, copy) void (^ _Nullable stateChanged)(OngoingCallStateWebrtc, OngoingCallVideoStateWebrtc, OngoingCallRemoteVideoStateWebrtc, OngoingCallRemoteAudioStateWebrtc, OngoingCallRemoteBatteryLevelWebrtc, float);
@property (nonatomic, copy) void (^ _Nullable signalBarsChanged)(int32_t);
@property (nonatomic, copy) void (^ _Nullable audioLevelUpdated)(float);
- (instancetype _Nonnull)initWithVersion:(NSString * _Nonnull)version queue:(id<OngoingCallThreadLocalContextQueueWebrtc> _Nonnull)queue proxy:(VoipProxyServerWebrtc * _Nullable)proxy networkType:(OngoingCallNetworkTypeWebrtc)networkType dataSaving:(OngoingCallDataSavingWebrtc)dataSaving derivedState:(NSData * _Nonnull)derivedState key:(NSData * _Nonnull)key isOutgoing:(bool)isOutgoing connections:(NSArray<OngoingCallConnectionDescriptionWebrtc *> * _Nonnull)connections maxLayer:(int32_t)maxLayer allowP2P:(BOOL)allowP2P allowTCP:(BOOL)allowTCP enableStunMarking:(BOOL)enableStunMarking logPath:(NSString * _Nonnull)logPath statsLogPath:(NSString * _Nonnull)statsLogPath sendSignalingData:(void (^ _Nonnull)(NSData * _Nonnull))sendSignalingData videoCapturer:(OngoingCallThreadLocalContextVideoCapturer * _Nullable)videoCapturer preferredVideoCodec:(NSString * _Nullable)preferredVideoCodec audioInputDeviceId: (NSString * _Nonnull)audioInputDeviceId;

View File

@ -463,6 +463,16 @@ static void (*InternalVoipLoggingFunction)(NSString *) = NULL;
}
}];
},
.audioLevelUpdated = [weakSelf, queue](float level) {
[queue dispatch:^{
__strong OngoingCallThreadLocalContextWebrtc *strongSelf = weakSelf;
if (strongSelf) {
if (strongSelf->_audioLevelUpdated) {
strongSelf->_audioLevelUpdated(level);
}
}
}];
},
.remoteMediaStateUpdated = [weakSelf, queue](tgcalls::AudioState audioState, tgcalls::VideoState videoState) {
[queue dispatch:^{
__strong OngoingCallThreadLocalContextWebrtc *strongSelf = weakSelf;
@ -825,11 +835,12 @@ static void (*InternalVoipLoggingFunction)(NSString *) = NULL;
networkStateUpdated(isConnected ? GroupCallNetworkStateConnected : GroupCallNetworkStateConnecting);
}];
},
.audioLevelsUpdated = [audioLevelsUpdated](std::vector<std::pair<uint32_t, float>> const &levels) {
.audioLevelsUpdated = [audioLevelsUpdated](std::vector<std::pair<uint32_t, std::pair<float, bool>>> const &levels) {
NSMutableArray *result = [[NSMutableArray alloc] init];
for (auto &it : levels) {
[result addObject:@(it.first)];
[result addObject:@(it.second)];
[result addObject:@(it.second.first)];
[result addObject:@(it.second.second)];
}
audioLevelsUpdated(result);
},

@ -1 +1 @@
Subproject commit 503f8ad1e8f0a744b1fb3eddb66e33176e427074
Subproject commit 6ae73f4c388854d86a0ce66bf243561a11d9e719