Compare commits

...
Author SHA1 Message Date
Frank KarlitschekandClaude Opus 5.5 b8d2cd706c test: Add tests for marking as read in the widget and the controls state
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Frank Karlitschek <[email protected]>
2026-10-25 21:36:46 +01:00
Frank KarlitschekandClaude Opus 5.5 2f3c9beae5 feat(widgets): Add Control Center controls and interactive widgets
Control Center, Lock Screen and Action button controls (iOS 18):
- Mute in call: mutes or unmutes the microphone in the ongoing call,
  and shows whether it is muted
- Do not disturb: switches the user status between Do not disturb and
  Online
- New conversation: opens the app to create or join a conversation

Interactive widgets (iOS 17):
- The large conversations widget gets a button to mark a conversation
  as read. The widget shows it as read right away, the real state
  follows once the server answered and the rooms were updated.
- New small Status widget, showing the current status with buttons to
  switch between Online, Away, Do not disturb and Invisible.

The widget extension has no access to the server, so the actions are
LiveActivityIntents, which are performed in the app's process (it is
launched in the background when needed). Their types are compiled into
both targets (TalkWidgetIntents.swift). The app keeps a small state in
the app group, whether there's a call, whether the microphone is muted,
and the user status (TalkControlsState.swift), and reloads the controls
and the status widget when it changes. It is removed on logout.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Frank Karlitschek <[email protected]>
2026-10-25 21:36:46 +01:00
Frank KarlitschekandClaude Opus 5.5 061dab85ff chore: Let Xcode sort the entries of the widget extension in the project file
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Frank Karlitschek <[email protected]>
2026-10-25 21:36:30 +01:00
Frank KarlitschekandClaude Opus 5.5 7442b1c423 feat: Add home and lock screen widgets and Spotlight search
Widgets (new TalkWidgets extension):
- "Conversations" (small, medium, large): favorite conversations, filled
  up with the most recent ones, with avatars, unread and mention badges
  and ongoing calls. Tapping a conversation opens it.
- "Unread conversations" (lock screen): number of conversations with
  unread messages and mentions.

The app writes a small JSON snapshot (and avatars) of the active account
into the app group container whenever the rooms are updated and reloads
the widgets. The widget extension needs no network, database or pods.
Conversation names are marked as privacy sensitive.

Spotlight: the names and descriptions of the conversations of the active
account are indexed, never any messages. Sensitive conversations are not
indexed. Selecting a result opens the conversation. Logged out accounts
are removed from the index and the widgets.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Frank Karlitschek <[email protected]>
2026-10-24 22:35:43 +02:00
Frank KarlitschekandClaude Opus 5.5 9d393a00de feat(call): Adapt video quality to thermal state and Low Power Mode
Encoding and decoding video is what heats up a device the most. While
the device is hot (serious thermal state) or in Low Power Mode, at most
medium quality is used, at a critical thermal state only low quality:

- Received video: the requested simulcast layer is capped.
- Sent video: higher simulcast layers are switched off, a single stream
  is scaled down. Screen shares are not limited.

The user is told once per call why the video quality was reduced.

Also adds a "Microphone mode" entry to the call menu, which opens the
system UI to switch between Standard, Voice Isolation and Wide Spectrum.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Frank Karlitschek <[email protected]>
2026-10-24 22:24:28 +02:00
Frank KarlitschekandClaude Opus 5.5 df3049e171 feat(chat): Double tap to react and confetti for celebrations
- Double tapping a message toggles the most used reaction (👍 by
  default), with a small burst animation. Taps on images, files, polls,
  players, references, quotes and reactions are left alone.
- Messages with 🎉 🥳 🎊 or 🎂 that arrive while the chat is open let
  confetti fall, at most once every 10 seconds.
- Haptic feedback for failed messages and for reacting from the
  context menu.

All animations are skipped when Reduce Motion is enabled.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Frank Karlitschek <[email protected]>
2026-10-24 22:20:01 +02:00
Frank KarlitschekandClaude Opus 5.5 726509188a feat: Add haptic feedback to common actions
Adds a small HapticFeedback helper and uses it when sending a message,
scheduling a message, copying a message or its link, locking a voice
recording, voting in a poll, toggling a favorite, reacting via the emoji
picker and for the main call buttons (mute, video, hang up, raise hand,
call reactions).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Frank Karlitschek <[email protected]>
2026-10-24 22:20:01 +02:00
32 changed files with 2306 additions and 3 deletions

No files matched your search

