Fix some concurrency warnings, update missed licence headers. (#3741)

* Switch the TimelineController to an async sequence and fix the warnings on the UserIndicatorController
This commit is contained in:
Stefan Ceriu 2025-02-06 11:35:23 +02:00 committed by GitHub
parent f86a5a2bb9
commit 922ebf47e6
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
22 changed files with 129 additions and 184 deletions

View File

@ -1,3 +1,3 @@
#!/bin/sh
command -v git-lfs >/dev/null 2>&1 || { echo >&2 "\nThis repository is configured for Git LFS but 'git-lfs' was not found on your path. If you no longer wish to use Git LFS, remove this hook by deleting the 'pre-push' file in the hooks directory (set by 'core.hookspath'; usually '.git/hooks').\n"; exit 2; }
command -v git-lfs >/dev/null 2>&1 || { printf >&2 "\n%s\n\n" "This repository is configured for Git LFS but 'git-lfs' was not found on your path. If you no longer wish to use Git LFS, remove this hook by deleting the 'pre-push' file in the hooks directory (set by 'core.hookspath'; usually '.git/hooks')."; exit 2; }
git lfs pre-push "$@"

View File

@ -7,6 +7,7 @@
import Foundation
@MainActor
protocol AppCoordinatorProtocol: CoordinatorProtocol {
var windowManager: SecureWindowManagerProtocol { get }

View File

@ -1,17 +1,8 @@
//
// Copyright 2024 New Vector Ltd
// Copyright 2022-2024 New Vector Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
// Please see LICENSE files in the repository root for full details.
//
import Combine

View File

@ -8,6 +8,7 @@
import Foundation
/// Represents a specific portion of the ViewState that can be bound to with SwiftUI's [2-way binding](https://developer.apple.com/documentation/swiftui/binding).
@MainActor
protocol BindableState {
/// The associated type of the Bindable State. Defaults to Void.
associatedtype BindStateType = Void

View File

@ -5,10 +5,11 @@
// Please see LICENSE files in the repository root for full details.
//
import Combine
import SwiftUI
class UserIndicatorController: ObservableObject, UserIndicatorControllerProtocol {
private var dismissalTimer: Timer?
private var timerCancellable: AnyCancellable?
private var displayTimes = [String: Date]()
private var delayedIndicators = Set<String>()
@ -21,10 +22,11 @@ class UserIndicatorController: ObservableObject, UserIndicatorControllerProtocol
activeIndicator = indicatorQueue.last
if let activeIndicator, !activeIndicator.persistent {
dismissalTimer?.invalidate()
dismissalTimer = Timer.scheduledTimer(withTimeInterval: nonPersistentDisplayDuration, repeats: false) { [weak self] _ in
timerCancellable?.cancel()
timerCancellable = Task { [weak self, nonPersistentDisplayDuration] in
try await Task.sleep(for: .seconds(nonPersistentDisplayDuration))
self?.retractIndicatorWithId(activeIndicator.id)
}
}.asCancellable()
}
}
}
@ -47,8 +49,8 @@ class UserIndicatorController: ObservableObject, UserIndicatorControllerProtocol
if let delay {
delayedIndicators.insert(indicator.id)
Timer.scheduledTimer(withTimeInterval: delay.seconds, repeats: false) { [weak self] _ in
guard let self else { return }
Task {
try await Task.sleep(for: .seconds(delay.seconds))
guard delayedIndicators.contains(indicator.id) else {
return
@ -76,9 +78,10 @@ class UserIndicatorController: ObservableObject, UserIndicatorControllerProtocol
return
}
Timer.scheduledTimer(withTimeInterval: minimumDisplayDuration, repeats: false) { [weak self] _ in
self?.indicatorQueue.removeAll { $0.id == id }
self?.displayTimes[id] = nil
Task {
try? await Task.sleep(for: .seconds(minimumDisplayDuration))
indicatorQueue.removeAll { $0.id == id }
displayTimes[id] = nil
}
}

View File

@ -7,6 +7,7 @@
import Combine
@MainActor
protocol SoftLogoutScreenViewModelProtocol {
var actions: AnyPublisher<SoftLogoutScreenViewModelAction, Never> { get }
var context: SoftLogoutScreenViewModelType.Context { get }

View File

@ -81,7 +81,7 @@ struct WebRegistrationWebView: UIViewRepresentable {
webView.load(URLRequest(url: url))
}
nonisolated func userContentController(_ userContentController: WKUserContentController,
func userContentController(_ userContentController: WKUserContentController,
didReceive message: WKScriptMessage) {
guard let jsonString = message.body as? String, let jsonData = jsonString.data(using: .utf8) else {
MXLog.error("Unexpected response.")
@ -94,7 +94,7 @@ struct WebRegistrationWebView: UIViewRepresentable {
}
MXLog.info("Received login credentials.")
Task { await viewModelContext.send(viewAction: .signedIn(credentials)) }
viewModelContext.send(viewAction: .signedIn(credentials))
}
// MARK: WKUIDelegate
@ -120,7 +120,7 @@ struct WebRegistrationWebView: UIViewRepresentable {
// MARK: WKScriptMessageHandler
nonisolated func userContentController(_ userContentController: WKUserContentController,
func userContentController(_ userContentController: WKUserContentController,
didReceive message: WKScriptMessage) {
coordinator?.userContentController(userContentController, didReceive: message)
}

View File

@ -152,11 +152,8 @@ private struct CallView: UIViewRepresentable {
}
}
nonisolated func userContentController(_ userContentController: WKUserContentController,
didReceive message: WKScriptMessage) {
Task { @MainActor [weak self] in
self?.viewModelContext?.javaScriptMessageHandler?(message.body)
}
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
viewModelContext?.javaScriptMessageHandler?(message.body)
}
// MARK: - WKUIDelegate
@ -191,11 +188,9 @@ private struct CallView: UIViewRepresentable {
return .cancel
}
nonisolated func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
Task { @MainActor in
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
viewModelContext?.send(viewAction: .urlChanged(webView.url))
}
}
// MARK: - Picture in Picture
@ -271,8 +266,7 @@ private struct CallView: UIViewRepresentable {
// MARK: - WKScriptMessageHandler
nonisolated func userContentController(_ userContentController: WKUserContentController,
didReceive message: WKScriptMessage) {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
coordinator?.userContentController(userContentController, didReceive: message)
}
}

View File

@ -6,7 +6,6 @@
//
import Combine
import Foundation
@MainActor
protocol ReportContentScreenViewModelProtocol {

View File

@ -1,17 +1,8 @@
//
// Copyright 2022 New Vector Ltd
// Copyright 2022-2024 New Vector Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
// Please see LICENSE files in the repository root for full details.
//
import Combine

View File

@ -1,17 +1,8 @@
//
// Copyright 2022 New Vector Ltd
// Copyright 2022-2024 New Vector Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
// Please see LICENSE files in the repository root for full details.
//
import Foundation

View File

@ -1,17 +1,8 @@
//
// Copyright 2022 New Vector Ltd
// Copyright 2022-2024 New Vector Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
// Please see LICENSE files in the repository root for full details.
//
import Combine

View File

@ -1,17 +1,8 @@
//
// Copyright 2022 New Vector Ltd
// Copyright 2022-2024 New Vector Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
// Please see LICENSE files in the repository root for full details.
//
import Combine

View File

@ -1,17 +1,8 @@
//
// Copyright 2022 New Vector Ltd
// Copyright 2022-2024 New Vector Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
// Please see LICENSE files in the repository root for full details.
//
import Compound

View File

@ -9,6 +9,7 @@ import Combine
import WysiwygComposer
// periphery: ignore - markdown protocol
@MainActor
protocol ComposerToolbarViewModelProtocol {
var actions: AnyPublisher<ComposerToolbarViewModelAction, Never> { get }
var context: ComposerToolbarViewModelType.Context { get }

View File

@ -6,8 +6,8 @@
//
import Combine
import Foundation
@MainActor
protocol RoomScreenViewModelProtocol {
var actions: AnyPublisher<RoomScreenViewModelAction, Never> { get }
var context: RoomScreenViewModel.Context { get }

View File

@ -324,16 +324,12 @@ class ClientProxy: ClientProxyProtocol {
// Note: This isn't strictly necessary now given the unwrap above, but leaving the code as
// documentation. SE-0371 will allow us to fix this by using an async deinit.
Task { [syncService] in
do {
defer {
completion?()
}
try await syncService.stop()
await syncService.stop()
MXLog.info("Sync stopped")
} catch {
MXLog.error("Failed stopping the sync service with error: \(error)")
}
}
}

View File

@ -46,7 +46,7 @@ final class ComposerDraftService: ComposerDraftServiceProtocol {
func getReply(eventID: String) async -> Result<TimelineItemReply, ComposerDraftServiceError> {
switch await roomProxy.timeline.getLoadedReplyDetails(eventID: eventID) {
case .success(let replyDetails):
return await .success(timelineItemfactory.buildReply(details: replyDetails))
return .success(timelineItemfactory.buildReply(details: replyDetails))
case .failure(let error):
MXLog.error("Could not load reply: \(error)")
return .failure(.failedToLoadReply)

View File

@ -62,8 +62,6 @@ class TimelineController: TimelineControllerProtocol {
activeTimeline = timelineProxy
activeTimelineProvider = liveTimelineProvider
NotificationCenter.default.addObserver(self, selector: #selector(contentSizeCategoryDidChange), name: UIContentSizeCategory.didChangeNotification, object: nil)
guard let initialFocussedEventID else {
configureActiveTimelineProvider()
return
@ -148,7 +146,9 @@ class TimelineController: TimelineControllerProtocol {
}
if let messageTimelineItem = timelineItem as? EventBasedMessageTimelineItemProtocol {
fetchEventDetails(for: messageTimelineItem, refetchOnError: true)
fetchEventDetails(for: messageTimelineItem,
refetchOnError: true,
activeTimeline: activeTimeline)
}
}
@ -375,35 +375,37 @@ class TimelineController: TimelineControllerProtocol {
paginationState = PaginationState(backward: .paginating, forward: .paginating)
callbacks.send(.isLive(activeTimelineProvider.kind == .live))
updateTimelineItemsCancellable = activeTimelineProvider
.updatePublisher
.receive(on: serialDispatchQueue)
.sink { [weak self] items, paginationState in
self?.updateTimelineItems(itemProxies: items, paginationState: paginationState)
updateTimelineItemsCancellable = Task { [weak self, activeTimelineProvider] in
let contentSizeChangePublisher = NotificationCenter.default.publisher(for: UIContentSizeCategory.didChangeNotification)
let timelineUpdates = activeTimelineProvider.updatePublisher.merge(with: contentSizeChangePublisher.map { _ in
(activeTimelineProvider.itemProxies, activeTimelineProvider.paginationState)
})
for await (items, paginationState) in timelineUpdates.values {
await self?.updateTimelineItems(itemProxies: items, paginationState: paginationState)
}
}.asCancellable()
}
@objc private func contentSizeCategoryDidChange() {
// Recompute all attributed strings on content size changes -> DynamicType support
serialDispatchQueue.async { [activeTimelineProvider] in
self.updateTimelineItems(itemProxies: activeTimelineProvider.itemProxies, paginationState: activeTimelineProvider.paginationState)
}
}
private func updateTimelineItems(itemProxies: [TimelineItemProxy], paginationState: PaginationState) {
var newTimelineItems = [RoomTimelineItemProtocol]()
private func updateTimelineItems(itemProxies: [TimelineItemProxy], paginationState: PaginationState) async {
let isNewTimeline = isSwitchingTimelines
isSwitchingTimelines = false
let collapsibleChunks = itemProxies.groupBy { isItemCollapsible($0) }
let isDM = roomProxy.isDirectOneToOneRoom
var newTimelineItems = await Task.detached { [timelineItemFactory, activeTimeline] in
var newTimelineItems = [RoomTimelineItemProtocol]()
let collapsibleChunks = itemProxies.groupBy { $0.isItemCollapsible }
for (index, collapsibleChunk) in collapsibleChunks.enumerated() {
let isLastItem = index == collapsibleChunks.indices.last
let items = collapsibleChunk.compactMap { itemProxy in
let timelineItem = buildTimelineItem(for: itemProxy)
let timelineItem = self.buildTimelineItem(for: itemProxy,
isDM: isDM,
timelineItemFactory: timelineItemFactory,
activeTimeline: activeTimeline)
return timelineItem
}
@ -425,6 +427,9 @@ class TimelineController: TimelineControllerProtocol {
}
}
return newTimelineItems
}.value
// Check if we need to add anything to the top of the timeline.
switch paginationState.backward {
case .timelineEndReached:
@ -445,23 +450,26 @@ class TimelineController: TimelineControllerProtocol {
break
}
DispatchQueue.main.sync {
timelineItems = newTimelineItems
}
callbacks.send(.updatedTimelineItems(timelineItems: newTimelineItems, isSwitchingTimelines: isNewTimeline))
self.paginationState = paginationState
}
private func buildTimelineItem(for itemProxy: TimelineItemProxy) -> RoomTimelineItemProtocol? {
private nonisolated func buildTimelineItem(for itemProxy: TimelineItemProxy,
isDM: Bool,
timelineItemFactory: RoomTimelineItemFactoryProtocol,
activeTimeline: TimelineProxyProtocol) -> RoomTimelineItemProtocol? {
switch itemProxy {
case .event(let eventTimelineItem):
let timelineItem = timelineItemFactory.buildTimelineItem(for: eventTimelineItem, isDM: roomProxy.isDirectOneToOneRoom)
let timelineItem = timelineItemFactory.buildTimelineItem(for: eventTimelineItem, isDM: isDM)
if let messageTimelineItem = timelineItem as? EventBasedMessageTimelineItemProtocol {
// Avoid fetching this over and over again as it changes states if it keeps failing to load
// Errors will be handled again on appearance
fetchEventDetails(for: messageTimelineItem, refetchOnError: false)
fetchEventDetails(for: messageTimelineItem,
refetchOnError: false,
activeTimeline: activeTimeline)
}
return timelineItem
@ -478,20 +486,9 @@ class TimelineController: TimelineControllerProtocol {
}
}
private func isItemCollapsible(_ item: TimelineItemProxy) -> Bool {
if case let .event(eventItem) = item {
switch eventItem.content {
case .profileChange, .roomMembership, .state:
return true
default:
return false
}
}
return false
}
private func fetchEventDetails(for timelineItem: EventBasedMessageTimelineItemProtocol, refetchOnError: Bool) {
private nonisolated func fetchEventDetails(for timelineItem: EventBasedMessageTimelineItemProtocol,
refetchOnError: Bool,
activeTimeline: TimelineProxyProtocol) {
guard let eventID = timelineItem.id.eventID else {
return
}
@ -524,3 +521,18 @@ class TimelineController: TimelineControllerProtocol {
return nil
}
}
private extension TimelineItemProxy {
var isItemCollapsible: Bool {
if case let .event(eventItem) = self {
switch eventItem.content {
case .profileChange, .roomMembership, .state:
return true
default:
return false
}
}
return false
}
}

View File

@ -9,7 +9,6 @@ import Foundation
import MatrixRustSDK
@MainActor
protocol RoomTimelineItemFactoryProtocol {
func buildTimelineItem(for eventItemProxy: EventTimelineItemProxy, isDM: Bool) -> RoomTimelineItemProtocol?
func buildReply(details: InReplyToDetails) -> TimelineItemReply

View File

@ -1,17 +1,8 @@
//
// Copyright 2022 New Vector Ltd
// Copyright 2022-2024 New Vector Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
// Please see LICENSE files in the repository root for full details.
//
import XCTest

View File

@ -9,6 +9,7 @@ import XCTest
@testable import ElementX
@MainActor
class ServerConfirmationScreenViewStateTests: XCTestCase {
func testLoginMessageString() {
let matrixDotOrgLogin = ServerConfirmationScreenViewState(homeserverAddress: LoginHomeserver.mockMatrixDotOrg.address,