+1
View File
@@ -14,6 +14,7 @@ on:
- NotificationServiceExtension/**
- ShareExtension/**
- BroadcastUploadExtension/**
- TalkWidgets/**
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
+162
View File
@@ -7,6 +7,7 @@
objects = {
/* Begin PBXBuildFile section */
07F8FEC44AC7B36560C5EE1B /* TalkWidgets.appex in Embed App Extensions */ = {isa = PBXBuildFile; fileRef = A06BE6676DC8072EFA0886DF /* TalkWidgets.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
1F0ECBF52A68274400921E90 /* CDMarkdownKit in Frameworks */ = {isa = PBXBuildFile; productRef = 1F0ECBF42A68274400921E90 /* CDMarkdownKit */; };
1F0ECBF72A68277000921E90 /* CDMarkdownKit in Frameworks */ = {isa = PBXBuildFile; productRef = 1F0ECBF62A68277000921E90 /* CDMarkdownKit */; };
1F0ECBF92A68277C00921E90 /* CDMarkdownKit in Frameworks */ = {isa = PBXBuildFile; productRef = 1F0ECBF82A68277C00921E90 /* CDMarkdownKit */; };
@@ -157,6 +158,7 @@
847EFC7236336B67A1A89358 /* libPods-BroadcastUploadExtension.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 9A3D305FCD7BF7E727A62F35 /* libPods-BroadcastUploadExtension.a */; };
8789AE73BFCAA413B43319C0 /* libPods-ShareExtension.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 684807120F4439797973DF73 /* libPods-ShareExtension.a */; };
9993261EDAC77481FF4EF58A /* libPods-NextcloudTalk.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 4F7C31E9D74F550EAF89931B /* libPods-NextcloudTalk.a */; };
AACE32068D5BE4716C35504B /* Localizable.strings in Resources */ = {isa = PBXBuildFile; fileRef = 2C7F47AC20289B9600081CC7 /* Localizable.strings */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
@@ -202,6 +204,13 @@
remoteGlobalIDString = 2CC0014E24A1F0E900A20167;
remoteInfo = NotificationServiceExtension;
};
B38B10737B74861948D4B46A /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 2C0574751EDD9E8E00D9E7F2 /* Project object */;
proxyType = 1;
remoteGlobalIDString = 404DF6649BF5F70D4316B064;
remoteInfo = TalkWidgets;
};
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
@@ -273,6 +282,7 @@
dstSubfolderSpec = 13;
files = (
2C62AFAE24C08845007E460A /* ShareExtension.appex in Embed App Extensions */,
07F8FEC44AC7B36560C5EE1B /* TalkWidgets.appex in Embed App Extensions */,
2CC0015724A1F0E900A20167 /* NotificationServiceExtension.appex in Embed App Extensions */,
1FF2FD722AB99CCB000C9905 /* BroadcastUploadExtension.appex in Embed App Extensions */,
);
@@ -454,6 +464,7 @@
95D756208A81284B975853EC /* Pods-ShareExtension.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-ShareExtension.release.xcconfig"; path = "Pods/Target Support Files/Pods-ShareExtension/Pods-ShareExtension.release.xcconfig"; sourceTree = "<group>"; };
9A3D305FCD7BF7E727A62F35 /* libPods-BroadcastUploadExtension.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-BroadcastUploadExtension.a"; sourceTree = BUILT_PRODUCTS_DIR; };
9B81BB7A4920C391CC2CACFD /* libPods-NotificationServiceExtension.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-NotificationServiceExtension.a"; sourceTree = BUILT_PRODUCTS_DIR; };
A06BE6676DC8072EFA0886DF /* TalkWidgets.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = TalkWidgets.appex; sourceTree = BUILT_PRODUCTS_DIR; };
A8F95DE6635ABC1E64CA8E4A /* Pods-BroadcastUploadExtension.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-BroadcastUploadExtension.release.xcconfig"; path = "Pods/Target Support Files/Pods-BroadcastUploadExtension/Pods-BroadcastUploadExtension.release.xcconfig"; sourceTree = "<group>"; };
B7874918820589BF8FD69BED /* Pods-NextcloudTalkTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-NextcloudTalkTests.release.xcconfig"; path = "Pods/Target Support Files/Pods-NextcloudTalkTests/Pods-NextcloudTalkTests.release.xcconfig"; sourceTree = "<group>"; };
D6DF51D976DC0F681FF83F7B /* Pods-NotificationServiceExtension.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-NotificationServiceExtension.debug.xcconfig"; path = "Pods/Target Support Files/Pods-NotificationServiceExtension/Pods-NotificationServiceExtension.debug.xcconfig"; sourceTree = "<group>"; };
@@ -975,6 +986,22 @@
);
target = 2C05747C1EDD9E8E00D9E7F2 /* NextcloudTalk */;
};
8B65C957AD2D5B226E3E451F /* Exceptions for "TalkWidgets" folder in "NextcloudTalk" target */ = {
isa = PBXFileSystemSynchronizedBuildFileExceptionSet;
membershipExceptions = (
ConversationsWidgetData.swift,
TalkControlsState.swift,
TalkWidgetIntents.swift,
);
target = 2C05747C1EDD9E8E00D9E7F2 /* NextcloudTalk */;
};
AF55F227961AC70B32D0CA6E /* Exceptions for "TalkWidgets" folder in "TalkWidgets" target */ = {
isa = PBXFileSystemSynchronizedBuildFileExceptionSet;
membershipExceptions = (
Info.plist,
);
target = 404DF6649BF5F70D4316B064 /* TalkWidgets */;
};
/* End PBXFileSystemSynchronizedBuildFileExceptionSet section */
/* Begin PBXFileSystemSynchronizedRootGroup section */
@@ -1172,6 +1199,15 @@
path = TalkIntents;
sourceTree = "<group>";
};
276FE3D714359BBDDFCFD105 /* TalkWidgets */ = {
isa = PBXFileSystemSynchronizedRootGroup;
exceptions = (
8B65C957AD2D5B226E3E451F /* Exceptions for "TalkWidgets" folder in "NextcloudTalk" target */,
AF55F227961AC70B32D0CA6E /* Exceptions for "TalkWidgets" folder in "TalkWidgets" target */,
);
path = TalkWidgets;
sourceTree = "<group>";
};
/* End PBXFileSystemSynchronizedRootGroup section */
/* Begin PBXFrameworksBuildPhase section */
@@ -1309,6 +1345,13 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
C8BF89396AF80593D0F773E3 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
@@ -1320,6 +1363,7 @@
1F2058A32CEBE4EA00AAA673 /* BroadcastUploadExtension */,
1F8977F52DB0F76100E8114D /* NextcloudTalkTests */,
1FA93D9D2D70FCC200DF6CDF /* TalkIntents */,
276FE3D714359BBDDFCFD105 /* TalkWidgets */,
2C05747E1EDD9E8E00D9E7F2 /* Products */,
2C05749C1EDDA01700D9E7F2 /* ThirdParty */,
2C05747F1EDD9E8E00D9E7F2 /* NextcloudTalk */,
@@ -1339,6 +1383,7 @@
1FF2FD5B2AB99CCB000C9905 /* BroadcastUploadExtension.appex */,
1F6D8C302B2E3756004376B8 /* NextcloudTalkTests.xctest */,
1FA93D9C2D70FCC200DF6CDF /* TalkIntents.appex */,
A06BE6676DC8072EFA0886DF /* TalkWidgets.appex */,
);
name = Products;
sourceTree = "<group>";
@@ -1664,6 +1709,7 @@
2C62AFAD24C08845007E460A /* PBXTargetDependency */,
1FF2FD712AB99CCB000C9905 /* PBXTargetDependency */,
1FA93DA42D70FCC200DF6CDF /* PBXTargetDependency */,
F9B0708653706C7E88EE41B0 /* PBXTargetDependency */,
);
fileSystemSynchronizedGroups = (
1F2058832CEBE4E700AAA673 /* ShareExtension */,
@@ -1793,6 +1839,28 @@
productReference = 2CC0014F24A1F0E900A20167 /* NotificationServiceExtension.appex */;
productType = "com.apple.product-type.app-extension";
};
404DF6649BF5F70D4316B064 /* TalkWidgets */ = {
isa = PBXNativeTarget;
buildConfigurationList = 9ABE05A230C005038CB734E7 /* Build configuration list for PBXNativeTarget "TalkWidgets" */;
buildPhases = (
7B48D333E0BB9346485C467C /* Sources */,
C8BF89396AF80593D0F773E3 /* Frameworks */,
E8B6BD717E91928AEB804805 /* Resources */,
);
buildRules = (
);
dependencies = (
);
fileSystemSynchronizedGroups = (
276FE3D714359BBDDFCFD105 /* TalkWidgets */,
);
name = TalkWidgets;
packageProductDependencies = (
);
productName = TalkWidgets;
productReference = A06BE6676DC8072EFA0886DF /* TalkWidgets.appex */;
productType = "com.apple.product-type.app-extension";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
@@ -1847,6 +1915,9 @@
LastSwiftMigration = 1220;
ProvisioningStyle = Automatic;
};
404DF6649BF5F70D4316B064 = {
CreatedOnToolsVersion = 27.1;
};
};
};
buildConfigurationList = 2C0574781EDD9E8E00D9E7F2 /* Build configuration list for PBXProject "NextcloudTalk" */;
@@ -1921,6 +1992,7 @@
1FD8AD892A3A162100787C16 /* NextcloudTalkUITests */,
1F6D8C2F2B2E3756004376B8 /* NextcloudTalkTests */,
1FA93D9B2D70FCC200DF6CDF /* TalkIntents */,
404DF6649BF5F70D4316B064 /* TalkWidgets */,
);
};
/* End PBXProject section */
@@ -1997,6 +2069,14 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
E8B6BD717E91928AEB804805 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
AACE32068D5BE4716C35504B /* Localizable.strings in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
@@ -2291,6 +2371,13 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
7B48D333E0BB9346485C467C /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
@@ -2324,6 +2411,11 @@
target = 2CC0014E24A1F0E900A20167 /* NotificationServiceExtension */;
targetProxy = 2CC0015524A1F0E900A20167 /* PBXContainerItemProxy */;
};
F9B0708653706C7E88EE41B0 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 404DF6649BF5F70D4316B064 /* TalkWidgets */;
targetProxy = B38B10737B74861948D4B46A /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin PBXVariantGroup section */
@@ -3288,6 +3380,67 @@
};
name = Release;
};
90C606693565B566AE1CBA39 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
APPLICATION_EXTENSION_API_ONLY = YES;
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_ENTITLEMENTS = TalkWidgets/TalkWidgets.entitlements;
CODE_SIGN_IDENTITY = "iPhone Developer";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = NKUJUXUJ3B;
GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = TalkWidgets/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 16.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
MARKETING_VERSION = 25.0.2;
PRODUCT_BUNDLE_IDENTIFIER = com.nextcloud.Talk.TalkWidgets;
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = APP_EXTENSION;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
};
9F99C4F4C1B607E85292FA51 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
APPLICATION_EXTENSION_API_ONLY = YES;
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_ENTITLEMENTS = TalkWidgets/TalkWidgets.entitlements;
CODE_SIGN_IDENTITY = "iPhone Distribution: Nextcloud GmbH (NKUJUXUJ3B)";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = NKUJUXUJ3B;
GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = TalkWidgets/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 16.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
MARKETING_VERSION = 25.0.2;
PRODUCT_BUNDLE_IDENTIFIER = com.nextcloud.Talk.TalkWidgets;
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = APP_EXTENSION;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
@@ -3363,6 +3516,15 @@
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
9ABE05A230C005038CB734E7 /* Build configuration list for PBXNativeTarget "TalkWidgets" */ = {
isa = XCConfigurationList;
buildConfigurations = (
90C606693565B566AE1CBA39 /* Debug */,
9F99C4F4C1B607E85292FA51 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
/* Begin XCRemoteSwiftPackageReference section */
+10
View File
@@ -75,6 +75,10 @@ class AppDelegate: UIResponder, UIApplicationDelegate, PKPushRegistryDelegate {
// Init rooms manager to start receiving NSNotificationCenter notifications
_ = NCRoomsManager.shared
// Keep the widgets and the system search up to date with the conversations
ConversationsWidgetController.shared.start()
ConversationsSpotlightIndexer.shared.start()
self.registerBackgroundFetchTask()
self.registerBackgroundProcessingTask()
@@ -95,6 +99,12 @@ class AppDelegate: UIResponder, UIApplicationDelegate, PKPushRegistryDelegate {
}
func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
// A conversation was selected in the system search (Spotlight)
if let conversationURL = ConversationsSpotlightIndexer.conversationURL(for: userActivity) {
NCUserInterfaceController.sharedInstance().presentChatForURL(conversationURL)
return true
}
let intent = userActivity.interaction?.intent
let audioCallIntent = intent is INStartAudioCallIntent
let videoCallIntent = intent is INStartVideoCallIntent
@@ -0,0 +1,67 @@
//
// SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
// SPDX-License-Identifier: GPL-3.0-or-later
//
import Foundation
// Watches the thermal state and Low Power Mode during a call. Encoding and decoding video is
// what heats up the device the most, so while it is hot or should save power, less video is used.
class CallPerformanceMonitor {
enum Reason {
case none
case thermalState
case lowPowerMode
}
private(set) var maxVideoQuality: SimulcastVideoQuality = .high
private(set) var reason: Reason = .none
// Called on the main thread, whenever the maximum video quality changed
var onChange: ((_ maxVideoQuality: SimulcastVideoQuality, _ reason: Reason) -> Void)?
private let processInfo: ProcessInfo
init(processInfo: ProcessInfo = .processInfo) {
self.processInfo = processInfo
self.update(notify: false)
NotificationCenter.default.addObserver(self, selector: #selector(stateDidChange), name: ProcessInfo.thermalStateDidChangeNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(stateDidChange), name: .NSProcessInfoPowerStateDidChange, object: nil)
}
static func maxVideoQuality(thermalState: ProcessInfo.ThermalState, isLowPowerModeEnabled: Bool) -> (quality: SimulcastVideoQuality, reason: Reason) {
switch thermalState {
case .critical:
return (.low, .thermalState)
case .serious:
return (.medium, .thermalState)
default:
return isLowPowerModeEnabled ? (.medium, .lowPowerMode) : (.high, .none)
}
}
@objc private func stateDidChange() {
// The notifications are posted on an arbitrary thread
DispatchQueue.main.async {
self.update(notify: true)
}
}
private func update(notify: Bool) {
let (quality, reason) = Self.maxVideoQuality(thermalState: processInfo.thermalState, isLowPowerModeEnabled: processInfo.isLowPowerModeEnabled)
guard quality != self.maxVideoQuality || reason != self.reason else { return }
NCLog.log("Call video quality limited to \(quality) (thermal state: \(processInfo.thermalState.rawValue), low power mode: \(processInfo.isLowPowerModeEnabled))")
self.maxVideoQuality = quality
self.reason = reason
if notify {
self.onChange?(quality, reason)
}
}
}
+87 -3
View File
@@ -157,6 +157,8 @@ class CallViewController: UIViewController,
private var showChatAfterRoomSwitch = false
private var connectingSoundAlreadyPlayed = false
private var buttonFeedbackGenerator = UIImpactFeedbackGenerator(style: .light)
private let performanceMonitor = CallPerformanceMonitor()
private var hasShownReducedVideoQualityNotice = false
private var localVideoDragStartingPoint: CGPoint?
private var airplayView = AVRoutePickerView(frame: .init(x: 0, y: 0, width: 48, height: 32))
private var pendingPeerInserts: [NCPeerConnection] = []
@@ -206,6 +208,8 @@ class CallViewController: UIViewController,
let callController = NCCallController(delegate: self, room: self.room, account: self.account, isAudioOnly: self.isAudioOnly, userSessionId: sessionId, voiceChatMode: self.voiceChatModeAtStart)
self.callController = callController
callController.setMaxSendVideoQuality(self.performanceMonitor.maxVideoQuality)
callController.disableAudioAtStart = self.audioDisabledAtStart
callController.disableVideoAtStart = self.videoDisabledAtStart
callController.silentCall = self.silentCall
@@ -227,6 +231,10 @@ class CallViewController: UIViewController,
self.setCallState(.joining)
self.performanceMonitor.onChange = { [weak self] maxVideoQuality, reason in
self?.performanceLimitsDidChange(maxVideoQuality: maxVideoQuality, reason: reason)
}
self.tapGestureForDetailedView = UITapGestureRecognizer(target: self, action: #selector(showDetailedViewWithTimer))
self.tapGestureForDetailedView?.numberOfTapsRequired = 1
@@ -870,12 +878,38 @@ class CallViewController: UIViewController,
return .low
}
var quality: SimulcastVideoQuality
if callViewMode == .speaker {
return peer.peerIdentifier == promotedPeerIdentifier ? .high : .low
quality = peer.peerIdentifier == promotedPeerIdentifier ? .high : .low
} else {
// Unlike web, a single participant is shown fullscreen in the grid
quality = peersInCall.count == 1 ? .high : .medium
}
// Unlike web, a single participant is shown fullscreen in the grid
return peersInCall.count == 1 ? .high : .medium
// Decoding less video keeps the device cooler
let maxVideoQuality = performanceMonitor.maxVideoQuality
return quality.rawValue > maxVideoQuality.rawValue ? maxVideoQuality : quality
}
private func performanceLimitsDidChange(maxVideoQuality: SimulcastVideoQuality, reason: CallPerformanceMonitor.Reason) {
self.callController?.setMaxSendVideoQuality(maxVideoQuality)
self.updateSimulcastVideoQualities()
// Let the user know once per call, why the video looks worse than before
guard maxVideoQuality != .high, !self.isAudioOnly, !self.hasShownReducedVideoQualityNotice else { return }
self.hasShownReducedVideoQualityNotice = true
let notificationText = switch reason {
case .lowPowerMode:
NSLocalizedString("Video quality was reduced to save battery", comment: "Shown in a call when Low Power Mode is enabled")
default:
NSLocalizedString("Video quality was reduced to cool down your device", comment: "Shown in a call when the device gets hot")
}
NotificationPresenter.shared().present(text: notificationText, dismissAfterDelay: 5.0, includedStyle: .dark)
}
private func updateSimulcastVideoQualities() {
@@ -2001,6 +2035,26 @@ class CallViewController: UIViewController,
}
self.audioMuteButton.accessibilityValue = micStatusString
// Control Center shows whether we're muted
TalkWidgetActions.callDidChange(isInCall: !self.hangingUp, isMicrophoneMuted: !isActive)
}
}
// The microphone was muted or unmuted with the control in Control Center
func setMicrophoneMutedFromControl(_ muted: Bool) {
guard let callController else { return }
callController.getAudioEnabledState { isEnabled in
guard isEnabled == muted else { return }
if CallKitManager.isCallKitAvailable() {
DispatchQueue.main.async {
CallKitManager.sharedInstance().changeAudioMuted(muted, forCall: self.room.token)
}
} else {
self.setAudioMuted(muted)
}
}
}
@@ -2141,6 +2195,7 @@ class CallViewController: UIViewController,
for reaction in callReactions {
reactionItems.append(UIAction(title: String(reaction), handler: { [unowned self] _ in
HapticFeedback.light()
self.callController?.sendReaction(reaction)
if let account = room.account {
@@ -2264,6 +2319,7 @@ class CallViewController: UIViewController,
}
items.append(UIAction(title: raiseHandTitle, image: .init(systemName: "hand.raised.fill"), handler: { [unowned self] _ in
HapticFeedback.light()
callController.raiseHand(!self.isHandRaised)
self.isHandRaised = !self.isHandRaised
self.adjustBars()
@@ -2313,6 +2369,14 @@ class CallViewController: UIViewController,
}))
}
// The microphone mode (Standard, Voice Isolation, Wide Spectrum) can only be changed in the system UI
let microphoneModeTitle = String(format: NSLocalizedString("Microphone mode: %@", comment: "Microphone mode: Voice Isolation"),
self.microphoneModeName(AVCaptureDevice.activeMicrophoneMode))
items.append(UIAction(title: microphoneModeTitle, image: .init(systemName: "waveform.and.mic"), handler: { _ in
AVCaptureDevice.showSystemUserInterface(.microphoneModes)
}))
if NCUtils.isTestEnvironment {
items.append(self.getDebugMenu())
}
@@ -2320,6 +2384,17 @@ class CallViewController: UIViewController,
return items
}
private func microphoneModeName(_ microphoneMode: AVCaptureDevice.MicrophoneMode) -> String {
switch microphoneMode {
case .voiceIsolation:
return NSLocalizedString("Voice Isolation", comment: "Microphone mode that filters out background noise")
case .wideSpectrum:
return NSLocalizedString("Wide Spectrum", comment: "Microphone mode that picks up all sounds around")
default:
return NSLocalizedString("Standard", comment: "Default microphone mode")
}
}
func adjustSpeakerButton() {
DispatchQueue.main.async {
guard self.speakerButton != nil else { return }
@@ -2496,6 +2571,8 @@ class CallViewController: UIViewController,
@IBAction func audioButtonPressed(_ sender: Any) {
guard let callController else { return }
HapticFeedback.light()
callController.getAudioEnabledState { isEnabled in
if CallKitManager.isCallKitAvailable() {
DispatchQueue.main.async {
@@ -2583,6 +2660,8 @@ class CallViewController: UIViewController,
@IBAction func videoButtonPressed(_ sender: Any) {
guard let callController else { return }
HapticFeedback.light()
callController.getVideoEnabledState { isEnabled in
self.setLocalVideoEnabled(!isEnabled)
self.userDisabledVideo = isEnabled
@@ -2682,6 +2761,7 @@ class CallViewController: UIViewController,
}
@IBAction func hangupButtonPressed(_ sender: Any) {
HapticFeedback.medium()
self.hangup(forAll: (room.type == .oneToOne))
}
@@ -3031,6 +3111,10 @@ class CallViewController: UIViewController,
func finishCall() {
callController = nil
DispatchQueue.main.async {
TalkWidgetActions.callDidChange(isInCall: false, isMicrophoneMuted: false)
}
DispatchQueue.main.async {
self.stopPictureInPicture()
}
@@ -107,6 +107,8 @@ internal class NCCallController: NSObject, NCPeerConnectionDelegate, NCSignaling
private var connectionsDict = [PeerKey: NCPeerConnection]()
private var pendingOffersDict = [PeerKey: Timer]()
private var simulcastVideoQualities = [SessionId: SimulcastVideoQuality]()
// Lowered while the device is hot or in Low Power Mode, see CallPerformanceMonitor
private var maxSendVideoQuality: SimulcastVideoQuality = .high
private var remoteVideoBlocked = [SessionId: Bool]()
private var sessionsInCall = [String]()
@@ -1127,6 +1129,7 @@ internal class NCCallController: NSObject, NCPeerConnectionDelegate, NCSignaling
peerConnectionWrapper?.delegate = self
peerConnectionWrapper?.isOwnScreensharePeer = ownScreenshare
peerConnectionWrapper?.preferredVideoCodec = self.preferredVideoCodec
peerConnectionWrapper?.maxSendVideoQuality = self.maxSendVideoQuality
peerConnectionWrapper?.receiverKeyRing = self.callEncryption?.keyRing(forSessionId: sessionId)
// Try to get displayName early
@@ -1214,6 +1217,19 @@ internal class NCCallController: NSObject, NCPeerConnectionDelegate, NCSignaling
}
}
func setMaxSendVideoQuality(_ quality: SimulcastVideoQuality) {
WebRTCCommon.shared.dispatch {
guard quality != self.maxSendVideoQuality else { return }
self.maxSendVideoQuality = quality
for (_, peerConnectionWrapper) in self.connectionsDict {
peerConnectionWrapper.maxSendVideoQuality = quality
peerConnectionWrapper.applyMaxSendVideoQuality()
}
}
}
// Blocking the video in the MCU while it is not shown saves bandwidth, same as web
func setRemoteVideoBlocked(_ blocked: Bool, forPeerId peerId: String) {
WebRTCCommon.shared.dispatch {
@@ -1319,6 +1335,7 @@ internal class NCCallController: NSObject, NCPeerConnectionDelegate, NCSignaling
peerConnectionWrapper.roomType = kRoomTypeVideo
peerConnectionWrapper.delegate = self
peerConnectionWrapper.preferredVideoCodec = self.preferredVideoCodec
peerConnectionWrapper.maxSendVideoQuality = self.maxSendVideoQuality
self.publisherPeerConnection = peerConnectionWrapper
@@ -825,12 +825,14 @@ import Toast
try await NCAPIController.sharedInstance().scheduleMessage(temporaryMessage.sendingMessage, inRoom: self.room.token, sendAt: timestamp, replyTo: replyToMessage?.messageId, silent: silently, threadId: self.thread?.threadId, forAccount: self.account)
NotificationPresenter.shared().present(text: NSLocalizedString("Message successfully scheduled", comment: ""), dismissAfterDelay: 5.0, includedStyle: .success)
HapticFeedback.success()
self.clearInputAfterSend()
NCRoomsManager.shared.updateRoom(self.room.token, forAccount: self.account)
} catch {
print(error)
NotificationPresenter.shared().present(text: NSLocalizedString("Message scheduling failed", comment: ""), dismissAfterDelay: 5.0, includedStyle: .error)
HapticFeedback.error()
}
}
}
@@ -862,6 +864,7 @@ import Toast
switch button.tag {
case sendButtonTagMessage:
HapticFeedback.light()
self.sendCurrentMessage(silently: false)
super.didPressRightButton(sender)
case sendButtonTagVoice:
@@ -1433,6 +1436,7 @@ import Toast
let pasteboard = UIPasteboard.general
pasteboard.string = message.parsedMessage().string
NotificationPresenter.shared().present(text: NSLocalizedString("Message copied", comment: ""), dismissAfterDelay: 5.0, includedStyle: .dark)
HapticFeedback.success()
}
func didPressCopyLink(for message: NCChatMessage) {
@@ -1445,6 +1449,7 @@ import Toast
pasteboard.string = url
NotificationPresenter.shared().present(text: NSLocalizedString("Message link copied", comment: ""), dismissAfterDelay: 5.0, includedStyle: .dark)
HapticFeedback.success()
}
func didPressCopySelection(for message: NCChatMessage) {
@@ -1634,6 +1639,7 @@ import Toast
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == self.emojiTextField, string.isSingleEmoji, let interactingMessage = self.interactingMessage {
HapticFeedback.light()
self.addReaction(reaction: string, to: interactingMessage)
textField.resignFirstResponder()
}
@@ -2612,6 +2618,7 @@ import Toast
let intOffset = Int(offset!.magnitude)
showExpandedVoiceMessageRecordingView(offset: intOffset)
print("LOCKED")
HapticFeedback.rigid()
isVoiceRecordingLocked = true
}
}
@@ -145,6 +145,9 @@ import UIKit
if let responsePoll = responsePoll, error == nil {
self.poll = responsePoll
self.editingVote = false
HapticFeedback.success()
} else {
HapticFeedback.error()
}
self.setupPollView()
}
+107
View File
@@ -35,6 +35,9 @@ import SwiftUI
private var isLeavingChat = false
private var chatViewPresentedTimestamp = Date().timeIntervalSince1970
private var doubleTapReactionGesture: UITapGestureRecognizer?
private var lastCelebrationTimestamp: TimeInterval = 0
private var generateSummaryFromMessageId: Int?
private var generateSummaryTimer: Timer?
@@ -631,6 +634,8 @@ import SwiftUI
// Disable room info, input bar and call buttons until joining room
self.disableRoomControls()
self.addDoubleTapReactionGesture()
}
public override func viewWillAppear(_ animated: Bool) {
@@ -1782,6 +1787,8 @@ import SwiftUI
if firstNewMessagesAfterHistory {
self.chatBackgroundView.loadingView.stopAnimating()
self.chatBackgroundView.loadingView.isHidden = true
} else {
self.celebrateIfNeeded(forReceivedMessages: messages)
}
if self.highlightMessageId > 0, let indexPath = self.indexPathAndMessage(forMessageId: self.highlightMessageId)?.indexPath {
@@ -1925,6 +1932,11 @@ import SwiftUI
message.isOfflineMessage = isOfflineMessage
}
// Offline messages are sent later automatically, only a real failure needs the user's attention
if !isOfflineMessage {
HapticFeedback.error()
}
} else {
// No referenceId -> show generic error
self.textView.text = message
@@ -2293,6 +2305,99 @@ import SwiftUI
super.didCommitTextEditing(sender)
}
// MARK: - Double tap to react
private func addDoubleTapReactionGesture() {
guard let tableView = self.tableView else { return }
let doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTapReaction(_:)))
doubleTapGesture.numberOfTapsRequired = 2
doubleTapGesture.delegate = self
tableView.addGestureRecognizer(doubleTapGesture)
self.doubleTapReactionGesture = doubleTapGesture
}
// The reaction a double tap adds: the one used most, which is 👍 until the user reacted a few times
private var doubleTapReaction: String {
return self.account.frequentlyUsedEmojis.first ?? "👍"
}
func handleDoubleTapReaction(_ gestureRecognizer: UITapGestureRecognizer) {
guard gestureRecognizer.state == .ended, let tableView = self.tableView else { return }
let location = gestureRecognizer.location(in: tableView)
guard let indexPath = tableView.indexPathForRow(at: location),
let message = self.message(for: indexPath),
!message.isSystemMessage, !message.isDeleting,
self.room.canReact, self.isMessageReactable(message: message)
else { return }
let emoji = self.doubleTapReaction
let reaction = message.reactionsArray().first(where: { $0.reaction == emoji }) ?? NCChatReaction(reaction: emoji)
// Like the reactions below a message, a double tap toggles the reaction
if !reaction.userReacted {
ChatEffects.showReactionBurst(emoji, at: gestureRecognizer.location(in: self.view), in: self.view)
}
HapticFeedback.light()
self.addOrRemoveReaction(reaction: reaction, in: message)
}
private func isInteractiveMessageContent(_ view: UIView?) -> Bool {
var currentView = view
// Images, files, polls, players and so on have their own taps, a double tap there should not add a reaction
while let checkedView = currentView, !(checkedView is UITableViewCell) {
if checkedView is UIControl || checkedView is UIImageView || checkedView is ReactionsView ||
checkedView is AudioPlayerView || checkedView is PollMessageView || checkedView is ReferenceView ||
checkedView is GroupedFilePreviewView || checkedView is QuotedMessageView {
return true
}
currentView = checkedView.superview
}
return false
}
public override func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if gestureRecognizer == self.doubleTapReactionGesture {
return !self.isInteractiveMessageContent(touch.view)
}
return true
}
public override func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
// A double tap on the message text would otherwise select a word instead of adding the reaction
if gestureRecognizer == self.doubleTapReactionGesture, otherGestureRecognizer.view is UITextView,
let otherTapGesture = otherGestureRecognizer as? UITapGestureRecognizer, otherTapGesture.numberOfTapsRequired >= 2 {
return true
}
return false
}
// MARK: - Celebration
private func celebrateIfNeeded(forReceivedMessages messages: [NCChatMessage]) {
// Only for messages that were written while the chat is open, not for the history
let hasNewCelebration = messages.contains { message in
!message.isSystemMessage && message.timestamp >= Int(self.chatViewPresentedTimestamp) &&
ChatEffects.isCelebration(message.message)
}
// Several celebrating messages right after each other only need one round of confetti
let now = Date().timeIntervalSince1970
guard hasNewCelebration, now - self.lastCelebrationTimestamp > 10 else { return }
self.lastCelebrationTimestamp = now
ChatEffects.showConfetti(in: self.view)
}
// MARK: - ChatMessageTableViewCellDelegate delegate
override public func cellDidSelectedReaction(_ reaction: NCChatReaction!, for message: NCChatMessage) {
@@ -2550,6 +2655,8 @@ import SwiftUI
let emojiAction = UIAction(title: emoji, image: self.getEmojiImage(for: emoji)) { [weak self] _ in
guard let self else { return }
HapticFeedback.light()
// Wait for the menu to be dismissed, otherwise the message is reloaded while the menu animates
self.contextMenuActionBlock = {
self.addOrRemoveReaction(reaction: reaction, in: message)
@@ -0,0 +1,111 @@
//
// SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
// SPDX-License-Identifier: GPL-3.0-or-later
//
import CoreSpotlight
import UniformTypeIdentifiers
// Makes the conversations findable in the system search (Spotlight).
// Only the names and descriptions are indexed, never any messages. Sensitive conversations are not indexed at all.
class ConversationsSpotlightIndexer {
public static let shared = ConversationsSpotlightIndexer()
private let indexedAccountIdsKey = "spotlightIndexedAccountIds"
// What was indexed last per account, to not index the same conversations again on every rooms update
private var indexedSignatures = [String: String]()
func start() {
NotificationCenter.default.addObserver(self, selector: #selector(setNeedsUpdate), name: .NCRoomsManagerDidUpdateRooms, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(setNeedsUpdate), name: .NCSettingsControllerDidChangeActiveAccount, object: nil)
self.setNeedsUpdate()
}
@objc func setNeedsUpdate() {
DispatchQueue.main.async {
self.update()
}
}
private func update() {
guard CSSearchableIndex.isIndexingAvailable() else { return }
let index = CSSearchableIndex.default()
let accounts = NCDatabaseManager.sharedInstance().allAccounts()
// Remove the conversations of accounts that were logged out
let accountIds = Set(accounts.map(\.accountId))
let removedAccountIds = self.indexedAccountIds.subtracting(accountIds)
if !removedAccountIds.isEmpty {
index.deleteSearchableItems(withDomainIdentifiers: Array(removedAccountIds))
removedAccountIds.forEach { self.indexedSignatures.removeValue(forKey: $0) }
}
self.indexedAccountIds = self.indexedAccountIds.intersection(accountIds)
guard !accounts.isEmpty else { return }
// Rooms are only updated for the active account
let account = NCDatabaseManager.sharedInstance().activeAccount()
let rooms = NCDatabaseManager.sharedInstance().roomsForAccountId(account.accountId, withRealm: nil)
.filter { !$0.isSensitive }
.sorted { $0.internalId < $1.internalId }
let signature = rooms.map { "\($0.internalId)\u{1F}\($0.displayName ?? "")\u{1F}\($0.roomDescription ?? "")" }.joined(separator: "\u{1E}")
guard indexedSignatures[account.accountId] != signature else { return }
let showAccountName = accounts.count > 1
let items = rooms.map { room in
let attributes = CSSearchableItemAttributeSet(contentType: .content)
attributes.title = room.displayName
attributes.contentDescription = showAccountName ? account.userDisplayName : room.roomDescription
attributes.keywords = ["Talk"]
return CSSearchableItem(uniqueIdentifier: room.internalId, domainIdentifier: account.accountId, attributeSet: attributes)
}
// Replace all conversations of the account, so removed conversations are removed from the index as well
index.deleteSearchableItems(withDomainIdentifiers: [account.accountId]) { _ in
index.indexSearchableItems(items) { error in
if let error {
NCLog.log("Could not index conversations in Spotlight: \(error.localizedDescription)")
}
}
}
indexedSignatures[account.accountId] = signature
self.indexedAccountIds.insert(account.accountId)
}
private var indexedAccountIds: Set<String> {
get { Set(UserDefaults.standard.stringArray(forKey: indexedAccountIdsKey) ?? []) }
set { UserDefaults.standard.set(Array(newValue), forKey: indexedAccountIdsKey) }
}
// MARK: - Opening a search result
static func conversationURL(for userActivity: NSUserActivity) -> NSURLComponents? {
guard userActivity.activityType == CSSearchableItemActionType,
let internalId = userActivity.userInfo?[CSSearchableItemActivityIdentifier] as? String,
let room = NCDatabaseManager.sharedInstance().room(withInternalId: internalId),
let account = room.account
else { return nil }
let urlComponents = NSURLComponents()
urlComponents.scheme = "nextcloudtalk"
urlComponents.host = "open-conversation"
urlComponents.queryItems = [
URLQueryItem(name: "server", value: account.server),
URLQueryItem(name: "user", value: account.userId),
URLQueryItem(name: "withRoomToken", value: room.token)
]
return urlComponents
}
}
@@ -0,0 +1,174 @@
//
// SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
// SPDX-License-Identifier: GPL-3.0-or-later
//
import UIKit
import WidgetKit
// Keeps the data of the home and lock screen widgets up to date, see ConversationsWidgetData
class ConversationsWidgetController {
public static let shared = ConversationsWidgetController()
// Enough for the large widget, the smaller ones show less
private let maxConversations = 6
private let avatarSize = CGSize(width: 88, height: 88)
private var lastSavedData: ConversationsWidgetData?
private var pendingUpdate: DispatchWorkItem?
private var avatarsBeingLoaded = Set<String>()
func start() {
NotificationCenter.default.addObserver(self, selector: #selector(setNeedsUpdate), name: .NCRoomsManagerDidUpdateRooms, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(setNeedsUpdate), name: .NCSettingsControllerDidChangeActiveAccount, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(activeAccountDidChange), name: .NCSettingsControllerDidChangeActiveAccount, object: nil)
self.setNeedsUpdate()
}
// The status of the new account is only known once it was loaded again
@objc private func activeAccountDidChange() {
DispatchQueue.main.async {
TalkWidgetActions.userStatusDidChange(nil)
}
}
// Rooms are often updated several times in a row, so the update is slightly delayed to only do it once
@objc func setNeedsUpdate() {
DispatchQueue.main.async {
self.pendingUpdate?.cancel()
let update = DispatchWorkItem {
self.update()
}
self.pendingUpdate = update
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: update)
}
}
private func update() {
guard NCDatabaseManager.sharedInstance().numberOfAccounts() > 0 else {
self.removeData()
return
}
let account = NCDatabaseManager.sharedInstance().activeAccount()
let rooms = NCDatabaseManager.sharedInstance().roomsForAccountId(account.accountId, withRealm: nil).filter { !$0.isArchived }
// Favorites first, the remaining space is filled with the most recent conversations
let byLastActivity: (NCRoom, NCRoom) -> Bool = { $0.lastActivity > $1.lastActivity }
let favoriteRooms = rooms.filter(\.isFavorite).sorted(by: byLastActivity)
let otherRooms = rooms.filter { !$0.isFavorite }.sorted(by: byLastActivity)
let shownRooms = Array((favoriteRooms + otherRooms).prefix(maxConversations))
let avatarsDirectoryURL = ConversationsWidgetData.avatarsDirectoryURL(appGroupIdentifier: groupIdentifier)
let conversations = shownRooms.map { room in
let avatarFileName = self.avatarFileName(for: room)
let avatarExists = avatarsDirectoryURL.map { FileManager.default.fileExists(atPath: $0.appendingPathComponent(avatarFileName).path) } ?? false
return ConversationsWidgetData.Conversation(id: room.internalId,
token: room.token,
displayName: room.displayName,
unreadMessages: room.unreadMessages,
unreadMention: room.unreadMention,
isFavorite: room.isFavorite,
hasCall: room.hasCall,
avatarFileName: avatarExists ? avatarFileName : nil)
}
let data = ConversationsWidgetData(server: account.server,
userId: account.userId,
conversations: conversations,
unreadConversations: rooms.filter { $0.unreadMessages > 0 }.count,
unreadMentions: rooms.filter(\.unreadMention).count)
self.removeUnusedAvatars(keeping: Set(shownRooms.map { self.avatarFileName(for: $0) }))
self.loadMissingAvatars(for: shownRooms)
guard data != lastSavedData else { return }
do {
try data.save(appGroupIdentifier: groupIdentifier)
self.lastSavedData = data
WidgetCenter.shared.reloadAllTimelines()
} catch {
NCLog.log("Could not save widget data: \(error.localizedDescription)")
}
}
private func removeData() {
guard lastSavedData != nil || ConversationsWidgetData.load(appGroupIdentifier: groupIdentifier) != nil else { return }
ConversationsWidgetData.remove(appGroupIdentifier: groupIdentifier)
self.lastSavedData = nil
WidgetCenter.shared.reloadAllTimelines()
DispatchQueue.main.async {
TalkWidgetActions.accountsDidChange()
}
}
// MARK: - Avatars
private func avatarFileName(for room: NCRoom) -> String {
// The version changes with the avatar, so a changed avatar is stored as a new file
let name = "\(room.internalId)-\(room.avatarVersion ?? "")"
let allowedCharacters = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "-_"))
let fileName = String(name.unicodeScalars.map { allowedCharacters.contains($0) ? Character($0) : "_" })
return "\(fileName).png"
}
private func loadMissingAvatars(for rooms: [NCRoom]) {
guard let avatarsDirectoryURL = ConversationsWidgetData.avatarsDirectoryURL(appGroupIdentifier: groupIdentifier) else { return }
for room in rooms {
let fileName = self.avatarFileName(for: room)
let fileURL = avatarsDirectoryURL.appendingPathComponent(fileName)
guard !FileManager.default.fileExists(atPath: fileURL.path), !avatarsBeingLoaded.contains(fileName) else { continue }
avatarsBeingLoaded.insert(fileName)
_ = AvatarManager.shared.getAvatar(for: room, with: .light) { [weak self] image in
DispatchQueue.main.async {
guard let self else { return }
self.avatarsBeingLoaded.remove(fileName)
guard let image, let pngData = self.resizedAvatar(image).pngData() else { return }
do {
try FileManager.default.createDirectory(at: avatarsDirectoryURL, withIntermediateDirectories: true)
try pngData.write(to: fileURL, options: [.atomic, .noFileProtection])
self.setNeedsUpdate()
} catch {
NCLog.log("Could not save widget avatar: \(error.localizedDescription)")
}
}
}
}
}
private func resizedAvatar(_ image: UIImage) -> UIImage {
let format = UIGraphicsImageRendererFormat()
format.scale = 1
return UIGraphicsImageRenderer(size: avatarSize, format: format).image { _ in
image.draw(in: CGRect(origin: .zero, size: avatarSize))
}
}
private func removeUnusedAvatars(keeping fileNames: Set<String>) {
guard let avatarsDirectoryURL = ConversationsWidgetData.avatarsDirectoryURL(appGroupIdentifier: groupIdentifier),
let storedFileNames = try? FileManager.default.contentsOfDirectory(atPath: avatarsDirectoryURL.path)
else { return }
for storedFileName in storedFileNames where !fileNames.contains(storedFileName) {
try? FileManager.default.removeItem(at: avatarsDirectoryURL.appendingPathComponent(storedFileName))
}
}
}
@@ -150,6 +150,7 @@ class RoomsTableViewController: UITableViewController, CCCertificateDelegate, UI
notificationCenter.addObserver(self, selector: #selector(appStateHasChanged(_:)), name: .NCAppStateHasChangedNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(connectionStateHasChanged(_:)), name: .NCConnectionStateHasChangedNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(roomsDidUpdate(_:)), name: .NCRoomsManagerDidUpdateRooms, object: nil)
notificationCenter.addObserver(self, selector: #selector(userStatusDidChangeFromWidget), name: .TalkWidgetActionsDidChangeUserStatus, object: nil)
notificationCenter.addObserver(self, selector: #selector(notificationWillBePresented(_:)), name: .NCNotificationControllerWillPresent, object: nil)
notificationCenter.addObserver(self, selector: #selector(serverCapabilitiesUpdated(_:)), name: .NCServerCapabilitiesUpdated, object: nil)
notificationCenter.addObserver(self, selector: #selector(userProfileImageUpdated(_:)), name: .NCUserProfileImageUpdated, object: nil)
@@ -277,6 +278,11 @@ class RoomsTableViewController: UITableViewController, CCCertificateDelegate, UI
return false
}
// E.g. from the control in Control Center
func presentNewConversation() {
self.presentNewRoomViewController()
}
@objc private func presentNewRoomViewController() {
let activeAccount = NCDatabaseManager.sharedInstance().activeAccount()
let newRoomVC = NewRoomTableViewController(account: activeAccount)
@@ -547,6 +553,7 @@ class RoomsTableViewController: UITableViewController, CCCertificateDelegate, UI
self.activeUserStatus = userStatus
self.updateProfileButtonImage()
TalkWidgetActions.userStatusDidChange(userStatus.status)
completion([onlineOption])
}
@@ -1367,12 +1374,18 @@ class RoomsTableViewController: UITableViewController, CCCertificateDelegate, UI
}
}
// The status was changed in a widget or in Control Center
@objc private func userStatusDidChangeFromWidget() {
self.updateUserStatus()
}
private func updateUserStatus() {
let activeAccount = NCDatabaseManager.sharedInstance().activeAccount()
NCAPIController.sharedInstance().getUserStatus(forAccount: activeAccount) { [weak self] userStatus in
if let userStatus {
self?.activeUserStatus = userStatus
self?.updateProfileButtonImage()
TalkWidgetActions.userStatusDidChange(userStatus.status)
}
}
}
@@ -1485,6 +1498,7 @@ class RoomsTableViewController: UITableViewController, CCCertificateDelegate, UI
}
private func addRoomToFavorites(_ room: NCRoom) {
HapticFeedback.selection()
NCAPIController.sharedInstance().addRoomToFavorites(room.token, forAccount: NCDatabaseManager.sharedInstance().activeAccount()) { error in
if let error {
NSLog("Error adding room to favorites: %@", error.description)
@@ -1494,6 +1508,7 @@ class RoomsTableViewController: UITableViewController, CCCertificateDelegate, UI
}
private func removeRoomFromFavorites(_ room: NCRoom) {
HapticFeedback.selection()
NCAPIController.sharedInstance().removeRoomFromFavorites(room.token, forAccount: NCDatabaseManager.sharedInstance().activeAccount()) { error in
if let error {
NSLog("Error removing room from favorites: %@", error.description)
+132
View File
@@ -0,0 +1,132 @@
//
// SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
// SPDX-License-Identifier: GPL-3.0-or-later
//
import UIKit
import WidgetKit
// Performs the actions of the widget buttons and the Control Center controls (see TalkWidgetIntents)
// and keeps the state they show up to date (see TalkControlsState).
enum TalkWidgetActions {
// MARK: - Actions
@available(iOS 17.0, *)
static func markConversationAsRead(server: String, userId: String, token: String) async throws {
guard let account = NCDatabaseManager.sharedInstance().talkAccount(forUserId: userId, inServer: server) else {
throw TalkIntentError.message(NSLocalizedString("Account not found", comment: ""))
}
// Update the widget right away, the server is asked afterwards
await MainActor.run {
if let data = ConversationsWidgetData.load(appGroupIdentifier: groupIdentifier) {
try? data.markingAsRead(token: token).save(appGroupIdentifier: groupIdentifier)
WidgetCenter.shared.reloadTimelines(ofKind: ConversationsWidgetData.conversationsWidgetKind)
WidgetCenter.shared.reloadTimelines(ofKind: ConversationsWidgetData.unreadWidgetKind)
}
}
let lastMessageId = NCDatabaseManager.sharedInstance().room(withToken: token, forAccountId: account.accountId)?.lastMessage?.messageId ?? 0
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
NCAPIController.sharedInstance().setChatReadMarker(lastMessageId, inRoom: token, forAccount: account) { error in
if let error {
continuation.resume(throwing: error)
} else {
continuation.resume()
}
}
}
// Also updates the widgets with the real state
NCRoomsManager.shared.updateRooms(updatingUserStatus: false, onlyLastModified: false)
}
@available(iOS 17.0, *)
static func setUserStatus(_ status: String) async throws {
guard NCDatabaseManager.sharedInstance().numberOfAccounts() > 0 else {
throw TalkIntentError.message(NSLocalizedString("Account not found", comment: ""))
}
let account = NCDatabaseManager.sharedInstance().activeAccount()
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
NCAPIController.sharedInstance().setUserStatus(status, forAccount: account) { error in
if let error {
continuation.resume(throwing: error)
} else {
continuation.resume()
}
}
}
await MainActor.run {
self.userStatusDidChange(status)
NotificationCenter.default.post(name: .TalkWidgetActionsDidChangeUserStatus, object: nil)
}
}
@MainActor
static func setMicrophoneMuted(_ muted: Bool) {
NCRoomsManager.shared.callViewController?.setMicrophoneMutedFromControl(muted)
}
@MainActor
static func presentNewConversation() {
guard NCDatabaseManager.sharedInstance().numberOfAccounts() > 0 else { return }
NCUserInterfaceController.sharedInstance().presentNewConversation()
}
// MARK: - State
@MainActor
static func callDidChange(isInCall: Bool, isMicrophoneMuted: Bool) {
self.updateState { state in
state.isInCall = isInCall
state.isMicrophoneMuted = isInCall && isMicrophoneMuted
}
}
@MainActor
static func userStatusDidChange(_ status: String?) {
self.updateState { state in
state.userStatus = status
}
}
@MainActor
static func accountsDidChange() {
guard NCDatabaseManager.sharedInstance().numberOfAccounts() == 0 else { return }
TalkControlsState.remove(appGroupIdentifier: groupIdentifier)
self.reloadControls()
}
@MainActor
private static func updateState(_ change: (inout TalkControlsState) -> Void) {
var state = TalkControlsState.load(appGroupIdentifier: groupIdentifier)
let previousState = state
change(&state)
guard state != previousState else { return }
state.save(appGroupIdentifier: groupIdentifier)
self.reloadControls()
}
@MainActor
private static func reloadControls() {
if #available(iOS 18.0, *) {
ControlCenter.shared.reloadControls(ofKind: TalkControlsState.muteMicrophoneControlKind)
ControlCenter.shared.reloadControls(ofKind: TalkControlsState.doNotDisturbControlKind)
}
WidgetCenter.shared.reloadTimelines(ofKind: TalkControlsState.statusWidgetKind)
}
}
extension Notification.Name {
static let TalkWidgetActionsDidChangeUserStatus = Notification.Name("TalkWidgetActionsDidChangeUserStatus")
}
@@ -432,6 +432,10 @@ public class NCSettingsController: NSObject {
NCRoomsManager.shared.chatViewController?.leaveChat()
self.createAccountsFile()
// Don't keep showing the conversations of the removed account
ConversationsWidgetController.shared.setNeedsUpdate()
ConversationsSpotlightIndexer.shared.setNeedsUpdate()
// Activate any of the inactive accounts
self.switchToAnyInactiveAccount()
@@ -0,0 +1,136 @@
//
// SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
// SPDX-License-Identifier: GPL-3.0-or-later
//
import UIKit
// Small, purely decorative animations in the chat.
// All effects are skipped when "Reduce Motion" is enabled.
@MainActor
enum ChatEffects {
// MARK: - Celebration
// Emojis that let it rain confetti. Only emojis, so it works the same in every language.
static let celebrationEmojis: Set<Character> = ["🎉", "🥳", "🎊", "🎂"]
static func isCelebration(_ messageText: String?) -> Bool {
guard let messageText else { return false }
return messageText.contains { celebrationEmojis.contains($0) }
}
/// Lets confetti fall from the top of the view for a moment. The view is removed again afterwards.
static func showConfetti(in view: UIView) {
guard !UIAccessibility.isReduceMotionEnabled else { return }
let confettiView = UIView(frame: view.bounds)
confettiView.isUserInteractionEnabled = false
confettiView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
confettiView.accessibilityElementsHidden = true
view.addSubview(confettiView)
let emitter = CAEmitterLayer()
emitter.emitterPosition = CGPoint(x: view.bounds.midX, y: -10)
emitter.emitterShape = .line
emitter.emitterSize = CGSize(width: view.bounds.width, height: 1)
emitter.beginTime = CACurrentMediaTime()
let colors: [UIColor] = [.systemRed, .systemOrange, .systemYellow, .systemGreen, .systemBlue, .systemPurple, .systemPink]
let confettiImage = self.confettiPieceImage()
emitter.emitterCells = colors.map { color in
let cell = CAEmitterCell()
cell.contents = confettiImage
cell.color = color.cgColor
cell.birthRate = 10
cell.lifetime = 6
cell.velocity = 180
cell.velocityRange = 60
cell.emissionLongitude = .pi
cell.emissionRange = .pi / 6
cell.yAcceleration = 120
cell.spin = 3
cell.spinRange = 4
cell.scale = 0.6
cell.scaleRange = 0.3
cell.alphaSpeed = -0.12
return cell
}
confettiView.layer.addSublayer(emitter)
// Stop emitting new pieces after a short burst, then remove the view once all pieces are gone
DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) {
emitter.birthRate = 0
}
DispatchQueue.main.asyncAfter(deadline: .now() + 6) {
confettiView.removeFromSuperview()
}
}
private static func confettiPieceImage() -> CGImage? {
let size = CGSize(width: 8, height: 12)
return UIGraphicsImageRenderer(size: size).image { context in
UIColor.white.setFill()
context.fill(CGRect(origin: .zero, size: size))
}.cgImage
}
// MARK: - Reaction burst
/// Shows the emoji growing at the given point, while smaller copies of it fly outwards.
static func showReactionBurst(_ emoji: String, at point: CGPoint, in view: UIView) {
guard !UIAccessibility.isReduceMotionEnabled else { return }
let mainLabel = self.emojiLabel(emoji, fontSize: 56)
mainLabel.center = point
mainLabel.transform = CGAffineTransform(scaleX: 0.3, y: 0.3)
view.addSubview(mainLabel)
UIView.animate(withDuration: 0.35, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.8) {
mainLabel.transform = .identity
} completion: { _ in
UIView.animate(withDuration: 0.4, delay: 0.15, options: .curveEaseIn) {
mainLabel.transform = CGAffineTransform(translationX: 0, y: -40).scaledBy(x: 0.6, y: 0.6)
mainLabel.alpha = 0
} completion: { _ in
mainLabel.removeFromSuperview()
}
}
let particleCount = 6
for index in 0..<particleCount {
let particleLabel = self.emojiLabel(emoji, fontSize: 20)
particleLabel.center = point
particleLabel.alpha = 0.9
view.addSubview(particleLabel)
let angle = (CGFloat(index) / CGFloat(particleCount)) * 2 * .pi + CGFloat.random(in: -0.3...0.3)
let distance = CGFloat.random(in: 50...80)
let translation = CGAffineTransform(translationX: cos(angle) * distance, y: sin(angle) * distance)
UIView.animate(withDuration: 0.6, delay: 0.05, options: .curveEaseOut) {
particleLabel.transform = translation.scaledBy(x: 0.5, y: 0.5)
particleLabel.alpha = 0
} completion: { _ in
particleLabel.removeFromSuperview()
}
}
}
private static func emojiLabel(_ emoji: String, fontSize: CGFloat) -> UILabel {
let label = UILabel()
label.text = emoji
label.font = .systemFont(ofSize: fontSize)
label.isUserInteractionEnabled = false
label.isAccessibilityElement = false
label.sizeToFit()
return label
}
}
@@ -0,0 +1,50 @@
//
// SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
// SPDX-License-Identifier: GPL-3.0-or-later
//
import UIKit
// Central place for haptic feedback, so the same kind of action feels the same everywhere in the app.
// UIFeedbackGenerator respects the system haptics setting, there's no need for an additional check here.
@MainActor
enum HapticFeedback {
private static let lightImpactGenerator = UIImpactFeedbackGenerator(style: .light)
private static let mediumImpactGenerator = UIImpactFeedbackGenerator(style: .medium)
private static let rigidImpactGenerator = UIImpactFeedbackGenerator(style: .rigid)
private static let selectionGenerator = UISelectionFeedbackGenerator()
private static let notificationGenerator = UINotificationFeedbackGenerator()
/// A small tap, e.g. when sending a message or toggling a call button
static func light() {
lightImpactGenerator.impactOccurred()
}
/// A more noticeable tap for actions with a bigger effect, e.g. leaving a call
static func medium() {
mediumImpactGenerator.impactOccurred()
}
/// A short, firm tap for something snapping into place, e.g. locking a voice recording
static func rigid() {
rigidImpactGenerator.impactOccurred()
}
/// A tick for changing a selection or toggling a state, e.g. adding a conversation to favorites
static func selection() {
selectionGenerator.selectionChanged()
}
static func success() {
notificationGenerator.notificationOccurred(.success)
}
static func warning() {
notificationGenerator.notificationOccurred(.warning)
}
static func error() {
notificationGenerator.notificationOccurred(.error)
}
}
@@ -233,6 +233,18 @@ public typealias PresentCallControllerCompletionBlock = () -> Void
}
}
func presentNewConversation() {
// Not while in a call, the call view would be dismissed
guard NCRoomsManager.shared.callViewController == nil else { return }
mainViewController.dismiss(animated: true) { [weak self] in
guard let self else { return }
self.popToConversationsList()
self.roomsTableViewController.presentNewConversation()
}
}
func presentAlertViewController(_ alertViewController: UIAlertController) {
if let presentedViewController = mainViewController.presentedViewController, !presentedViewController.isBeingDismissed {
// When the callview is presented, we need to show the alert this way
@@ -52,6 +52,9 @@ public class NCPeerConnection: NSObject {
var showRemoteVideoInOriginalSize = false
var addedTime: Int = 0
var selectedSimulcastVideoQuality: SimulcastVideoQuality?
// The highest video quality we send, lowered while the device is hot or in Low Power Mode
var maxSendVideoQuality: SimulcastVideoQuality = .high
private var appliedMaxSendVideoQuality: SimulcastVideoQuality = .high
var isRemoteVideoBlockedInMCU = false
// Keys of the remote participant, set for end-to-end encrypted calls before any media is received
@@ -422,11 +425,65 @@ public class NCPeerConnection: NSObject {
disableSimulcastIfUnsupported()
}
// The codec is only known now, so a limit that was set before can be applied now
applyMaxSendVideoQuality()
if peerConnection?.remoteDescription != nil {
drainRemoteCandidates()
}
}
func applyMaxSendVideoQuality() {
WebRTCCommon.shared.assertQueue()
// Screen shares need to stay readable, they are not limited
guard roomType == kRoomTypeVideo,
maxSendVideoQuality != .high || appliedMaxSendVideoQuality != .high
else { return }
for transceiver in peerConnection?.transceivers ?? [] where transceiver.mediaType == .video {
let parameters = transceiver.sender.parameters
if NCPeerConnection.limitSendEncodings(parameters.encodings, withCodec: parameters.codecs.first?.name, to: maxSendVideoQuality) {
transceiver.sender.parameters = parameters
}
}
appliedMaxSendVideoQuality = maxSendVideoQuality
}
// Returns false, when the encodings could not be limited (yet)
static func limitSendEncodings(_ encodings: [RTCRtpEncodingParameters], withCodec codecName: String?, to quality: SimulcastVideoQuality) -> Bool {
guard !encodings.isEmpty else { return false }
if encodings.count > 1 {
// Before the negotiation finished it's unknown whether simulcast is used
guard let codecName else { return false }
if codecName.caseInsensitiveCompare(kRTCVideoCodecVp8Name) == .orderedSame {
// The layers are ordered from lowest to highest, so their index matches the quality
for (index, encoding) in encodings.enumerated() {
encoding.isActive = index <= quality.rawValue
}
return true
}
}
// A single stream (no simulcast, or only the highest layer active) can only be scaled down
let scaleResolutionDownBy: Double = switch quality {
case .low: 4
case .medium: 2
case .high: 1
}
for encoding in encodings where encoding.isActive {
encoding.scaleResolutionDownBy = NSNumber(value: scaleResolutionDownBy)
}
return true
}
// Only the VP8 encoder supports simulcast, others encode a single stream
private func disableSimulcastIfUnsupported() {
for transceiver in peerConnection?.transceivers ?? [] where transceiver.mediaType == .video {
@@ -0,0 +1,81 @@
//
// SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
// SPDX-License-Identifier: GPL-3.0-or-later
//
import XCTest
import WebRTC
@testable import NextcloudTalk
final class UnitCallPerformanceTest: XCTestCase {
func testMaxVideoQuality() {
func maxVideoQuality(_ thermalState: ProcessInfo.ThermalState, _ lowPower: Bool) -> SimulcastVideoQuality {
return CallPerformanceMonitor.maxVideoQuality(thermalState: thermalState, isLowPowerModeEnabled: lowPower).quality
}
XCTAssertEqual(maxVideoQuality(.nominal, false), .high)
XCTAssertEqual(maxVideoQuality(.fair, false), .high)
XCTAssertEqual(maxVideoQuality(.nominal, true), .medium)
XCTAssertEqual(maxVideoQuality(.serious, false), .medium)
XCTAssertEqual(maxVideoQuality(.serious, true), .medium)
XCTAssertEqual(maxVideoQuality(.critical, false), .low)
XCTAssertEqual(maxVideoQuality(.critical, true), .low)
XCTAssertEqual(CallPerformanceMonitor.maxVideoQuality(thermalState: .serious, isLowPowerModeEnabled: true).reason, .thermalState)
XCTAssertEqual(CallPerformanceMonitor.maxVideoQuality(thermalState: .fair, isLowPowerModeEnabled: true).reason, .lowPowerMode)
}
private func simulcastEncodings() -> [RTCRtpEncodingParameters] {
return [4.0, 2.0, 1.0].map { scale in
let encoding = RTCRtpEncodingParameters()
encoding.scaleResolutionDownBy = NSNumber(value: scale)
encoding.isActive = true
return encoding
}
}
func testLimitSimulcastEncodings() {
let encodings = simulcastEncodings()
XCTAssertTrue(NCPeerConnection.limitSendEncodings(encodings, withCodec: kRTCVideoCodecVp8Name, to: .medium))
XCTAssertEqual(encodings.map(\.isActive), [true, true, false])
// The layers themselves are not scaled, only switched off
XCTAssertEqual(encodings.map { $0.scaleResolutionDownBy?.doubleValue }, [4, 2, 1])
XCTAssertTrue(NCPeerConnection.limitSendEncodings(encodings, withCodec: kRTCVideoCodecVp8Name, to: .low))
XCTAssertEqual(encodings.map(\.isActive), [true, false, false])
XCTAssertTrue(NCPeerConnection.limitSendEncodings(encodings, withCodec: kRTCVideoCodecVp8Name, to: .high))
XCTAssertEqual(encodings.map(\.isActive), [true, true, true])
}
func testLimitSimulcastEncodingsBeforeNegotiation() {
let encodings = simulcastEncodings()
XCTAssertFalse(NCPeerConnection.limitSendEncodings(encodings, withCodec: nil, to: .low))
XCTAssertEqual(encodings.map(\.isActive), [true, true, true])
}
func testLimitSingleStream() {
let encoding = RTCRtpEncodingParameters()
encoding.isActive = true
XCTAssertTrue(NCPeerConnection.limitSendEncodings([encoding], withCodec: nil, to: .medium))
XCTAssertEqual(encoding.scaleResolutionDownBy?.doubleValue, 2)
XCTAssertTrue(NCPeerConnection.limitSendEncodings([encoding], withCodec: nil, to: .high))
XCTAssertEqual(encoding.scaleResolutionDownBy?.doubleValue, 1)
}
func testLimitSimulcastWithUnsupportedCodec() {
// Only the highest layer is active without VP8, see disableSimulcastIfUnsupported
let encodings = simulcastEncodings()
encodings[0].isActive = false
encodings[1].isActive = false
XCTAssertTrue(NCPeerConnection.limitSendEncodings(encodings, withCodec: kRTCVideoCodecH264Name, to: .low))
XCTAssertEqual(encodings.map(\.isActive), [false, false, true])
XCTAssertEqual(encodings.map { $0.scaleResolutionDownBy?.doubleValue }, [4, 2, 4])
}
}
@@ -0,0 +1,21 @@
//
// SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
// SPDX-License-Identifier: GPL-3.0-or-later
//
import XCTest
@testable import NextcloudTalk
final class UnitChatEffectsTest: XCTestCase {
@MainActor
func testCelebrationDetection() {
XCTAssertTrue(ChatEffects.isCelebration("Happy birthday 🎂"))
XCTAssertTrue(ChatEffects.isCelebration("🎉"))
XCTAssertTrue(ChatEffects.isCelebration("We shipped it 🥳🥳"))
XCTAssertFalse(ChatEffects.isCelebration("Happy birthday"))
XCTAssertFalse(ChatEffects.isCelebration("👍"))
XCTAssertFalse(ChatEffects.isCelebration(""))
XCTAssertFalse(ChatEffects.isCelebration(nil))
}
}
@@ -0,0 +1,38 @@
//
// SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
// SPDX-License-Identifier: GPL-3.0-or-later
//
import XCTest
@testable import NextcloudTalk
final class UnitConversationsWidgetDataTest: XCTestCase {
private let conversation = ConversationsWidgetData.Conversation(id: "account@token", token: "abc123", displayName: "Design & Dev",
unreadMessages: 2, unreadMention: true, isFavorite: true,
hasCall: false, avatarFileName: nil)
func testOpenURL() throws {
let data = ConversationsWidgetData(server: "https://cloud.example.com/sub", userId: "alice smith", conversations: [conversation],
unreadConversations: 1, unreadMentions: 1)
let url = try XCTUnwrap(data.openURL(for: conversation))
let components = try XCTUnwrap(NSURLComponents(url: url, resolvingAgainstBaseURL: false))
let queryItems = (components.queryItems ?? []) as NSArray
XCTAssertEqual(components.scheme, "nextcloudtalk")
XCTAssertEqual(components.host, "open-conversation")
XCTAssertEqual(NCUtils.value(forKey: "server", fromQueryItems: queryItems), "https://cloud.example.com/sub")
XCTAssertEqual(NCUtils.value(forKey: "user", fromQueryItems: queryItems), "alice smith")
XCTAssertEqual(NCUtils.value(forKey: "withRoomToken", fromQueryItems: queryItems), "abc123")
}
func testCodableRoundTrip() throws {
let data = ConversationsWidgetData(server: "https://cloud.example.com", userId: "alice", conversations: [conversation],
unreadConversations: 1, unreadMentions: 1)
let decoded = try JSONDecoder().decode(ConversationsWidgetData.self, from: JSONEncoder().encode(data))
XCTAssertEqual(decoded, data)
}
}
@@ -0,0 +1,48 @@
//
// SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
// SPDX-License-Identifier: GPL-3.0-or-later
//
import XCTest
@testable import NextcloudTalk
final class UnitInteractiveWidgetsTest: XCTestCase {
func testMarkingAsReadInWidgetData() {
let unreadMention = ConversationsWidgetData.Conversation(id: "1", token: "t1", displayName: "Design", unreadMessages: 3, unreadMention: true,
isFavorite: true, hasCall: false, avatarFileName: "a.png")
let unread = ConversationsWidgetData.Conversation(id: "2", token: "t2", displayName: "Bob", unreadMessages: 1, unreadMention: false,
isFavorite: false, hasCall: true, avatarFileName: nil)
let data = ConversationsWidgetData(server: "https://cloud.example.com", userId: "alice", conversations: [unreadMention, unread],
unreadConversations: 2, unreadMentions: 1)
let markedAsRead = data.markingAsRead(token: "t1")
XCTAssertEqual(markedAsRead.conversations[0].unreadMessages, 0)
XCTAssertFalse(markedAsRead.conversations[0].unreadMention)
XCTAssertEqual(markedAsRead.conversations[0].avatarFileName, "a.png")
XCTAssertEqual(markedAsRead.conversations[1], unread)
XCTAssertEqual(markedAsRead.unreadConversations, 1)
XCTAssertEqual(markedAsRead.unreadMentions, 0)
// Already read or unknown conversations change nothing
XCTAssertEqual(markedAsRead.markingAsRead(token: "t1"), markedAsRead)
XCTAssertEqual(data.markingAsRead(token: "unknown"), data)
}
func testControlsStateRoundTrip() {
let suiteName = "UnitSystemIntegrationTest"
defer { UserDefaults().removePersistentDomain(forName: suiteName) }
XCTAssertEqual(TalkControlsState.load(appGroupIdentifier: suiteName), TalkControlsState())
let state = TalkControlsState(isInCall: true, isMicrophoneMuted: true, userStatus: "dnd")
state.save(appGroupIdentifier: suiteName)
XCTAssertEqual(TalkControlsState.load(appGroupIdentifier: suiteName), state)
TalkControlsState.remove(appGroupIdentifier: suiteName)
XCTAssertEqual(TalkControlsState.load(appGroupIdentifier: suiteName), TalkControlsState())
}
}
+291
View File
@@ -0,0 +1,291 @@
//
// SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
// SPDX-License-Identifier: GPL-3.0-or-later
//
import SwiftUI
import WidgetKit
// Home screen widget with the favorite conversations, filled up with the most recent ones
struct ConversationsWidget: Widget {
var body: some WidgetConfiguration {
StaticConfiguration(kind: ConversationsWidgetData.conversationsWidgetKind, provider: ConversationsProvider()) { entry in
ConversationsWidgetView(entry: entry)
.widgetBackground { Color(UIColor.systemBackground) }
}
.configurationDisplayName(NSLocalizedString("Conversations", comment: "Name of the widget"))
.description(NSLocalizedString("Your favorite and most recent conversations.", comment: "Description of the conversations widget"))
.supportedFamilies([.systemSmall, .systemMedium, .systemLarge])
}
}
struct ConversationsWidgetView: View {
@Environment(\.widgetFamily) private var family
let entry: ConversationsEntry
var body: some View {
if let data = entry.data {
switch family {
case .systemSmall:
SmallConversationsView(data: data)
case .systemMedium:
ConversationsGridView(data: data, conversations: Array(data.conversations.prefix(4)))
default:
ConversationsListView(data: data, conversations: Array(data.conversations.prefix(6)))
}
} else {
Text(NSLocalizedString("Log in to Nextcloud Talk to see your conversations here", comment: "Shown in a widget, when no account is logged in"))
.font(.footnote)
.foregroundColor(.secondary)
.multilineTextAlignment(.center)
}
}
}
// MARK: - Small
struct SmallConversationsView: View {
let data: ConversationsWidgetData
var body: some View {
VStack(alignment: .leading, spacing: 6) {
HStack {
Image(systemName: "bubble.left.and.bubble.right.fill")
.foregroundColor(.talkAccent)
Spacer()
if data.unreadMentions > 0 {
UnreadBadge(text: "@", isMention: true)
}
}
Text("\(data.unreadConversations)")
.font(.system(size: 34, weight: .bold, design: .rounded))
.minimumScaleFactor(0.6)
Text(NSLocalizedString("Unread conversations", comment: "Shown in a widget below the number of conversations with unread messages"))
.font(.caption)
.foregroundColor(.secondary)
.lineLimit(2)
Spacer(minLength: 0)
// The most recent unread conversation, or the first favorite
if let conversation = data.conversations.first(where: { $0.unreadMessages > 0 }) ?? data.conversations.first {
Text(conversation.displayName)
.font(.footnote.weight(.semibold))
.lineLimit(1)
.privacySensitive()
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
}
}
// MARK: - Medium
struct ConversationsGridView: View {
let data: ConversationsWidgetData
let conversations: [ConversationsWidgetData.Conversation]
var body: some View {
if conversations.isEmpty {
NoConversationsView()
} else {
HStack(alignment: .top, spacing: 8) {
ForEach(conversations) { conversation in
ConversationLink(url: data.openURL(for: conversation)) {
VStack(spacing: 6) {
ConversationAvatar(conversation: conversation, size: 52)
.overlay(alignment: .topTrailing) {
if conversation.unreadMessages > 0 {
UnreadBadge(conversation: conversation)
.offset(x: 6, y: -4)
}
}
Text(conversation.displayName)
.font(.caption)
.lineLimit(2)
.multilineTextAlignment(.center)
.privacySensitive()
}
.frame(maxWidth: .infinity)
}
}
}
}
}
}
// MARK: - Large
struct ConversationsListView: View {
let data: ConversationsWidgetData
let conversations: [ConversationsWidgetData.Conversation]
var body: some View {
VStack(alignment: .leading, spacing: 10) {
HStack {
Image(systemName: "bubble.left.and.bubble.right.fill")
.foregroundColor(.talkAccent)
Text(NSLocalizedString("Conversations", comment: ""))
.font(.headline)
Spacer()
}
if conversations.isEmpty {
NoConversationsView()
} else {
ForEach(conversations) { conversation in
HStack(spacing: 8) {
ConversationLink(url: data.openURL(for: conversation)) {
HStack(spacing: 10) {
ConversationAvatar(conversation: conversation, size: 36)
Text(conversation.displayName)
.font(.subheadline.weight(conversation.unreadMessages > 0 ? .semibold : .regular))
.lineLimit(1)
.privacySensitive()
Spacer(minLength: 4)
if conversation.hasCall {
Image(systemName: "video.fill")
.foregroundColor(.green)
.font(.caption)
}
if conversation.isFavorite {
Image(systemName: "star.fill")
.foregroundColor(.yellow)
.font(.caption2)
}
if conversation.unreadMessages > 0 {
UnreadBadge(conversation: conversation)
}
}
}
if conversation.unreadMessages > 0 {
MarkAsReadButton(data: data, conversation: conversation)
}
}
}
}
Spacer(minLength: 0)
}
}
}
// MARK: - Components
// Marks a conversation as read without opening the app (iOS 17 and later)
struct MarkAsReadButton: View {
let data: ConversationsWidgetData
let conversation: ConversationsWidgetData.Conversation
var body: some View {
if #available(iOSApplicationExtension 17.0, *) {
Button(intent: WidgetMarkAsReadIntent(server: data.server, userId: data.userId, token: conversation.token)) {
Image(systemName: "checkmark.circle")
.font(.body)
.foregroundColor(.talkAccent)
}
.buttonStyle(.plain)
.accessibilityLabel(NSLocalizedString("Mark as read", comment: ""))
}
}
}
struct ConversationLink<Content: View>: View {
let url: URL?
@ViewBuilder let content: () -> Content
var body: some View {
if let url {
Link(destination: url, label: content)
} else {
content()
}
}
}
struct NoConversationsView: View {
var body: some View {
Text(NSLocalizedString("No conversations yet", comment: "Shown in a widget"))
.font(.footnote)
.foregroundColor(.secondary)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
struct UnreadBadge: View {
let text: String
let isMention: Bool
init(text: String, isMention: Bool) {
self.text = text
self.isMention = isMention
}
init(conversation: ConversationsWidgetData.Conversation) {
self.text = conversation.unreadMessages > 99 ? "99+" : "\(conversation.unreadMessages)"
self.isMention = conversation.unreadMention
}
var body: some View {
Text(text)
.font(.caption2.weight(.bold))
.foregroundColor(isMention ? .white : .primary)
.padding(.horizontal, 6)
.padding(.vertical, 2)
.background(Capsule().fill(isMention ? Color.talkAccent : Color(UIColor.systemGray5)))
}
}
struct ConversationAvatar: View {
let conversation: ConversationsWidgetData.Conversation
let size: CGFloat
private static let colors: [Color] = [.blue, .green, .orange, .pink, .purple, .teal, .indigo, .red]
var body: some View {
Group {
if let image = WidgetStorage.avatar(named: conversation.avatarFileName) {
Image(uiImage: image)
.resizable()
.scaledToFill()
} else {
ZStack {
Self.colors[colorIndex]
Text(initials)
.font(.system(size: size * 0.4, weight: .semibold))
.foregroundColor(.white)
}
}
}
.frame(width: size, height: size)
.clipShape(Circle())
}
private var initials: String {
return conversation.displayName.split(separator: " ").prefix(2).compactMap(\.first).map(String.init).joined().uppercased()
}
// Stable over launches, unlike hashValue
private var colorIndex: Int {
return conversation.displayName.unicodeScalars.reduce(0) { $0 + Int($1.value) } % Self.colors.count
}
}
+103
View File
@@ -0,0 +1,103 @@
//
// SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
// SPDX-License-Identifier: GPL-3.0-or-later
//
import Foundation
// What the widgets show. The app writes it into the shared app group container whenever the
// conversations change and the widgets only read it, so they need neither network access nor the database.
// This file is part of the app and of the widget extension.
struct ConversationsWidgetData: Codable, Equatable {
struct Conversation: Codable, Equatable, Identifiable {
// The internalId of the room
let id: String
let token: String
let displayName: String
let unreadMessages: Int
let unreadMention: Bool
let isFavorite: Bool
let hasCall: Bool
// Name of the avatar image in the avatars directory, if it was stored already
let avatarFileName: String?
}
let server: String
let userId: String
let conversations: [Conversation]
let unreadConversations: Int
let unreadMentions: Int
static let conversationsWidgetKind = "ConversationsWidget"
static let unreadWidgetKind = "UnreadConversationsWidget"
private static let directoryName = "Widgets"
private static let dataFileName = "conversations.json"
private static let avatarsDirectoryName = "Avatars"
// Opens the conversation, same as a nextcloudtalk:// link from the web
func openURL(for conversation: Conversation) -> URL? {
var components = URLComponents()
components.scheme = "nextcloudtalk"
components.host = "open-conversation"
components.queryItems = [
URLQueryItem(name: "server", value: server),
URLQueryItem(name: "user", value: userId),
URLQueryItem(name: "withRoomToken", value: conversation.token)
]
return components.url
}
// The same data, but with the conversation shown as read, until the app has the real state from the server
func markingAsRead(token: String) -> ConversationsWidgetData {
guard let conversation = conversations.first(where: { $0.token == token }), conversation.unreadMessages > 0 else { return self }
let updatedConversations = conversations.map { conversation in
guard conversation.token == token else { return conversation }
return Conversation(id: conversation.id, token: conversation.token, displayName: conversation.displayName,
unreadMessages: 0, unreadMention: false, isFavorite: conversation.isFavorite,
hasCall: conversation.hasCall, avatarFileName: conversation.avatarFileName)
}
return ConversationsWidgetData(server: server, userId: userId, conversations: updatedConversations,
unreadConversations: max(0, unreadConversations - 1),
unreadMentions: max(0, unreadMentions - (conversation.unreadMention ? 1 : 0)))
}
// MARK: - Storage
static func directoryURL(appGroupIdentifier: String) -> URL? {
return FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroupIdentifier)?.appendingPathComponent(directoryName, isDirectory: true)
}
static func avatarsDirectoryURL(appGroupIdentifier: String) -> URL? {
return directoryURL(appGroupIdentifier: appGroupIdentifier)?.appendingPathComponent(avatarsDirectoryName, isDirectory: true)
}
static func load(appGroupIdentifier: String) -> ConversationsWidgetData? {
guard let fileURL = directoryURL(appGroupIdentifier: appGroupIdentifier)?.appendingPathComponent(dataFileName),
let data = try? Data(contentsOf: fileURL)
else { return nil }
return try? JSONDecoder().decode(ConversationsWidgetData.self, from: data)
}
func save(appGroupIdentifier: String) throws {
guard let directoryURL = Self.directoryURL(appGroupIdentifier: appGroupIdentifier) else { return }
try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true)
let data = try JSONEncoder().encode(self)
// The widget reads the file while the device is locked as well
try data.write(to: directoryURL.appendingPathComponent(Self.dataFileName), options: [.atomic, .noFileProtection])
}
static func remove(appGroupIdentifier: String) {
guard let directoryURL = directoryURL(appGroupIdentifier: appGroupIdentifier) else { return }
try? FileManager.default.removeItem(at: directoryURL)
}
}
+31
View File
@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleDisplayName</key>
<string>Talk</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
<key>CFBundleShortVersionString</key>
<string>$(MARKETING_VERSION)</string>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>NCAppGroupIdentifier</key>
<string>group.com.nextcloud.Talk</string>
<key>NSExtension</key>
<dict>
<key>NSExtensionPointIdentifier</key>
<string>com.apple.widgetkit-extension</string>
</dict>
</dict>
</plist>
+129
View File
@@ -0,0 +1,129 @@
//
// SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
// SPDX-License-Identifier: GPL-3.0-or-later
//
import SwiftUI
import WidgetKit
// Small home screen widget to see and change the user status with one tap (iOS 17 and later)
@available(iOS 17.0, *)
struct StatusWidget: Widget {
var body: some WidgetConfiguration {
StaticConfiguration(kind: TalkControlsState.statusWidgetKind, provider: StatusProvider()) { entry in
StatusWidgetView(entry: entry)
.containerBackground(for: .widget) { Color(UIColor.systemBackground) }
}
.configurationDisplayName(NSLocalizedString("Status", comment: "Name of the widget"))
.description(NSLocalizedString("See and change your status.", comment: "Description of the status widget"))
.supportedFamilies([.systemSmall])
}
}
struct StatusEntry: TimelineEntry {
let date: Date
let isLoggedIn: Bool
let status: String?
}
struct StatusProvider: TimelineProvider {
func placeholder(in context: Context) -> StatusEntry {
return StatusEntry(date: Date(), isLoggedIn: true, status: "online")
}
func getSnapshot(in context: Context, completion: @escaping (StatusEntry) -> Void) {
completion(self.currentEntry(isPreview: context.isPreview))
}
func getTimeline(in context: Context, completion: @escaping (Timeline<StatusEntry>) -> Void) {
// The app reloads the widget whenever the status changes
completion(Timeline(entries: [self.currentEntry(isPreview: false)], policy: .never))
}
private func currentEntry(isPreview: Bool) -> StatusEntry {
let isLoggedIn = WidgetStorage.loadData() != nil
let status = TalkControlsState.load(appGroupIdentifier: WidgetStorage.appGroupIdentifier).userStatus
if isPreview, !isLoggedIn {
return StatusEntry(date: Date(), isLoggedIn: true, status: "online")
}
return StatusEntry(date: Date(), isLoggedIn: isLoggedIn, status: status)
}
}
struct StatusOption: Identifiable {
let id: String
let title: String
let systemImage: String
let color: Color
static let all: [StatusOption] = [
StatusOption(id: "online", title: NSLocalizedString("Online", comment: "User status"), systemImage: "circle.fill", color: .green),
StatusOption(id: "away", title: NSLocalizedString("Away", comment: "User status"), systemImage: "moon.fill", color: .yellow),
StatusOption(id: "dnd", title: NSLocalizedString("Do not disturb", comment: "User status"), systemImage: "minus.circle.fill", color: .red),
StatusOption(id: "invisible", title: NSLocalizedString("Invisible", comment: "User status"), systemImage: "circle.dashed", color: .gray)
]
}
@available(iOS 17.0, *)
struct StatusWidgetView: View {
let entry: StatusEntry
var body: some View {
if !entry.isLoggedIn {
Text(NSLocalizedString("Log in to Nextcloud Talk to see your status here", comment: "Shown in a widget, when no account is logged in"))
.font(.footnote)
.foregroundColor(.secondary)
.multilineTextAlignment(.center)
} else {
VStack(alignment: .leading, spacing: 8) {
let current = StatusOption.all.first { $0.id == entry.status }
HStack(spacing: 6) {
Image(systemName: current?.systemImage ?? "circle")
.foregroundColor(current?.color ?? .secondary)
Text(current?.title ?? NSLocalizedString("Status", comment: ""))
.font(.footnote.weight(.semibold))
.lineLimit(1)
.minimumScaleFactor(0.7)
}
Grid(horizontalSpacing: 8, verticalSpacing: 8) {
GridRow {
StatusButton(option: StatusOption.all[0], isCurrent: entry.status == "online")
StatusButton(option: StatusOption.all[1], isCurrent: entry.status == "away")
}
GridRow {
StatusButton(option: StatusOption.all[2], isCurrent: entry.status == "dnd")
StatusButton(option: StatusOption.all[3], isCurrent: entry.status == "invisible")
}
}
}
}
}
}
@available(iOS 17.0, *)
private struct StatusButton: View {
let option: StatusOption
let isCurrent: Bool
var body: some View {
Button(intent: WidgetSetStatusIntent(status: option.id)) {
Image(systemName: option.systemImage)
.font(.title3)
.foregroundColor(option.color)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(RoundedRectangle(cornerRadius: 12, style: .continuous)
.fill(isCurrent ? option.color.opacity(0.25) : Color(UIColor.secondarySystemFill)))
}
.buttonStyle(.plain)
.accessibilityLabel(option.title)
.accessibilityAddTraits(isCurrent ? .isSelected : [])
}
}
+77
View File
@@ -0,0 +1,77 @@
//
// SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
// SPDX-License-Identifier: GPL-3.0-or-later
//
import AppIntents
import SwiftUI
import WidgetKit
// Controls for Control Center, the Lock Screen and the Action button (iOS 18 and later)
@available(iOS 18.0, *)
struct MuteMicrophoneControl: ControlWidget {
struct Provider: ControlValueProvider {
var previewValue: Bool { false }
func currentValue() async throws -> Bool {
let state = TalkControlsState.load(appGroupIdentifier: WidgetStorage.appGroupIdentifier)
return state.isInCall && state.isMicrophoneMuted
}
}
var body: some ControlWidgetConfiguration {
StaticControlConfiguration(kind: TalkControlsState.muteMicrophoneControlKind, provider: Provider()) { isMuted in
ControlWidgetToggle(isOn: isMuted, action: ControlMuteMicrophoneIntent()) {
Label(NSLocalizedString("Mute in call", comment: "Name of a control in Control Center"), systemImage: "mic.fill")
} valueLabel: { isOn in
Label(isOn ? NSLocalizedString("Muted", comment: "") : NSLocalizedString("Microphone on", comment: ""),
systemImage: isOn ? "mic.slash.fill" : "mic.fill")
}
.tint(.red)
}
.displayName(LocalizedStringResource("Mute in call"))
.description(LocalizedStringResource("Mutes or unmutes your microphone in a Nextcloud Talk call."))
}
}
@available(iOS 18.0, *)
struct DoNotDisturbControl: ControlWidget {
struct Provider: ControlValueProvider {
var previewValue: Bool { false }
func currentValue() async throws -> Bool {
return TalkControlsState.load(appGroupIdentifier: WidgetStorage.appGroupIdentifier).userStatus == "dnd"
}
}
var body: some ControlWidgetConfiguration {
StaticControlConfiguration(kind: TalkControlsState.doNotDisturbControlKind, provider: Provider()) { isOn in
ControlWidgetToggle(isOn: isOn, action: ControlDoNotDisturbIntent()) {
Label(NSLocalizedString("Do not disturb", comment: "User status"), systemImage: "minus.circle.fill")
} valueLabel: { isOn in
Label(isOn ? NSLocalizedString("Do not disturb", comment: "User status") : NSLocalizedString("Online", comment: "User status"),
systemImage: isOn ? "minus.circle.fill" : "circle.fill")
}
.tint(.red)
}
.displayName(LocalizedStringResource("Talk: Do not disturb"))
.description(LocalizedStringResource("Sets your Nextcloud status to Do not disturb, which mutes all notifications."))
}
}
@available(iOS 18.0, *)
struct NewConversationControl: ControlWidget {
var body: some ControlWidgetConfiguration {
StaticControlConfiguration(kind: TalkControlsState.newConversationControlKind) {
ControlWidgetButton(action: ControlNewConversationIntent()) {
Label(NSLocalizedString("New conversation", comment: "Name of a control in Control Center"), systemImage: "plus.bubble.fill")
}
}
.displayName(LocalizedStringResource("New conversation"))
.description(LocalizedStringResource("Opens Nextcloud Talk to start a new conversation."))
}
}
+43
View File
@@ -0,0 +1,43 @@
//
// SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
// SPDX-License-Identifier: GPL-3.0-or-later
//
import Foundation
// What the Control Center controls and the status widget show: whether there's a call and the
// microphone is muted, and the user status of the active account. The app writes it into the
// shared app group, the widget extension only reads it.
// This file is part of the app and of the widget extension.
struct TalkControlsState: Codable, Equatable {
var isInCall = false
var isMicrophoneMuted = false
// One of online, away, dnd, invisible or offline, nil when unknown or no account is logged in
var userStatus: String?
static let muteMicrophoneControlKind = "MuteMicrophoneControl"
static let doNotDisturbControlKind = "DoNotDisturbControl"
static let newConversationControlKind = "NewConversationControl"
static let statusWidgetKind = "StatusWidget"
private static let userDefaultsKey = "talkControlsState"
static func load(appGroupIdentifier: String) -> TalkControlsState {
guard let data = UserDefaults(suiteName: appGroupIdentifier)?.data(forKey: userDefaultsKey),
let state = try? JSONDecoder().decode(TalkControlsState.self, from: data)
else { return TalkControlsState() }
return state
}
func save(appGroupIdentifier: String) {
guard let data = try? JSONEncoder().encode(self) else { return }
UserDefaults(suiteName: appGroupIdentifier)?.set(data, forKey: Self.userDefaultsKey)
}
static func remove(appGroupIdentifier: String) {
UserDefaults(suiteName: appGroupIdentifier)?.removeObject(forKey: userDefaultsKey)
}
}
+114
View File
@@ -0,0 +1,114 @@
//
// SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
// SPDX-License-Identifier: GPL-3.0-or-later
//
import AppIntents
// Actions of the Control Center controls and of the buttons in the widgets.
// This file is part of the app and of the widget extension: the widget extension needs the types to show
// the controls and buttons, but has no access to the server. As LiveActivityIntents, they're performed in
// the app's process, which is launched in the background if needed (see TalkWidgetActions in the app).
@available(iOS 17.0, *)
struct WidgetMarkAsReadIntent: LiveActivityIntent {
static var title: LocalizedStringResource = "Mark conversation as read"
static var isDiscoverable = false
@Parameter(title: "Server")
var server: String
@Parameter(title: "User")
var userId: String
@Parameter(title: "Conversation")
var token: String
init() {}
init(server: String, userId: String, token: String) {
self.server = server
self.userId = userId
self.token = token
}
func perform() async throws -> some IntentResult {
#if !APP_EXTENSION
try await TalkWidgetActions.markConversationAsRead(server: server, userId: userId, token: token)
#endif
return .result()
}
}
@available(iOS 17.0, *)
struct WidgetSetStatusIntent: LiveActivityIntent {
static var title: LocalizedStringResource = "Set status"
static var isDiscoverable = false
// online, away, dnd or invisible
@Parameter(title: "Status")
var status: String
init() {}
init(status: String) {
self.status = status
}
func perform() async throws -> some IntentResult {
#if !APP_EXTENSION
try await TalkWidgetActions.setUserStatus(status)
#endif
return .result()
}
}
@available(iOS 18.0, *)
struct ControlMuteMicrophoneIntent: SetValueIntent, LiveActivityIntent {
static var title: LocalizedStringResource = "Mute microphone in call"
static var isDiscoverable = false
@Parameter(title: "Muted")
var value: Bool
init() {}
func perform() async throws -> some IntentResult {
#if !APP_EXTENSION
await TalkWidgetActions.setMicrophoneMuted(value)
#endif
return .result()
}
}
@available(iOS 18.0, *)
struct ControlDoNotDisturbIntent: SetValueIntent, LiveActivityIntent {
static var title: LocalizedStringResource = "Do not disturb"
static var isDiscoverable = false
@Parameter(title: "Do not disturb")
var value: Bool
init() {}
func perform() async throws -> some IntentResult {
#if !APP_EXTENSION
try await TalkWidgetActions.setUserStatus(value ? "dnd" : "online")
#endif
return .result()
}
}
@available(iOS 18.0, *)
struct ControlNewConversationIntent: LiveActivityIntent {
static var title: LocalizedStringResource = "New conversation"
static var isDiscoverable = false
static var openAppWhenRun = true
func perform() async throws -> some IntentResult {
#if !APP_EXTENSION
await TalkWidgetActions.presentNewConversation()
#endif
return .result()
}
}
+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.application-groups</key>
<array>
<string>group.com.nextcloud.Talk</string>
</array>
</dict>
</plist>
+108
View File
@@ -0,0 +1,108 @@
//
// SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
// SPDX-License-Identifier: GPL-3.0-or-later
//
import SwiftUI
import WidgetKit
@main
struct TalkWidgetsBundle: WidgetBundle {
var body: some Widget {
ConversationsWidget()
UnreadConversationsWidget()
if #available(iOSApplicationExtension 17.0, *) {
StatusWidget()
}
if #available(iOSApplicationExtension 18.0, *) {
MuteMicrophoneControl()
DoNotDisturbControl()
NewConversationControl()
}
}
}
// MARK: - Timeline
struct ConversationsEntry: TimelineEntry {
let date: Date
// Nil, when no account is logged in
let data: ConversationsWidgetData?
}
struct ConversationsProvider: TimelineProvider {
func placeholder(in context: Context) -> ConversationsEntry {
return ConversationsEntry(date: Date(), data: .preview)
}
func getSnapshot(in context: Context, completion: @escaping (ConversationsEntry) -> Void) {
// The widget gallery shows example conversations, until there are real ones
let data = WidgetStorage.loadData() ?? (context.isPreview ? .preview : nil)
completion(ConversationsEntry(date: Date(), data: data))
}
func getTimeline(in context: Context, completion: @escaping (Timeline<ConversationsEntry>) -> Void) {
// The app reloads the widgets whenever the conversations change, there's nothing to refresh on our own
let entry = ConversationsEntry(date: Date(), data: WidgetStorage.loadData())
completion(Timeline(entries: [entry], policy: .never))
}
}
// MARK: - Storage
enum WidgetStorage {
// Set in the Info.plist, as it differs for branded apps
static var appGroupIdentifier: String {
return Bundle.main.object(forInfoDictionaryKey: "NCAppGroupIdentifier") as? String ?? "group.com.nextcloud.Talk"
}
static func loadData() -> ConversationsWidgetData? {
return ConversationsWidgetData.load(appGroupIdentifier: appGroupIdentifier)
}
static func avatar(named fileName: String?) -> UIImage? {
guard let fileName,
let fileURL = ConversationsWidgetData.avatarsDirectoryURL(appGroupIdentifier: appGroupIdentifier)?.appendingPathComponent(fileName)
else { return nil }
return UIImage(contentsOfFile: fileURL.path)
}
}
// MARK: - Preview data
extension ConversationsWidgetData {
static let preview = ConversationsWidgetData(server: "", userId: "", conversations: [
.init(id: "1", token: "1", displayName: "Design team", unreadMessages: 3, unreadMention: true, isFavorite: true, hasCall: false, avatarFileName: nil),
.init(id: "2", token: "2", displayName: "Alice", unreadMessages: 1, unreadMention: false, isFavorite: true, hasCall: false, avatarFileName: nil),
.init(id: "3", token: "3", displayName: "Weekly sync", unreadMessages: 0, unreadMention: false, isFavorite: false, hasCall: true, avatarFileName: nil),
.init(id: "4", token: "4", displayName: "Bob", unreadMessages: 0, unreadMention: false, isFavorite: false, hasCall: false, avatarFileName: nil),
.init(id: "5", token: "5", displayName: "Support", unreadMessages: 12, unreadMention: false, isFavorite: false, hasCall: false, avatarFileName: nil),
.init(id: "6", token: "6", displayName: "Marketing", unreadMessages: 0, unreadMention: false, isFavorite: false, hasCall: false, avatarFileName: nil)
], unreadConversations: 3, unreadMentions: 1)
}
// MARK: - Helpers
extension Color {
// The Nextcloud blue
static let talkAccent = Color(red: 0, green: 130 / 255, blue: 201 / 255)
}
extension View {
// iOS 17 requires the widget background to be set like this, so it can be removed e.g. in StandBy
@ViewBuilder
func widgetBackground<Background: View>(@ViewBuilder _ background: () -> Background) -> some View {
if #available(iOSApplicationExtension 17.0, *) {
self.containerBackground(for: .widget, content: background)
} else {
self.background(background())
}
}
}
@@ -0,0 +1,60 @@
//
// SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
// SPDX-License-Identifier: GPL-3.0-or-later
//
import SwiftUI
import WidgetKit
// Lock screen widget with the number of unread conversations and mentions
struct UnreadConversationsWidget: Widget {
var body: some WidgetConfiguration {
StaticConfiguration(kind: ConversationsWidgetData.unreadWidgetKind, provider: ConversationsProvider()) { entry in
UnreadConversationsWidgetView(entry: entry)
.widgetBackground { Color.clear }
.widgetURL(URL(string: "nextcloudtalk://"))
}
.configurationDisplayName(NSLocalizedString("Unread conversations", comment: "Name of the widget"))
.description(NSLocalizedString("The number of conversations with unread messages and mentions.", comment: "Description of the unread conversations widget"))
.supportedFamilies([.accessoryCircular, .accessoryRectangular, .accessoryInline])
}
}
struct UnreadConversationsWidgetView: View {
@Environment(\.widgetFamily) private var family
let entry: ConversationsEntry
private var unreadConversations: Int { entry.data?.unreadConversations ?? 0 }
private var unreadMentions: Int { entry.data?.unreadMentions ?? 0 }
var body: some View {
switch family {
case .accessoryCircular:
ZStack {
AccessoryWidgetBackground()
VStack(spacing: 0) {
Image(systemName: unreadMentions > 0 ? "at" : "bubble.left.and.bubble.right.fill")
.font(.caption)
Text("\(unreadConversations)")
.font(.system(.title3, design: .rounded).weight(.semibold))
.minimumScaleFactor(0.5)
}
}
case .accessoryRectangular:
VStack(alignment: .leading, spacing: 2) {
Label("Talk", systemImage: "bubble.left.and.bubble.right.fill")
.font(.headline)
Text(String(format: NSLocalizedString("Unread: %ld", comment: "Number of conversations with unread messages"), unreadConversations))
Text(String(format: NSLocalizedString("Mentions: %ld", comment: "Number of conversations with unread mentions"), unreadMentions))
.foregroundColor(.secondary)
}
.frame(maxWidth: .infinity, alignment: .leading)
default:
Label(String(format: NSLocalizedString("Unread: %ld", comment: "Number of conversations with unread messages"), unreadConversations),
systemImage: "bubble.left.and.bubble.right.fill")
}
}
}